text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { AnimatePresence } from '@tamagui/animate-presence'
import { useComposedRefs } from '@tamagui/compose-refs'
import {
GetProps,
Slot,
Theme,
composeEventHandlers,
isWeb,
styled,
useId,
useThemeName,
withStaticProperties,
} from '@tamagui/core'
import { Scope, createContext, createContextScope } from '@tamagui/create-context'
import { Dismissable, DismissableProps } from '@tamagui/dismissable'
import { FocusScope, FocusScopeProps } from '@tamagui/focus-scope'
import { Portal, PortalProps } from '@tamagui/portal'
import { ThemeableStack, YStack, YStackProps } from '@tamagui/stacks'
import { H2, Paragraph } from '@tamagui/text'
import { useControllableState } from '@tamagui/use-controllable-state'
import * as React from 'react'
import { View } from 'react-native'
import { RemoveScroll } from 'react-remove-scroll'
// import { hideOthers } from 'aria-hidden';
const DIALOG_NAME = 'Dialog'
type ScopedProps<P> = P & { __scopeDialog?: Scope }
type TamaguiElement = HTMLElement | View
const [createDialogContext, createDialogScope] = createContextScope(DIALOG_NAME)
type DialogContextValue = {
triggerRef: React.RefObject<TamaguiElement>
contentRef: React.RefObject<TamaguiElement>
contentId: string
titleId: string
descriptionId: string
open: boolean
onOpenChange(open: boolean): void
onOpenToggle(): void
modal: boolean
allowPinchZoom: boolean
// allowPinchZoom: DialogProps['allowPinchZoom'];
}
const [DialogProvider, useDialogContext] = createDialogContext<DialogContextValue>(DIALOG_NAME)
type RemoveScrollProps = React.ComponentProps<typeof RemoveScroll>
interface DialogProps {
children?: React.ReactNode
open?: boolean
defaultOpen?: boolean
onOpenChange?(open: boolean): void
modal?: boolean
/**
* @see https://github.com/theKashey/react-remove-scroll#usage
*/
allowPinchZoom?: RemoveScrollProps['allowPinchZoom']
}
/* -------------------------------------------------------------------------------------------------
* DialogTrigger
* -----------------------------------------------------------------------------------------------*/
const TRIGGER_NAME = 'DialogTrigger'
const DialogTriggerFrame = styled(YStack, {
name: TRIGGER_NAME,
})
interface DialogTriggerProps extends YStackProps {}
const DialogTrigger = React.forwardRef<TamaguiElement, DialogTriggerProps>(
(props: ScopedProps<DialogTriggerProps>, forwardedRef) => {
const { __scopeDialog, ...triggerProps } = props
const context = useDialogContext(TRIGGER_NAME, __scopeDialog)
const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef)
return (
<DialogTriggerFrame
tag="button"
aria-haspopup="dialog"
aria-expanded={context.open}
aria-controls={context.contentId}
data-state={getState(context.open)}
{...triggerProps}
ref={composedTriggerRef}
onPress={composeEventHandlers(props.onPress, context.onOpenToggle)}
/>
)
}
)
DialogTrigger.displayName = TRIGGER_NAME
/* -------------------------------------------------------------------------------------------------
* DialogPortal
* -----------------------------------------------------------------------------------------------*/
const PORTAL_NAME = 'DialogPortal'
type PortalContextValue = { forceMount?: true }
const [PortalProvider, usePortalContext] = createDialogContext<PortalContextValue>(PORTAL_NAME, {
forceMount: undefined,
})
interface DialogPortalProps extends Omit<PortalProps, 'asChild'> {
children?: React.ReactNode
/**
* Used to force mounting when more control is needed. Useful when
* controlling animation with React animation libraries.
*/
forceMount?: true
}
const DialogPortal: React.FC<DialogPortalProps> = (props: ScopedProps<DialogPortalProps>) => {
const { __scopeDialog, forceMount, children, ...rest } = props
const themeName = useThemeName()
const context = useDialogContext(PORTAL_NAME, __scopeDialog)
const isShowing = forceMount || context.open
const contents = <AnimatePresence>{isShowing ? children : null}</AnimatePresence>
if (!context.modal) {
return contents
}
if (!isWeb && !isShowing) {
return contents
}
return (
<PortalProvider scope={__scopeDialog} forceMount={forceMount}>
<Portal
alignItems="center"
justifyContent="center"
zIndex={100}
pointerEvents={isShowing ? 'auto' : 'none'}
{...(isWeb && {
maxHeight: '100vh',
})}
{...rest}
>
<Theme name={themeName}>{contents}</Theme>
</Portal>
</PortalProvider>
)
}
DialogPortal.displayName = PORTAL_NAME
/* -------------------------------------------------------------------------------------------------
* DialogOverlay
* -----------------------------------------------------------------------------------------------*/
const OVERLAY_NAME = 'DialogOverlay'
const DialogOverlayFrame = styled(ThemeableStack, {
name: OVERLAY_NAME,
pointerEvents: 'auto',
backgrounded: true,
fullscreen: true,
})
interface DialogOverlayProps extends YStackProps {
/**
* Used to force mounting when more control is needed. Useful when
* controlling animation with React animation libraries.
*/
forceMount?: true
}
const DialogOverlay = React.forwardRef<TamaguiElement, DialogOverlayProps>(
(props: ScopedProps<DialogOverlayProps>, forwardedRef) => {
const portalContext = usePortalContext(OVERLAY_NAME, props.__scopeDialog)
const { forceMount = portalContext.forceMount, ...overlayProps } = props
const context = useDialogContext(OVERLAY_NAME, props.__scopeDialog)
if (!context.modal) {
return null
}
// <AnimatePresence>
return <DialogOverlayImpl {...overlayProps} ref={forwardedRef} />
// </AnimatePresence>
}
)
DialogOverlay.displayName = OVERLAY_NAME
type DialogOverlayImplProps = GetProps<typeof DialogOverlayFrame>
const DialogOverlayImpl = React.forwardRef<TamaguiElement, DialogOverlayImplProps>(
(props: ScopedProps<DialogOverlayImplProps>, forwardedRef) => {
const { __scopeDialog, ...overlayProps } = props
const context = useDialogContext(OVERLAY_NAME, __scopeDialog)
const content = (
<DialogOverlayFrame
data-state={getState(context.open)}
// We re-enable pointer-events prevented by `Dialog.Content` to allow scrolling the overlay.
pointerEvents="auto"
{...overlayProps}
ref={forwardedRef}
/>
)
if (!isWeb) {
return content
}
return (
// Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll`
// ie. when `Overlay` and `Content` are siblings
<RemoveScroll as={Slot} allowPinchZoom={context.allowPinchZoom} shards={[context.contentRef]}>
{content}
</RemoveScroll>
)
}
)
/* -------------------------------------------------------------------------------------------------
* DialogContent
* -----------------------------------------------------------------------------------------------*/
const CONTENT_NAME = 'DialogContent'
const DialogContentFrame = styled(ThemeableStack, {
name: CONTENT_NAME,
tag: 'dialog',
pointerEvents: 'auto',
position: 'relative',
backgrounded: true,
padded: true,
radiused: true,
elevate: true,
variants: {
size: {
'...size': (val, extras) => {
return {}
},
},
},
defaultVariants: {
size: '$4',
},
})
type DialogContentFrameProps = GetProps<typeof DialogContentFrame>
type DialogContentProps = DialogContentFrameProps & {
/**
* Used to force mounting when more control is needed. Useful when
* controlling animation with React animation libraries.
*/
forceMount?: true
}
const DialogContent = React.forwardRef<TamaguiElement, DialogContentProps>(
(props: ScopedProps<DialogContentProps>, forwardedRef) => {
const portalContext = usePortalContext(CONTENT_NAME, props.__scopeDialog)
const { forceMount = portalContext.forceMount, ...contentProps } = props
const context = useDialogContext(CONTENT_NAME, props.__scopeDialog)
return (
<>
{context.modal ? (
<DialogContentModal {...contentProps} ref={forwardedRef} />
) : (
<DialogContentNonModal {...contentProps} ref={forwardedRef} />
)}
</>
)
}
)
DialogContent.displayName = CONTENT_NAME
/* -----------------------------------------------------------------------------------------------*/
interface DialogContentTypeProps
extends Omit<DialogContentImplProps, 'trapFocus' | 'disableOutsidePointerEvents'> {}
const DialogContentModal = React.forwardRef<TamaguiElement, DialogContentTypeProps>(
(props: ScopedProps<DialogContentTypeProps>, forwardedRef) => {
const context = useDialogContext(CONTENT_NAME, props.__scopeDialog)
const contentRef = React.useRef<HTMLDivElement>(null)
const composedRefs = useComposedRefs(forwardedRef, context.contentRef, contentRef)
// aria-hide everything except the content (better supported equivalent to setting aria-modal)
// React.useEffect(() => {
// const content = contentRef.current
// if (content) {
// console.log('should hide others')
// // return hideOthers(content)
// }
// }, [])
return (
<DialogContentImpl
{...props}
ref={composedRefs}
// we make sure focus isn't trapped once `DialogContent` has been closed
// (closed !== unmounted when animating out)
trapFocus={context.open}
disableOutsidePointerEvents
onCloseAutoFocus={composeEventHandlers(props.onCloseAutoFocus, (event) => {
event.preventDefault()
context.triggerRef.current?.focus()
})}
onPointerDownOutside={composeEventHandlers(props.onPointerDownOutside, (event) => {
const originalEvent = event['detail'].originalEvent
const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true
const isRightClick = originalEvent.button === 2 || ctrlLeftClick
// If the event is a right-click, we shouldn't close because
// it is effectively as if we right-clicked the `Overlay`.
if (isRightClick) event.preventDefault()
})}
// When focus is trapped, a `focusout` event may still happen.
// We make sure we don't trigger our `onDismiss` in such case.
onFocusOutside={composeEventHandlers(props.onFocusOutside, (event) =>
event.preventDefault()
)}
/>
)
}
)
/* -----------------------------------------------------------------------------------------------*/
const DialogContentNonModal = React.forwardRef<TamaguiElement, DialogContentTypeProps>(
(props: ScopedProps<DialogContentTypeProps>, forwardedRef) => {
const context = useDialogContext(CONTENT_NAME, props.__scopeDialog)
const hasInteractedOutsideRef = React.useRef(false)
return (
<DialogContentImpl
{...props}
ref={forwardedRef}
trapFocus={false}
disableOutsidePointerEvents={false}
onCloseAutoFocus={(event) => {
props.onCloseAutoFocus?.(event)
if (!event.defaultPrevented) {
if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus()
// Always prevent auto focus because we either focus manually or want user agent focus
event.preventDefault()
}
hasInteractedOutsideRef.current = false
}}
onInteractOutside={(event) => {
props.onInteractOutside?.(event)
if (!event.defaultPrevented) hasInteractedOutsideRef.current = true
// Prevent dismissing when clicking the trigger.
// As the trigger is already setup to close, without doing so would
// cause it to close and immediately open.
//
// We use `onInteractOutside` as some browsers also
// focus on pointer down, creating the same issue.
const target = event.target as HTMLElement
const trigger = context.triggerRef.current
if (!(trigger instanceof HTMLElement)) return
const targetIsTrigger = trigger.contains(target)
if (targetIsTrigger) event.preventDefault()
}}
/>
)
}
)
/* -----------------------------------------------------------------------------------------------*/
type DialogContentImplProps = DialogContentFrameProps &
Omit<DismissableProps, 'onDismiss'> & {
/**
* When `true`, focus cannot escape the `Content` via keyboard,
* pointer, or a programmatic focus.
* @defaultValue false
*/
trapFocus?: FocusScopeProps['trapped']
/**
* Event handler called when auto-focusing on open.
* Can be prevented.
*/
onOpenAutoFocus?: FocusScopeProps['onMountAutoFocus']
/**
* Event handler called when auto-focusing on close.
* Can be prevented.
*/
onCloseAutoFocus?: FocusScopeProps['onUnmountAutoFocus']
}
const DialogContentImpl = React.forwardRef<TamaguiElement, DialogContentImplProps>(
(props: ScopedProps<DialogContentImplProps>, forwardedRef) => {
const {
__scopeDialog,
trapFocus,
onOpenAutoFocus,
onCloseAutoFocus,
disableOutsidePointerEvents,
onEscapeKeyDown,
onPointerDownOutside,
onFocusOutside,
onInteractOutside,
...contentProps
} = props
const context = useDialogContext(CONTENT_NAME, __scopeDialog)
const contentRef = React.useRef<HTMLDivElement>(null)
const composedRefs = useComposedRefs(forwardedRef, contentRef)
// Make sure the whole tree has focus guards as our `Dialog` will be
// the last element in the DOM (beacuse of the `Portal`)
// useFocusGuards();
return (
<>
<FocusScope
loop
trapped={trapFocus}
onMountAutoFocus={onOpenAutoFocus}
onUnmountAutoFocus={onCloseAutoFocus}
>
<Dismissable
disableOutsidePointerEvents={disableOutsidePointerEvents}
onEscapeKeyDown={onEscapeKeyDown}
onPointerDownOutside={onPointerDownOutside}
onFocusOutside={onFocusOutside}
onInteractOutside={onInteractOutside}
// @ts-ignore
ref={composedRefs}
onDismiss={() => context.onOpenChange(false)}
>
<DialogContentFrame
id={context.contentId}
aria-describedby={context.descriptionId}
aria-labelledby={context.titleId}
data-state={getState(context.open)}
{...contentProps}
/>
</Dismissable>
</FocusScope>
{process.env.NODE_ENV !== 'production' && (
<>
<TitleWarning titleId={context.titleId} />
<DescriptionWarning contentRef={contentRef} descriptionId={context.descriptionId} />
</>
)}
</>
)
}
)
/* -------------------------------------------------------------------------------------------------
* DialogTitle
* -----------------------------------------------------------------------------------------------*/
const TITLE_NAME = 'DialogTitle'
const DialogTitleFrame = styled(H2, {
name: TITLE_NAME,
})
type DialogTitleProps = GetProps<typeof DialogTitleFrame>
const DialogTitle = React.forwardRef<TamaguiElement, DialogTitleProps>(
(props: ScopedProps<DialogTitleProps>, forwardedRef) => {
const { __scopeDialog, ...titleProps } = props
const context = useDialogContext(TITLE_NAME, __scopeDialog)
return <DialogTitleFrame id={context.titleId} {...titleProps} ref={forwardedRef} />
}
)
DialogTitle.displayName = TITLE_NAME
/* -------------------------------------------------------------------------------------------------
* DialogDescription
* -----------------------------------------------------------------------------------------------*/
const DialogDescriptionFrame = styled(Paragraph, {
name: 'DialogDescription',
})
type DialogDescriptionProps = GetProps<typeof DialogDescriptionFrame>
const DESCRIPTION_NAME = 'DialogDescription'
const DialogDescription = React.forwardRef<TamaguiElement, DialogDescriptionProps>(
(props: ScopedProps<DialogDescriptionProps>, forwardedRef) => {
const { __scopeDialog, ...descriptionProps } = props
const context = useDialogContext(DESCRIPTION_NAME, __scopeDialog)
return (
<DialogDescriptionFrame id={context.descriptionId} {...descriptionProps} ref={forwardedRef} />
)
}
)
DialogDescription.displayName = DESCRIPTION_NAME
/* -------------------------------------------------------------------------------------------------
* DialogClose
* -----------------------------------------------------------------------------------------------*/
const CLOSE_NAME = 'DialogClose'
type DialogCloseProps = YStackProps
const DialogClose = React.forwardRef<TamaguiElement, DialogCloseProps>(
(props: ScopedProps<DialogCloseProps>, forwardedRef) => {
const { __scopeDialog, ...closeProps } = props
const context = useDialogContext(CLOSE_NAME, __scopeDialog)
return (
<YStack
tag="button"
{...closeProps}
ref={forwardedRef}
onPress={composeEventHandlers(props.onPress, () => context.onOpenChange(false))}
/>
)
}
)
DialogClose.displayName = CLOSE_NAME
/* -----------------------------------------------------------------------------------------------*/
function getState(open: boolean) {
return open ? 'open' : 'closed'
}
const TITLE_WARNING_NAME = 'DialogTitleWarning'
const [WarningProvider, useWarningContext] = createContext(TITLE_WARNING_NAME, {
contentName: CONTENT_NAME,
titleName: TITLE_NAME,
docsSlug: 'dialog',
})
type TitleWarningProps = { titleId?: string }
const TitleWarning: React.FC<TitleWarningProps> = ({ titleId }) => {
const titleWarningContext = useWarningContext(TITLE_WARNING_NAME)
const MESSAGE = `\`${titleWarningContext.contentName}\` requires a \`${titleWarningContext.titleName}\` for the component to be accessible for screen reader users.
If you want to hide the \`${titleWarningContext.titleName}\`, you can wrap it with our VisuallyHidden component.
For more information, see https://radix-ui.com/primitives/docs/components/${titleWarningContext.docsSlug}`
React.useEffect(() => {
if (!isWeb) return
if (titleId) {
const hasTitle = document.getElementById(titleId)
if (!hasTitle) throw new Error(MESSAGE)
}
}, [MESSAGE, titleId])
return null
}
const DESCRIPTION_WARNING_NAME = 'DialogDescriptionWarning'
type DescriptionWarningProps = {
contentRef: React.RefObject<TamaguiElement>
descriptionId?: string
}
const DescriptionWarning: React.FC<DescriptionWarningProps> = ({ contentRef, descriptionId }) => {
const descriptionWarningContext = useWarningContext(DESCRIPTION_WARNING_NAME)
const MESSAGE = `Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${descriptionWarningContext.contentName}}.`
React.useEffect(() => {
if (!isWeb) return
const contentNode = contentRef.current
if (!(contentNode instanceof HTMLElement)) {
return
}
const describedById = contentNode.getAttribute('aria-describedby')
// if we have an id and the user hasn't set aria-describedby={undefined}
if (descriptionId && describedById) {
const hasDescription = document.getElementById(descriptionId)
if (!hasDescription) console.warn(MESSAGE)
}
}, [MESSAGE, contentRef, descriptionId])
return null
}
/* -------------------------------------------------------------------------------------------------
* Dialog
* -----------------------------------------------------------------------------------------------*/
const Dialog = withStaticProperties(
function Dialog(props: ScopedProps<DialogProps>) {
const {
__scopeDialog,
children,
open: openProp,
defaultOpen = false,
onOpenChange,
modal = true,
allowPinchZoom,
} = props
const triggerRef = React.useRef<HTMLButtonElement>(null)
const contentRef = React.useRef<TamaguiElement>(null)
const [open = false, setOpen] = useControllableState({
prop: openProp,
defaultProp: defaultOpen,
onChange: onOpenChange,
})
return (
<DialogProvider
scope={__scopeDialog}
triggerRef={triggerRef}
contentRef={contentRef}
contentId={useId() || ''}
titleId={useId() || ''}
descriptionId={useId() || ''}
open={open}
onOpenChange={setOpen}
onOpenToggle={React.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen])}
modal={modal}
allowPinchZoom={allowPinchZoom || false}
>
{children}
</DialogProvider>
)
},
{
Trigger: DialogTrigger,
Portal: DialogPortal,
Overlay: DialogOverlay,
Content: DialogContent,
Title: DialogTitle,
Description: DialogDescription,
Close: DialogClose,
}
)
export {
createDialogScope,
//
Dialog,
DialogTrigger,
DialogPortal,
DialogOverlay,
DialogContent,
DialogTitle,
DialogDescription,
DialogClose,
//
WarningProvider,
}
export type {
DialogProps,
DialogTriggerProps,
DialogPortalProps,
DialogOverlayProps,
DialogContentProps,
DialogTitleProps,
DialogDescriptionProps,
DialogCloseProps,
} | the_stack |
import {
makeSprite,
t,
GameProps,
makeNativeSprite,
mask,
Texture,
makeContext,
} from "@replay/core";
import { mockContext, testSprite } from "../index";
test("getTextures, nextFrame", () => {
const { getTextures, nextFrame } = testSprite(Game(gameProps), gameProps, {
initInputs: {
pressed: true,
},
});
expect(getTextures()).toMatchInlineSnapshot(`
Array [
Object {
"props": Object {
"anchorX": 0,
"anchorY": 0,
"color": "blue",
"gradient": undefined,
"mask": Object {
"height": 10,
"type": "rectangleMask",
"width": 5,
"x": 0,
"y": 0,
},
"opacity": 1,
"radius": 10,
"rotation": 0,
"scaleX": 1,
"scaleY": 1,
"testId": "player",
"x": 0,
"y": 100,
},
"type": "circle",
},
Object {
"props": Object {
"anchorX": 0,
"anchorY": 0,
"color": "red",
"font": Object {
"family": "Arial",
"size": 12,
},
"gradient": undefined,
"mask": null,
"opacity": 1,
"rotation": 0,
"scaleX": 1,
"scaleY": 1,
"strokeColor": undefined,
"strokeThickness": undefined,
"testId": undefined,
"text": "x: 0",
"x": 100,
"y": 0,
},
"type": "text",
},
Object {
"props": Object {
"anchorX": 0,
"anchorY": 0,
"color": "red",
"font": undefined,
"gradient": undefined,
"mask": null,
"opacity": 1,
"rotation": 0,
"scaleX": 1,
"scaleY": 1,
"strokeColor": undefined,
"strokeThickness": undefined,
"testId": undefined,
"text": "Loading",
"x": 0,
"y": 0,
},
"type": "text",
},
]
`);
nextFrame();
expect(getTextures()).toMatchInlineSnapshot(`
Array [
Object {
"props": Object {
"anchorX": 0,
"anchorY": 0,
"color": "blue",
"gradient": undefined,
"mask": Object {
"height": 10,
"type": "rectangleMask",
"width": 5,
"x": 0,
"y": 0,
},
"opacity": 1,
"radius": 10,
"rotation": 0,
"scaleX": 1,
"scaleY": 1,
"testId": "player",
"x": 1,
"y": 100,
},
"type": "circle",
},
Object {
"props": Object {
"anchorX": 0,
"anchorY": 0,
"color": "red",
"font": Object {
"family": "Arial",
"size": 12,
},
"gradient": undefined,
"mask": null,
"opacity": 1,
"rotation": 0,
"scaleX": 1,
"scaleY": 1,
"strokeColor": undefined,
"strokeThickness": undefined,
"testId": undefined,
"text": "x: 1",
"x": 100,
"y": 0,
},
"type": "text",
},
Object {
"props": Object {
"anchorX": 0,
"anchorY": 0,
"color": "red",
"font": undefined,
"gradient": undefined,
"mask": null,
"opacity": 1,
"rotation": 0,
"scaleX": 1,
"scaleY": 1,
"strokeColor": undefined,
"strokeThickness": undefined,
"testId": undefined,
"text": "Loading",
"x": 0,
"y": 0,
},
"type": "text",
},
]
`);
});
test("jumpToFrame, getTexture", async () => {
const { jumpToFrame, getTexture } = testSprite(Game(gameProps), gameProps, {
initInputs: {
pressed: true,
},
});
await jumpToFrame(() => getTexture("player").props.x > 10);
expect(getTexture("player").props.x).toBe(11);
});
test("setRandomNumbers, log", () => {
const { setRandomNumbers, log, nextFrame } = testSprite(
Game(gameProps),
gameProps,
{
initInputs: {
testInput: "logRandom",
},
}
);
expect(log).not.toBeCalled();
nextFrame();
expect(log).toBeCalledWith(0.5);
nextFrame();
expect(log).toBeCalledWith(0.5);
setRandomNumbers([0.1, 0.2, 0.3]);
nextFrame();
expect(log).toBeCalledWith(0.1);
nextFrame();
expect(log).toBeCalledWith(0.2);
nextFrame();
expect(log).toBeCalledWith(0.3);
nextFrame();
expect(log).toBeCalledWith(0.1);
});
test("initRandom", () => {
const { log, nextFrame } = testSprite(Game(gameProps), gameProps, {
initInputs: {
testInput: "logRandom",
},
initRandom: [0.7, 0.8],
});
nextFrame();
expect(log).toBeCalledWith(0.7);
nextFrame();
expect(log).toBeCalledWith(0.8);
nextFrame();
expect(log).toBeCalledWith(0.7);
});
test("textureExists, updateInputs", () => {
const { textureExists, updateInputs, nextFrame } = testSprite(
Game(gameProps),
gameProps
);
expect(textureExists("player")).toBe(true);
expect(textureExists("enemy")).toBe(false);
updateInputs({ testInput: "showEnemy" });
nextFrame();
expect(textureExists("player")).toBe(true);
expect(textureExists("enemy")).toBe(true);
});
test("getByText", () => {
const { getByText, nextFrame } = testSprite(Game(gameProps), gameProps, {
initInputs: {
pressed: true,
},
});
nextFrame();
expect(getByText("x: 1").length).toBe(1);
expect(getByText("X: 1")[0].props.x).toBe(100);
nextFrame();
expect(getByText("x: 2").length).toBe(1);
expect(getByText("x: 1").length).toBe(0);
});
test("now", () => {
const { log, nextFrame } = testSprite(Game(gameProps), gameProps, {
initInputs: {
testInput: "logNow",
},
});
expect(log).not.toBeCalled();
nextFrame();
expect(log).toBeCalledWith("2000-02-01T00:00:00.000Z");
});
describe("timer", () => {
test("Can call function after timeout with timer", async () => {
const { log, nextFrame, updateInputs } = testSprite(
Game(gameProps),
gameProps,
{
initInputs: {
testInput: "timerStart",
},
}
);
nextFrame();
updateInputs({ testInput: undefined });
nextFrame();
nextFrame();
expect(log).not.toBeCalled();
nextFrame();
// 50 ms passed
expect(log).toBeCalledWith("timeout complete");
});
test("Can pause and resume timer", async () => {
const { log, nextFrame, updateInputs } = testSprite(
Game(gameProps),
gameProps,
{
initInputs: {
testInput: "timerStart",
},
}
);
nextFrame();
updateInputs({ testInput: undefined });
nextFrame();
expect(log).not.toBeCalled();
// Can pause
updateInputs({ testInput: "timerPause" });
nextFrame();
updateInputs({ testInput: undefined });
nextFrame();
nextFrame();
nextFrame();
nextFrame();
expect(log).not.toBeCalled();
// Can resume
updateInputs({ testInput: "timerResume" });
nextFrame();
updateInputs({ testInput: undefined });
nextFrame();
expect(log).toBeCalledWith("timeout complete");
});
test("Can cancel timer", async () => {
const { log, nextFrame, updateInputs } = testSprite(
Game(gameProps),
gameProps,
{
initInputs: {
testInput: "timerStart",
},
}
);
nextFrame();
updateInputs({ testInput: undefined });
nextFrame();
expect(log).not.toBeCalled();
// Can cancel
updateInputs({ testInput: "timerCancel" });
nextFrame();
updateInputs({ testInput: undefined });
nextFrame();
nextFrame();
nextFrame();
nextFrame();
expect(log).not.toBeCalled();
// Resume timer (should do nothing)
updateInputs({ testInput: "timerResume" });
nextFrame();
updateInputs({ testInput: undefined });
nextFrame();
expect(log).not.toBeCalled();
});
});
test("audio", async () => {
const { nextFrame, audio, log, updateInputs, resolvePromises } = testSprite(
Game(gameProps),
gameProps,
{
initInputs: {
testInput: "audioPlay",
},
}
);
await resolvePromises();
nextFrame();
expect(audio.play).toBeCalledWith("sound.wav");
updateInputs({
testInput: "audioPlayFrom",
});
nextFrame();
expect(audio.play).toBeCalledWith("sound.wav", 100);
updateInputs({
testInput: "audioPlayLoop",
});
nextFrame();
expect(audio.play).toBeCalledWith("sound.wav", {
fromPosition: 0,
loop: true,
});
updateInputs({
testInput: "audioPause",
});
nextFrame();
expect(audio.pause).toBeCalledWith("sound.wav");
updateInputs({
testInput: "logAudioPosition",
});
nextFrame();
expect(audio.getPosition).toBeCalledWith("sound.wav");
expect(log).toBeCalledWith(120);
});
test("audio additional features", async () => {
const { nextFrame, audio, updateInputs, resolvePromises } = testSprite(
Game(gameProps),
gameProps,
{
initInputs: {
testInput: "audioGetStatus",
},
}
);
await resolvePromises();
/*
getStatus: () => "paused" | "playing";
getVolume: () => number;
setVolume: (volume: Volume) => void;
getDuration: () => number;
*/
nextFrame();
expect(audio.play).toBeCalledWith("sound.wav");
expect(audio.getStatus).toBeCalledWith("sound.wav");
updateInputs({
testInput: "audioSetVolume",
});
nextFrame();
expect(audio.setVolume).toBeCalledWith("sound.wav", 0.25);
updateInputs({
testInput: "audioGetDuration",
});
nextFrame();
expect(audio.getDuration).toBeCalledWith("sound.wav");
});
test("network", () => {
const { nextFrame, network, log, updateInputs } = testSprite(
Game(gameProps),
gameProps,
{
initInputs: {
testInput: "networkGET",
},
networkResponses: {
get: {
"/test-get": () => ({ got: "a get" }),
},
put: {
"/test-put": (body: any) => ({ got: body.hi }),
},
post: {
"/test-post": (body: any) => ({ got: body.hi }),
},
delete: {
"/test-delete": () => ({ got: "a delete" }),
},
},
}
);
nextFrame();
expect(network.get).toBeCalled();
expect(log).toBeCalledWith({ got: "a get" });
updateInputs({ testInput: "networkPUT" });
nextFrame();
expect(network.put).toBeCalled();
expect(log).toBeCalledWith({ got: "hello put" });
updateInputs({ testInput: "networkPOST" });
nextFrame();
expect(network.post).toBeCalled();
expect(log).toBeCalledWith({ got: "hello post" });
updateInputs({ testInput: "networkDELETE" });
nextFrame();
expect(network.delete).toBeCalled();
expect(log).toBeCalledWith({ got: "a delete" });
updateInputs({ testInput: "networkGET-no-url" });
expect(() => nextFrame()).toThrowError(
"No GET response defined for url: /test-get-fail"
);
});
test("storage", async () => {
const { nextFrame, store, updateInputs, resolvePromises, log } = testSprite(
Game(gameProps),
gameProps,
{
initStore: { origStore: "origValue" },
}
);
nextFrame();
expect(store).toEqual({ origStore: "origValue" });
updateInputs({ testInput: "storage-set" });
nextFrame();
await resolvePromises();
expect(store).toEqual({ origStore: "origValue", testKey: "hello" });
updateInputs({ testInput: "storage-get" });
nextFrame();
await resolvePromises();
expect(log).toBeCalledWith("hello");
updateInputs({ testInput: "storage-remove" });
nextFrame();
await resolvePromises();
expect(store).toEqual({ origStore: "origValue" });
});
test("alerts", () => {
const {
nextFrame,
log,
alert,
updateInputs,
updateAlertResponse,
} = testSprite(Game(gameProps), gameProps, {
initAlertResponse: false,
});
nextFrame();
updateInputs({ testInput: "alert-ok" });
nextFrame();
expect(alert.ok).toBeCalledWith("Ok?", expect.any(Function));
expect(log).toBeCalledWith("It's ok");
updateInputs({ testInput: "alert-ok-cancel" });
nextFrame();
expect(alert.okCancel).toBeCalledWith("Ok or cancel?", expect.any(Function));
expect(log).toBeCalledWith("Was ok: false");
updateAlertResponse(true);
nextFrame();
expect(log).toBeCalledWith("Was ok: true");
});
test("clipboard", () => {
const { nextFrame, log, clipboard, updateInputs } = testSprite(
Game(gameProps),
gameProps
);
nextFrame();
updateInputs({ testInput: "clipboard-copy" });
nextFrame();
expect(clipboard.copy).toBeCalledWith("Hello", expect.any(Function));
expect(log).toBeCalledWith("Copied");
});
test("can test individual Sprites", () => {
const { getByText, getTextures } = testSprite(
Text({ id: "Text", text: "Hello" }),
gameProps
);
expect(getTextures().length).toBe(1);
expect(getByText("Hello").length).toBe(1);
});
test("can map input coordinates to relative coordinates within Sprite", () => {
const { log } = testSprite(Game(gameProps), gameProps, {
initInputs: {
x: 20,
},
mapInputCoordinates(getLocalCoords, inputs) {
const { x = 0 } = inputs;
const localX = getLocalCoords({ x, y: 0 }).x;
return {
...inputs,
x: localX,
};
},
});
// x is -100 from input due to mapping function
expect(log).toBeCalledWith("x in Text Sprite is -80");
});
test("can get global position and rotation of deeply nested textures", () => {
const { getTextures } = testSprite(NestedSpriteGame(gameProps), gameProps);
const textures = getTextures();
expect(textures.length).toBe(1);
expect(textures[0].props.x).toBe(-10);
expect(textures[0].props.y).toBe(50);
expect(textures[0].props.rotation).toBe(0);
});
test("jumpToFrame throws last error", async () => {
const { jumpToFrame, getTexture } = testSprite(Game(gameProps), gameProps, {
initInputs: {},
});
expect.assertions(4);
try {
await jumpToFrame(() => getTexture("i-dont-exist"));
} catch (e) {
expect(e.message).toBe(
`Timeout of 30 gameplay seconds reached on jumpToFrame with error:\n\nNo textures found with test id "i-dont-exist"`
);
// First line of stack is the code in this file
expect(
e.stack.split("\n")[1].includes("src/__tests__/replay-test.test.ts")
).toBe(true);
}
// Override max frames
let frameCount = 0;
try {
await jumpToFrame(() => {
frameCount++;
return getTexture("i-dont-exist");
}, 3600);
} catch (e) {
expect(e.message).toBe(
`Timeout of 60 gameplay seconds reached on jumpToFrame with error:\n\nNo textures found with test id "i-dont-exist"`
);
expect(frameCount).toBe(3600);
}
});
test("can mock Native Sprites", () => {
const { getTextures } = testSprite(NativeSpriteGame(gameProps), gameProps, {
nativeSpriteNames: ["MyNativeSprite"],
});
const textures = getTextures();
expect(textures.length).toBe(0);
});
test("can load files specified in preloadFiles", async () => {
const { getTextures, nextFrame, resolvePromises } = testSprite(
Game(gameProps),
gameProps
);
const isLoading = (textures: Texture[]) =>
textures.some(
(texture) => texture.type === "text" && texture.props.text === "Loading"
);
expect(isLoading(getTextures())).toBe(true);
await resolvePromises();
nextFrame();
expect(isLoading(getTextures())).toBe(false);
});
test("shows error if file asset not loaded", async () => {
expect(() => testSprite(ImageErrorGame(gameProps), gameProps)).toThrowError(
`Image file "unknown.png" was not preloaded`
);
expect(() => testSprite(ImageErrorGame2(gameProps), gameProps)).toThrowError(
`Image file "player.png" did not finish loading before it was used`
);
expect(() => testSprite(AudioErrorGame(gameProps), gameProps)).toThrowError(
`Audio file "unknown.mp3" was not preloaded`
);
expect(() => testSprite(AudioErrorGame2(gameProps), gameProps)).toThrowError(
`Audio file "shoot.wav" did not finish loading before it was used`
);
// Doesn't throw error if option is set
expect(() =>
testSprite(AudioErrorGame(gameProps), gameProps, {
throwAssetErrors: false,
})
).not.toThrowError();
expect(() =>
testSprite(ImageErrorGame(gameProps), gameProps, {
throwAssetErrors: false,
})
).not.toThrowError();
});
test("can mock context", () => {
const { log } = testSprite(TestContextSprite(gameProps), gameProps, {
contexts: [
mockContext(testContext1, { val: "test" }),
mockContext(testContext2, { result: "hello" }),
],
});
expect(log).toBeCalledWith("Val: test, result: hello");
});
// --- Mock Game
interface State {
x: number;
showEnemy: boolean;
loading: boolean;
timerId?: string;
}
interface Inputs {
x?: number;
pressed?: boolean;
testInput?: string;
}
const gameProps: GameProps = {
id: "Game",
size: {
width: 500,
height: 300,
},
};
const Game = makeSprite<GameProps, State, Inputs>({
init({ preloadFiles, updateState }) {
preloadFiles({ audioFileNames: ["sound.wav"] }).then(() => {
updateState((s) => ({ ...s, loading: false }));
});
return {
x: 0,
showEnemy: false,
loading: true,
};
},
loop({ state, device, getInputs, updateState }) {
const inputs = getInputs();
if (inputs.pressed) {
return {
...state,
x: state.x + 1,
};
}
switch (inputs.testInput) {
case "logRandom":
device.log(device.random());
break;
case "logNow":
device.log(device.now().toISOString());
break;
case "showEnemy":
return {
...state,
showEnemy: true,
};
case "timerStart":
const id = device.timer.start(() => {
device.log("timeout complete");
}, 40);
updateState((s) => ({ ...s, timerId: id }));
break;
case "timerPause":
device.timer.pause(state.timerId ?? "");
break;
case "timerResume":
device.timer.resume(state.timerId ?? "");
break;
case "timerCancel":
device.timer.cancel(state.timerId ?? "");
break;
case "audioPlay":
device.audio("sound.wav").play();
break;
case "audioPlayFrom":
device.audio("sound.wav").play(100);
break;
case "audioPlayLoop":
device.audio("sound.wav").play({ fromPosition: 0, loop: true });
break;
case "audioPause":
device.audio("sound.wav").pause();
break;
case "logAudioPosition":
device.log(device.audio("sound.wav").getPosition());
break;
case "audioGetStatus":
device.audio("sound.wav").play();
device.audio("sound.wav").getStatus();
break;
case "audioSetVolume":
device.audio("sound.wav").setVolume(0.25);
break;
case "audioGetDuration":
device.audio("sound.wav").getDuration();
break;
case "networkGET":
device.network.get("/test-get", (response) => {
device.log(response);
});
break;
case "networkPUT":
device.network.put("/test-put", { hi: "hello put" }, (response) => {
device.log(response);
});
break;
case "networkPOST":
device.network.post("/test-post", { hi: "hello post" }, (response) => {
device.log(response);
});
break;
case "networkDELETE":
device.network.delete("/test-delete", (response) => {
device.log(response);
});
break;
case "networkGET-no-url":
device.network.get("/test-get-fail", () => null);
break;
case "storage-set":
device.storage.setItem("testKey", "hello");
break;
case "storage-get":
device.storage.getItem("testKey").then((value) => {
device.log(value);
});
break;
case "storage-remove":
device.storage.setItem("testKey", null);
break;
case "alert-ok":
device.alert.ok("Ok?", () => {
device.log("It's ok");
});
break;
case "alert-ok-cancel":
device.alert.okCancel("Ok or cancel?", (wasOk) => {
device.log(`Was ok: ${wasOk}`);
});
break;
case "clipboard-copy":
device.clipboard.copy("Hello", () => {
device.log("Copied");
});
break;
default:
break;
}
return state;
},
render({ state }) {
return [
t.circle({
testId: "player",
x: state.x,
y: 100,
rotation: 0,
radius: 10,
color: "blue",
mask: mask.rectangle({
width: 5,
height: 10,
}),
}),
Text({
id: "Text",
x: 100,
y: 0,
rotation: 0,
text: `x: ${state.x}`,
}),
state.showEnemy
? t.circle({
testId: "enemy",
x: 100,
y: 100,
rotation: 0,
radius: 10,
color: "red",
})
: null,
state.loading
? t.text({
text: "Loading",
color: "red",
})
: null,
];
},
});
const Text = makeSprite<{ text: string }, undefined, Inputs>({
render({ props, device, getInputs }) {
const inputs = getInputs();
if (inputs.x) {
device.log(`x in Text Sprite is ${inputs.x}`);
}
return [
t.text({
text: props.text,
color: "red",
font: { family: "Arial", size: 12 },
}),
];
},
});
/// -- Nested Sprite test
const NestedSpriteGame = makeSprite<GameProps>({
render() {
return [
NestedFirstSprite({
id: "first",
x: 20,
y: 20,
rotation: -90,
}),
];
},
});
const NestedFirstSprite = makeSprite({
render() {
return [
NestedSecondSprite({
id: "second",
x: 50,
y: 20,
rotation: -90,
}),
];
},
});
const NestedSecondSprite = makeSprite({
render() {
return [
t.text({
text: "nested",
color: "black",
x: 10,
y: 20,
rotation: 180,
}),
];
},
});
/// -- Mock Native Sprite test
const NativeSpriteGame = makeSprite<GameProps>({
render() {
return [
MyNativeSprite({
id: "native",
}),
];
},
});
const MyNativeSprite = makeNativeSprite("MyNativeSprite");
/// -- Loading files error Sprite test
const ImageErrorGame = makeSprite<GameProps>({
render() {
return [
t.image({
fileName: "unknown.png",
width: 30,
height: 30,
}),
];
},
});
const ImageErrorGame2 = makeSprite<GameProps>({
init({ preloadFiles }) {
// Loading file, but not waiting in render
preloadFiles({ imageFileNames: ["player.png"] });
return undefined;
},
render() {
return [
t.image({
fileName: "player.png",
width: 30,
height: 30,
}),
];
},
});
const AudioErrorGame = makeSprite<GameProps>({
init({ device }) {
device.audio("unknown.mp3").play();
return undefined;
},
render() {
return [];
},
});
const AudioErrorGame2 = makeSprite<GameProps>({
init({ device, preloadFiles }) {
preloadFiles({ audioFileNames: ["shoot.wav"] });
device.audio("shoot.wav").play();
return undefined;
},
render() {
return [];
},
});
const testContext1 = makeContext<{ val: string }>();
const testContext2 = makeContext<{ result: string }>();
const TestContextSprite = makeSprite<{}>({
render({ getContext, device }) {
const { val } = getContext(testContext1);
const { result } = getContext(testContext2);
device.log(`Val: ${val}, result: ${result}`);
return [];
},
}); | the_stack |
import { Unit } from '@iota/unit-converter'
import { convertToFiat, currencies, exchangeRates } from 'shared/lib/currency'
import { localize } from 'shared/lib/i18n'
import { activeProfile, updateProfile } from 'shared/lib/profile'
import { formatUnitPrecision } from 'shared/lib/units'
import { isSelfTransaction, wallet } from 'shared/lib/wallet'
import { formatDate } from 'shared/lib/i18n'
import { derived, get, writable } from 'svelte/store'
import { formatCurrencyValue } from './currency'
import { priceData } from './market'
import type { Message } from './typings/message'
import { ActivityTimeframe, ChartData, DashboardChartType, Tooltip, WalletChartType } from './typings/chart'
import { AvailableExchangeRates, CurrencyTypes } from './typings/currency'
import { HistoryDataProps } from './typings/market'
import type { BalanceHistory, WalletAccount } from './typings/wallet'
const BAR_CHART_ACTIVITY_MONTHS = 6
/** Selected chart */
export const selectedDashboardChart = writable<DashboardChartType>(DashboardChartType.HOLDINGS)
export const selectedWalletChart = writable<WalletChartType>(WalletChartType.HOLDINGS)
const fiatHistoryData = derived([priceData, activeProfile], ([$priceData, $activeProfile]) => {
if ($activeProfile?.settings) {
// back compatibility: init profile chartSelectors
if (!$activeProfile?.settings.chartSelectors) {
const chartSelectors = {
currency: AvailableExchangeRates.USD,
timeframe: HistoryDataProps.SEVEN_DAYS,
}
updateProfile('settings.chartSelectors', chartSelectors)
}
//
return (
$priceData?.[$activeProfile?.settings.chartSelectors.currency.toLocaleLowerCase()]?.[
$activeProfile?.settings.chartSelectors.timeframe
]
?.slice()
.sort((a, b) => a[0] - b[0]) ?? []
)
}
})
const walletBalance = derived(wallet, ($wallet) => {
const { balanceOverview } = $wallet
return get(balanceOverview)?.balanceRaw
})
export function getChartDataFromBalanceHistory({
balanceHistory,
currentBalance,
tokenType,
convertToSelectedCurrency = false,
}: {
balanceHistory: BalanceHistory
currentBalance: number
tokenType: string
convertToSelectedCurrency?: boolean
}): ChartData {
let chartData: ChartData = { labels: [], data: [], tooltips: [] }
let _fiatHistoryData
const selectedCurrency = get(activeProfile)?.settings.chartSelectors.currency ?? ''
if (convertToSelectedCurrency) {
_fiatHistoryData = get(fiatHistoryData)
}
chartData = balanceHistory[get(activeProfile)?.settings.chartSelectors.timeframe].reduce(
(acc, values, index) => {
const balance = convertToSelectedCurrency
? ((values.balance * _fiatHistoryData[index][1]) / 1000000).toFixed(5)
: values.balance
acc.data.push(balance)
acc.labels.push(formatLabel(values.timestamp * 1000))
acc.tooltips.push(
formatLineChartTooltip(
balance,
convertToSelectedCurrency ? selectedCurrency : tokenType.toLocaleLowerCase(),
values.timestamp * 1000,
false,
convertToSelectedCurrency
)
)
return acc
},
{ labels: [], data: [], tooltips: [] }
)
// add current balance
const currentBalanceDataPoint = getCurrentBalanceDataPoint({ currentBalance, tokenType, convertToSelectedCurrency })
chartData.data.push(currentBalanceDataPoint.data)
chartData.labels.push(currentBalanceDataPoint.label)
chartData.tooltips.push(currentBalanceDataPoint.tooltip)
chartData.steppedLine = !convertToSelectedCurrency
return chartData
}
export function getChartDataForTokenValue(): ChartData {
let chartData: ChartData = { labels: [], data: [], tooltips: [] }
const currency = get(activeProfile)?.settings.chartSelectors.currency ?? ''
chartData = get(fiatHistoryData).reduce(
(acc, values) => {
acc.data.push(parseFloat(values[1]))
acc.labels.push(formatLabel(values[0] * 1000))
acc.tooltips.push(formatLineChartTooltip(parseFloat(values[1]), currency, values[0] * 1000, true))
return acc
},
{ labels: [], data: [], tooltips: [] }
)
return chartData
}
export const getAccountActivityData = (
account: WalletAccount
): { incoming: ChartData; outgoing: ChartData; labels: string[] } => {
const now = new Date()
const activityTimeframes: ActivityTimeframe[] = []
const incoming: ChartData = {
data: [],
tooltips: [],
label: localize('general.incoming'),
color: account.color || 'blue',
} // TODO: profile colors
const outgoing: ChartData = { data: [], tooltips: [], label: localize('general.outgoing'), color: 'gray' } // TODO: profile colors
const labels: string[] = []
const messages: Message[] =
account.messages
.slice()
?.filter((message) => message.payload && !isSelfTransaction(message.payload, account)) // Remove self transactions and messages with no payload
?.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()) ?? []
for (let i = 0; i < BAR_CHART_ACTIVITY_MONTHS; i++) {
const start: number = new Date(now.getFullYear(), now.getMonth() - i, 1).getTime()
const end: number = new Date(now.getFullYear(), now.getMonth() - i + 1, 0).getTime()
activityTimeframes.push({ start, end })
labels.unshift(formatDate(new Date(start), { month: 'short' }))
}
if (messages?.length) {
let index = 0
activityTimeframes.forEach(({ start, end }) => {
let _incoming = 0
let _outgoing = 0
if (
new Date(messages[messages.length - 1].timestamp).getTime() >= start &&
new Date(messages[messages.length - 1].timestamp).getTime() <= end
) {
for (index; index < messages.length; index++) {
const message = messages[index]
if (message.payload.type === 'Transaction') {
const messageTimestamp = new Date(message.timestamp).getTime()
if (messageTimestamp >= start && messageTimestamp <= end) {
if (message.payload.data.essence.data.incoming) {
_incoming += message.payload.data.essence.data.value
} else {
_outgoing += message.payload.data.essence.data.value
}
} else if (messageTimestamp > end) return
}
}
}
incoming.data.unshift(_incoming)
incoming.tooltips.unshift({
title: formatDate(new Date(start), {
year: 'numeric',
month: 'long',
}),
label: localize('charts.incomingMi', {
values: {
value: formatUnitPrecision(_incoming, Unit.Mi, true),
},
}),
})
outgoing.data.unshift(_outgoing)
outgoing.tooltips.unshift({
title: formatDate(new Date(start), {
year: 'numeric',
month: 'long',
}),
label: localize('charts.outgoingMi', {
values: {
value: formatUnitPrecision(_outgoing, Unit.Mi, true),
},
}),
})
})
} else {
activityTimeframes.forEach(({ start, end }) => {
incoming.data.push(0)
incoming.tooltips.unshift({
title: formatDate(new Date(start), {
year: 'numeric',
month: 'long',
}),
label: localize('charts.incomingMi', {
values: {
value: 0,
},
}),
})
outgoing.data.unshift(0)
outgoing.tooltips.unshift({
title: formatDate(new Date(start), {
year: 'numeric',
month: 'long',
}),
label: localize('charts.outgoingMi', {
values: {
value: 0,
},
}),
})
})
}
return {
incoming,
outgoing,
labels,
}
}
function formatLabel(timestamp: number): string {
const date: Date = new Date(timestamp)
let formattedLabel: string = ''
switch (get(activeProfile)?.settings.chartSelectors.timeframe) {
case HistoryDataProps.ONE_HOUR:
case HistoryDataProps.TWENTY_FOUR_HOURS:
formattedLabel = formatDate(new Date(date), {
hour: '2-digit',
minute: '2-digit',
})
break
case HistoryDataProps.SEVEN_DAYS:
case HistoryDataProps.ONE_MONTH:
formattedLabel = formatDate(new Date(date), {
month: 'short',
day: 'numeric',
})
break
}
return formattedLabel
}
function formatLineChartTooltip(
data: number | string,
currency: string,
timestamp: number | string,
showMiota: boolean = false,
showCurrencyUnit: boolean = true
): Tooltip {
const title: string = `${showMiota ? `1 ${Unit.Mi}: ` : ''}${formatCurrencyValue(data, currency, 3)} ${
showCurrencyUnit ? currency : ''
}`
const label: string = formatDate(new Date(timestamp), {
year: 'numeric',
month: 'short',
day: '2-digit',
weekday: 'long',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
})
return { title, label }
}
function getCurrentBalanceDataPoint({
currentBalance,
tokenType,
convertToSelectedCurrency,
}: {
currentBalance: number
tokenType: string
convertToSelectedCurrency?: boolean
}): { data: number; label: string; tooltip: Tooltip } {
const selectedCurrency = get(activeProfile)?.settings.chartSelectors.currency ?? ''
const now = new Date().getTime()
const balance = convertToSelectedCurrency
? convertToFiat(
currentBalance,
get(currencies)[CurrencyTypes.USD],
get(exchangeRates)[get(activeProfile)?.settings.chartSelectors.currency]
)
: currentBalance
return {
data: balance,
label: formatLabel(now),
tooltip: formatLineChartTooltip(
balance,
convertToSelectedCurrency ? selectedCurrency : tokenType.toLocaleLowerCase(),
now,
false,
convertToSelectedCurrency
),
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { ComputePolicies } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { DataLakeAnalyticsAccountManagementClient } from "../dataLakeAnalyticsAccountManagementClient";
import {
ComputePolicy,
ComputePoliciesListByAccountNextOptionalParams,
ComputePoliciesListByAccountOptionalParams,
ComputePoliciesListByAccountResponse,
CreateOrUpdateComputePolicyParameters,
ComputePoliciesCreateOrUpdateOptionalParams,
ComputePoliciesCreateOrUpdateResponse,
ComputePoliciesGetOptionalParams,
ComputePoliciesGetResponse,
ComputePoliciesUpdateOptionalParams,
ComputePoliciesUpdateResponse,
ComputePoliciesDeleteOptionalParams,
ComputePoliciesListByAccountNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing ComputePolicies operations. */
export class ComputePoliciesImpl implements ComputePolicies {
private readonly client: DataLakeAnalyticsAccountManagementClient;
/**
* Initialize a new instance of the class ComputePolicies class.
* @param client Reference to the service client
*/
constructor(client: DataLakeAnalyticsAccountManagementClient) {
this.client = client;
}
/**
* Lists the Data Lake Analytics compute policies within the specified Data Lake Analytics account. An
* account supports, at most, 50 policies
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param options The options parameters.
*/
public listByAccount(
resourceGroupName: string,
accountName: string,
options?: ComputePoliciesListByAccountOptionalParams
): PagedAsyncIterableIterator<ComputePolicy> {
const iter = this.listByAccountPagingAll(
resourceGroupName,
accountName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByAccountPagingPage(
resourceGroupName,
accountName,
options
);
}
};
}
private async *listByAccountPagingPage(
resourceGroupName: string,
accountName: string,
options?: ComputePoliciesListByAccountOptionalParams
): AsyncIterableIterator<ComputePolicy[]> {
let result = await this._listByAccount(
resourceGroupName,
accountName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByAccountNext(
resourceGroupName,
accountName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByAccountPagingAll(
resourceGroupName: string,
accountName: string,
options?: ComputePoliciesListByAccountOptionalParams
): AsyncIterableIterator<ComputePolicy> {
for await (const page of this.listByAccountPagingPage(
resourceGroupName,
accountName,
options
)) {
yield* page;
}
}
/**
* Lists the Data Lake Analytics compute policies within the specified Data Lake Analytics account. An
* account supports, at most, 50 policies
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param options The options parameters.
*/
private _listByAccount(
resourceGroupName: string,
accountName: string,
options?: ComputePoliciesListByAccountOptionalParams
): Promise<ComputePoliciesListByAccountResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listByAccountOperationSpec
);
}
/**
* Creates or updates the specified compute policy. During update, the compute policy with the
* specified name will be replaced with this new compute policy. An account supports, at most, 50
* policies
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param computePolicyName The name of the compute policy to create or update.
* @param parameters Parameters supplied to create or update the compute policy. The max degree of
* parallelism per job property, min priority per job property, or both must be present.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
accountName: string,
computePolicyName: string,
parameters: CreateOrUpdateComputePolicyParameters,
options?: ComputePoliciesCreateOrUpdateOptionalParams
): Promise<ComputePoliciesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
accountName,
computePolicyName,
parameters,
options
},
createOrUpdateOperationSpec
);
}
/**
* Gets the specified Data Lake Analytics compute policy.
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param computePolicyName The name of the compute policy to retrieve.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
accountName: string,
computePolicyName: string,
options?: ComputePoliciesGetOptionalParams
): Promise<ComputePoliciesGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, computePolicyName, options },
getOperationSpec
);
}
/**
* Updates the specified compute policy.
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param computePolicyName The name of the compute policy to update.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
accountName: string,
computePolicyName: string,
options?: ComputePoliciesUpdateOptionalParams
): Promise<ComputePoliciesUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, computePolicyName, options },
updateOperationSpec
);
}
/**
* Deletes the specified compute policy from the specified Data Lake Analytics account
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param computePolicyName The name of the compute policy to delete.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
accountName: string,
computePolicyName: string,
options?: ComputePoliciesDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, computePolicyName, options },
deleteOperationSpec
);
}
/**
* ListByAccountNext
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param nextLink The nextLink from the previous successful call to the ListByAccount method.
* @param options The options parameters.
*/
private _listByAccountNext(
resourceGroupName: string,
accountName: string,
nextLink: string,
options?: ComputePoliciesListByAccountNextOptionalParams
): Promise<ComputePoliciesListByAccountNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, nextLink, options },
listByAccountNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByAccountOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ComputePolicyListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.ComputePolicy
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters6,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.computePolicyName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ComputePolicy
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.computePolicyName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.ComputePolicy
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters7,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.computePolicyName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.computePolicyName
],
headerParameters: [Parameters.accept],
serializer
};
const listByAccountNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ComputePolicyListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import noop from "../../../../../../utils/noop";
import {
IAdaptationSetAttributes,
IAdaptationSetChildren,
ISegmentListIntermediateRepresentation,
} from "../../../node_parser_types";
import ParsersStack, {
IAttributeParser,
IChildrenParser,
} from "../parsers_stack";
import {
AttributeName,
TagName,
} from "../types";
import {
parseFloatOrBool,
parseString,
} from "../utils";
import { generateBaseUrlAttrParser } from "./BaseURL";
import { generateContentComponentAttrParser } from "./ContentComponent";
import { generateContentProtectionAttrParser } from "./ContentProtection";
import {
generateRepresentationAttrParser,
generateRepresentationChildrenParser,
} from "./Representation";
import { generateSchemeAttrParser } from "./Scheme";
import { generateSegmentBaseAttrParser } from "./SegmentBase";
import { generateSegmentListChildrenParser } from "./SegmentList";
import { generateSegmentTemplateAttrParser } from "./SegmentTemplate";
/**
* Generate a "children parser" once inside a `AdaptationSet` node.
* @param {Object} adaptationSetChildren
* @param {WebAssembly.Memory} linearMemory
* @param {ParsersStack} parsersStack
* @returns {Function}
*/
export function generateAdaptationSetChildrenParser(
adaptationSetChildren : IAdaptationSetChildren,
linearMemory : WebAssembly.Memory,
parsersStack : ParsersStack
) : IChildrenParser {
return function onRootChildren(nodeId : number) {
switch (nodeId) {
case TagName.Accessibility: {
const accessibility = {};
if (adaptationSetChildren.accessibilities === undefined) {
adaptationSetChildren.accessibilities = [];
}
adaptationSetChildren.accessibilities.push(accessibility);
const schemeAttrParser = generateSchemeAttrParser(accessibility,
linearMemory);
parsersStack.pushParsers(nodeId, noop, schemeAttrParser);
break;
}
case TagName.BaseURL: {
const baseUrl = { value: "", attributes: {} };
adaptationSetChildren.baseURLs.push(baseUrl);
const attributeParser = generateBaseUrlAttrParser(baseUrl, linearMemory);
parsersStack.pushParsers(nodeId, noop, attributeParser);
break;
}
case TagName.ContentComponent: {
const contentComponent = {};
adaptationSetChildren.contentComponent = contentComponent;
parsersStack.pushParsers(nodeId,
noop,
generateContentComponentAttrParser(contentComponent,
linearMemory));
break;
}
case TagName.ContentProtection: {
const contentProtection = { children: { cencPssh: [] },
attributes: {} };
if (adaptationSetChildren.contentProtections === undefined) {
adaptationSetChildren.contentProtections = [];
}
adaptationSetChildren.contentProtections.push(contentProtection);
const contentProtAttrParser =
generateContentProtectionAttrParser(contentProtection, linearMemory);
parsersStack.pushParsers(nodeId, noop, contentProtAttrParser);
break;
}
case TagName.EssentialProperty: {
const essentialProperty = {};
if (adaptationSetChildren.essentialProperties === undefined) {
adaptationSetChildren.essentialProperties = [];
}
adaptationSetChildren.essentialProperties.push(essentialProperty);
const childrenParser = noop; // EssentialProperty have no sub-element
const attributeParser = generateSchemeAttrParser(essentialProperty,
linearMemory);
parsersStack.pushParsers(nodeId, childrenParser, attributeParser);
break;
}
case TagName.InbandEventStream: {
const inbandEvent = {};
if (adaptationSetChildren.inbandEventStreams === undefined) {
adaptationSetChildren.inbandEventStreams = [];
}
adaptationSetChildren.inbandEventStreams.push(inbandEvent);
const childrenParser = noop; // InbandEventStream have no sub-element
const attributeParser = generateSchemeAttrParser(inbandEvent,
linearMemory);
parsersStack.pushParsers(nodeId, childrenParser, attributeParser);
break;
}
case TagName.Representation: {
const representationObj = { children: { baseURLs: [] },
attributes: {} };
adaptationSetChildren.representations.push(representationObj);
const childrenParser =
generateRepresentationChildrenParser(representationObj.children,
linearMemory,
parsersStack);
const attributeParser =
generateRepresentationAttrParser(representationObj.attributes, linearMemory);
parsersStack.pushParsers(nodeId, childrenParser, attributeParser);
break;
}
case TagName.Role: {
const role = {};
if (adaptationSetChildren.roles === undefined) {
adaptationSetChildren.roles = [];
}
adaptationSetChildren.roles.push(role);
const attributeParser = generateSchemeAttrParser(role,
linearMemory);
parsersStack.pushParsers(nodeId, noop, attributeParser);
break;
}
case TagName.SupplementalProperty: {
const supplementalProperty = {};
if (adaptationSetChildren.supplementalProperties === undefined) {
adaptationSetChildren.supplementalProperties = [];
}
adaptationSetChildren.supplementalProperties.push(supplementalProperty);
const attributeParser = generateSchemeAttrParser(supplementalProperty,
linearMemory);
parsersStack.pushParsers(nodeId, noop, attributeParser);
break;
}
case TagName.SegmentBase: {
const segmentBaseObj = {};
adaptationSetChildren.segmentBase = segmentBaseObj;
const attributeParser = generateSegmentBaseAttrParser(segmentBaseObj,
linearMemory);
parsersStack.pushParsers(nodeId, noop, attributeParser);
break;
}
case TagName.SegmentList: {
const segmentListObj : ISegmentListIntermediateRepresentation =
{ list: [] };
adaptationSetChildren.segmentList = segmentListObj;
const childrenParser = generateSegmentListChildrenParser(segmentListObj,
linearMemory,
parsersStack);
// Re-use SegmentBase attribute parse as we should have the same attributes
const attributeParser = generateSegmentBaseAttrParser(segmentListObj,
linearMemory);
parsersStack.pushParsers(nodeId, childrenParser, attributeParser);
break;
}
case TagName.SegmentTemplate: {
const stObj = {};
adaptationSetChildren.segmentTemplate = stObj;
parsersStack.pushParsers(nodeId,
noop, // SegmentTimeline as treated like an attribute
generateSegmentTemplateAttrParser(stObj, linearMemory));
break;
}
}
};
}
/**
* @param {Object} adaptationAttrs
* @param {WebAssembly.Memory} linearMemory
* @returns {Function}
*/
export function generateAdaptationSetAttrParser(
adaptationAttrs : IAdaptationSetAttributes,
linearMemory : WebAssembly.Memory
) : IAttributeParser {
const textDecoder = new TextDecoder();
return function onAdaptationSetAttribute(attr : number, ptr : number, len : number) {
const dataView = new DataView(linearMemory.buffer);
switch (attr) {
case AttributeName.Id:
adaptationAttrs.id = parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.Group:
adaptationAttrs.group = dataView.getFloat64(ptr, true);
break;
case AttributeName.Language:
adaptationAttrs.language =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.ContentType:
adaptationAttrs.contentType =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.Par:
adaptationAttrs.par = parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.MinBandwidth:
adaptationAttrs.minBitrate = dataView.getFloat64(ptr, true);
break;
case AttributeName.MaxBandwidth:
adaptationAttrs.maxBitrate = dataView.getFloat64(ptr, true);
break;
case AttributeName.MinWidth:
adaptationAttrs.minWidth = dataView.getFloat64(ptr, true);
break;
case AttributeName.MaxWidth:
adaptationAttrs.maxWidth = dataView.getFloat64(ptr, true);
break;
case AttributeName.MinHeight:
adaptationAttrs.minHeight = dataView.getFloat64(ptr, true);
break;
case AttributeName.MaxHeight:
adaptationAttrs.maxHeight = dataView.getFloat64(ptr, true);
break;
case AttributeName.MinFrameRate:
adaptationAttrs.minFrameRate =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.MaxFrameRate:
adaptationAttrs.maxFrameRate =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.SelectionPriority:
adaptationAttrs.selectionPriority = dataView.getFloat64(ptr, true);
break;
case AttributeName.SegmentAlignment:
adaptationAttrs.segmentAlignment =
parseFloatOrBool(dataView.getFloat64(ptr, true));
break;
case AttributeName.SubsegmentAlignment:
adaptationAttrs.subsegmentAlignment =
parseFloatOrBool(dataView.getFloat64(ptr, true));
break;
case AttributeName.BitstreamSwitching:
adaptationAttrs.bitstreamSwitching = dataView.getFloat64(ptr, true) !== 0;
break;
case AttributeName.AudioSamplingRate:
adaptationAttrs.audioSamplingRate =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.Codecs:
adaptationAttrs.codecs =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.Profiles:
adaptationAttrs.profiles =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.SegmentProfiles:
adaptationAttrs.segmentProfiles =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.MimeType:
adaptationAttrs.mimeType =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.CodingDependency:
adaptationAttrs.codingDependency = dataView.getFloat64(ptr, true) !== 0;
break;
case AttributeName.FrameRate:
adaptationAttrs.frameRate =
parseString(textDecoder, linearMemory.buffer, ptr, len);
break;
case AttributeName.Height:
adaptationAttrs.height = dataView.getFloat64(ptr, true);
break;
case AttributeName.Width:
adaptationAttrs.width = dataView.getFloat64(ptr, true);
break;
case AttributeName.MaxPlayoutRate:
adaptationAttrs.maxPlayoutRate = dataView.getFloat64(ptr, true);
break;
case AttributeName.MaxSAPPeriod:
adaptationAttrs.maximumSAPPeriod = dataView.getFloat64(ptr, true);
break;
// TODO
// case AttributeName.StartsWithSap:
// adaptationAttrs.startsWithSap = dataView.getFloat64(ptr, true);
}
};
} | the_stack |
import { isPrdApp } from '~/app/constants'
import Erd from '~/components/erd'
import { modelDetailSchema } from './model_detail'
import * as styled from './styled'
import * as tpl from './template'
import * as utils from './utils'
export default {
props: {
scopeRef: utils.scopeRefProp,
},
schema: {
type: 'page',
name: 'page',
title: '数据模型',
remark: isPrdApp ? '' : '数据模型可以用于在线生成API',
bodyClassName: 'p-none',
css: styled.modelListPageCss,
cssVars: {
'--Drawer-widthXl': '75%',
},
data: {
displayMode: utils.displayModeCtrl('get'),
},
toolbar: [
{
$preset: 'forms.switchMode',
},
{
$preset: 'actions.copyTable',
disabledOn: 'displayMode !== "list"',
},
{
$preset: 'actions.add',
disabledOn: 'displayMode !== "list"',
},
],
body: {
type: 'lib-when',
condition: (value) => {
return utils.displayModeCtrl('get') === value
},
cases: [
{
value: 'list',
...tpl.getModeList(),
},
{
value: 'diagram',
type: 'container',
body: {
component: Erd,
},
},
{
value: 'detail',
...modelDetailSchema,
},
],
},
definitions: {
fieldsTransfer: {
name: 'types',
type: 'transfer',
selectMode: 'tree',
selectTitle: '请选择字段',
resultTitle: '已选择的字段',
searchable: true,
sortable: true,
source: {
$preset: 'apis.listTable',
onSuccess: utils.onGetFieldOptsSuc,
},
},
},
preset: {
actions: {
add: {
limits: 'add',
type: 'button',
align: 'right',
actionType: 'dialog',
label: '添加模型',
icon: 'fa fa-plus pull-left',
size: 'sm',
primary: true,
dialog: {
title: '添加一个模型',
size: 'md',
bodyClassName: 'p-none',
body: '$preset.forms.addTable',
},
},
// viewTableData: {
// label: '${name}',
// size: 'lg',
// level: 'link',
// type: 'action',
// actionType: 'drawer',
// drawer: {
// title: '【${name}】模型数据',
// size: 'xl',
// closeOnEsc: true,
// resizable: true,
// actions: [],
// data: {
// id: '$id',
// name: '$name',
// items: [],
// },
// body: tpl.getModelDataTable(),
// },
// },
copyTable: {
limits: 'add',
type: 'button',
align: 'right',
actionType: 'dialog',
label: '复制模型',
hiddenOn: 'true',
icon: 'fa fa-copy pull-left',
size: 'sm',
dialog: {
title: '添加一个模型',
size: 'md',
bodyClassName: 'p-none',
body: '$preset.forms.addTable',
},
},
editTable: {
limits: 'edit',
type: 'action',
icon: 'fa fa-pencil pull-left',
label: '编辑',
actionType: 'dialog',
dialog: {
title: '编辑模型【$name】',
size: 'lg',
actions: [],
bodyClassName: 'p-none',
onClose: utils.onUpdateTableData,
body: '$preset.forms.updateTable',
},
},
delTable: {
limits: 'del',
type: 'action',
icon: 'fa fa-times pull-left',
level: 'danger',
actionType: 'ajax',
label: '删除',
confirmText: '删除后将不可恢复,您确认要删除模型【$name】 吗?',
api: '$preset.apis.delTable',
messages: {
success: '删除成功',
failed: '删除失败',
},
},
addField: {
limits: 'add',
type: 'button',
align: 'right',
label: '添加字段',
icon: 'fa fa-plus pull-left',
size: 'sm',
primary: true,
actionType: 'drawer',
drawer: {
position: 'right',
title: '【$tableName】添加一个字段',
size: 'md',
data: {
id: '$id',
tableName: '$name',
},
body: {
$preset: 'forms.updateField',
api: {
$preset: 'apis.addField',
onPreRequest: utils.onPreUpdateFiledReq,
onSuccess: utils.markTableListDataDirty,
},
},
},
},
batchAddField: {
hiddenOn: 'true',
limits: 'add',
type: 'button',
align: 'right',
actionType: 'dialog',
label: '快速添加',
icon: 'fa fa-paper-plane-o pull-left',
dialog: {
position: 'right',
title: '快速添加字段',
size: 'md',
body: {
$preset: 'forms.batchAddField',
},
},
},
copyAddField: {
hiddenOn: 'true',
limits: 'add',
type: 'button',
align: 'right',
label: '复制添加',
icon: 'fa fa-copy pull-left',
actionType: 'dialog',
dialog: {
title: '复制添加字段',
size: 'md',
body: {
$preset: 'forms.copyAddField',
},
},
},
copyField: {
hiddenOn: 'true',
limits: 'edit',
type: 'button',
icon: 'fa fa-copy',
tooltip: '复制字段',
},
editField: {
limits: 'edit',
type: 'button',
icon: 'fa fa-pencil',
tooltip: '编辑字段',
actionType: 'drawer',
drawer: {
position: 'right',
title: '编辑模型字段',
size: 'md',
body: {
$preset: 'forms.updateField',
api: {
$preset: 'apis.editField',
onPreRequest: utils.onPreUpdateFiledReq,
onSuccess: utils.markTableListDataDirty,
},
},
},
},
delField: {
limits: 'del',
type: 'button',
icon: 'fa fa-times text-danger',
actionType: 'ajax',
tooltip: '删除字段',
confirmText: '删除后将不可恢复,您确认要删除模型【$name】 吗?',
api: {
$preset: 'apis.delField',
onSuccess: utils.markTableListDataDirty,
},
messages: {
success: '删除成功',
failed: '删除失败',
},
},
},
forms: {
switchMode: {
type: 'form',
mode: 'inline',
target: 'page',
wrapWithPanel: false,
onInit: (_, formIns) => {
formIns.store.setValueByName('displayMode', utils.displayModeCtrl('get'))
},
controls: [
{
type: 'button-group',
name: 'displayMode',
submitOnChange: true,
onChange: (mode: string) => {
utils.displayModeCtrl('set', mode)
},
className: 'm-b-none',
options: [
{
label: '列表',
value: 'list',
size: 'sm',
},
!isPrdApp && {
label: '图示',
value: 'diagram',
size: 'sm',
},
{
label: '数据',
value: 'detail',
size: 'sm',
},
].filter(Boolean),
},
],
},
addTable: {
type: 'service',
api: '$preset.apis.fakeTableTemplate',
body: {
type: 'form',
mode: 'horizontal',
wrapWithPanel: false,
className: 'p-lg',
api: {
$preset: 'apis.addTable',
onPreRequest: utils.onPreUpdateTableReq,
},
controls: [
{
type: 'lib-renderer',
source: 'table',
renderer: 'sysSchemaService',
onSuccess: utils.onTableInfoSchemaSuc,
},
],
},
},
updateTable: {
type: 'lib-css',
css: ({ ns }) => `
.${ns}Table {
border: 0;
}
.${ns}Table-toolbar {
padding-left: 0;
}
`,
body: {
type: 'tabs',
mode: 'vertical',
tabs: [
{
title: '设置字段',
tab: {
type: 'service',
data: {
'&': '$$',
items: [],
},
body: {
type: 'lib-crud',
api: {
$preset: 'apis.tableInfo',
columnsTogglable: false,
affixHeader: false,
onSuccess: utils.onGetTableFileSuc,
},
defaultParams: {
perPage: 100,
},
loadDataOnce: true,
filter: false,
// draggable: true,
headerToolbar: [
{
align: 'left',
$preset: 'actions.addField',
},
{
align: 'left',
$preset: 'actions.batchAddField',
}, // copyAddField
{
align: 'left',
$preset: 'actions.copyAddField',
},
],
columns: [
{
type: 'operation',
label: '字段操作',
width: 100,
limits: ['edit', 'del'],
limitsLogic: 'or', // 满足 limits列表中 一个权限即可渲染
buttons: [
'$preset.actions.editField',
'$preset.actions.copyField',
'$preset.actions.delField',
],
},
...tpl.getTableFieldColumn(),
],
},
},
},
{
title: '基本信息',
tab: [
{
type: 'service',
api: '$preset.apis.fakeTableTemplate',
body: {
type: 'form',
mode: 'horizontal',
wrapWithPanel: false,
className: 'p-md',
api: {
$preset: 'apis.editTable',
onPreRequest: utils.onPreUpdateTableReq,
onSuccess: (source) => {
utils.onUpdateTableData(true)
return utils.onTableInfoSchemaSuc(source)
},
},
controls: [
{
type: 'lib-renderer',
source: 'table',
renderer: 'sysSchemaService',
onSuccess: utils.onTableInfoSchemaSuc,
},
{
type: 'divider',
},
{
type: 'container',
mode: 'inline',
body: [
{
limits: 'add',
type: 'action',
actionType: 'submit',
className: 'm-r-md',
primary: true,
label: '保存信息',
icon: 'fa fa-check pull-left',
size: 'md',
},
{
limits: 'add',
type: 'action',
actionType: 'close',
label: '关闭',
icon: 'fa fa-check pull-left',
size: 'md',
},
],
},
],
},
},
],
},
],
},
},
batchAddField: {
type: 'form',
controls: [
{
type: 'textarea',
name: 'namse',
label: '字段名称',
desc: '仅填写字段名称,多个字段用逗号隔开',
},
],
},
updateField: {
type: 'form',
mode: 'horizontal',
controls: [
{
type: 'text',
name: 'name',
label: '字段名称',
required: true,
desc: '用于区分数据模型的每一个属性,同一模型的名字不能重复',
},
{
type: 'textarea',
name: 'desc',
label: '字段描述',
desc: '字段底部显示的描述信息',
},
{
name: 'beanType',
type: 'select',
source: {
url: 'fakeFieldTypeOpts',
onFakeRequest: utils.onFakeFieldTypeOpts,
},
label: '字段类型',
value: 'TEXT',
required: true,
},
{
name: 'required',
type: 'switch',
required: true,
label: '是否必填',
falseValue: 0,
trueValue: 1,
value: 1,
},
{
type: 'lib-renderer',
initFetchSchemaOn: 'data.beanType',
updateDeps: ['beanType'],
renderer: 'sysSchemaService',
onSuccess: utils.onTableFieldSchemaSuc,
},
],
},
copyAddField: {
type: 'form',
mode: 'normal',
controls: [
{
$ref: 'fieldsTransfer',
},
],
},
},
},
},
}
// type: 'form',
// mode: 'normal',
// type: 'form',
// api: '$preset.apis.add',
// mode: 'normal',
// $preset: 'forms.add', | the_stack |
import { v4 as uuidv4 } from "uuid";
import "jest-extended";
import { Account } from "web3-core";
import { PluginRegistry } from "@hyperledger/cactus-core";
import {
EthContractInvocationType,
Web3SigningCredentialType,
PluginLedgerConnectorXdai,
PluginFactoryLedgerConnector,
Web3SigningCredentialCactusKeychainRef,
ReceiptType,
} from "../../../main/typescript/public-api";
import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory";
import {
K_DEV_WHALE_ACCOUNT_PRIVATE_KEY,
K_DEV_WHALE_ACCOUNT_PUBLIC_KEY,
OpenEthereumTestLedger,
} from "@hyperledger/cactus-test-tooling";
import { LogLevelDesc } from "@hyperledger/cactus-common";
import HelloWorldContractJson from "../../solidity/hello-world-contract/HelloWorld.json";
import Web3 from "web3";
import { PluginImportType } from "@hyperledger/cactus-core-api";
const logLevel: LogLevelDesc = "TRACE";
let xdaiTestLedger: OpenEthereumTestLedger;
const testCase = "Xdai Ledger Connector Plugin";
describe(testCase, () => {
let contractAddress: string;
const contractName = "HelloWorld";
const whalePubKey = K_DEV_WHALE_ACCOUNT_PUBLIC_KEY;
const whalePrivKey = K_DEV_WHALE_ACCOUNT_PRIVATE_KEY;
let keychainPlugin: PluginKeychainMemory;
let connector: PluginLedgerConnectorXdai;
let web3: Web3;
let testEthAccount: Account;
let keychainEntryKey: string;
let keychainEntryValue: string, rpcApiHttpHost: string;
beforeAll(async () => {
xdaiTestLedger = new OpenEthereumTestLedger({});
});
afterAll(async () => {
await xdaiTestLedger.stop();
await xdaiTestLedger.destroy();
});
beforeAll(async () => {
await xdaiTestLedger.start();
rpcApiHttpHost = await xdaiTestLedger.getRpcApiHttpHost();
expect(rpcApiHttpHost).toBeString();
web3 = new Web3(rpcApiHttpHost);
testEthAccount = web3.eth.accounts.create(uuidv4());
keychainEntryKey = uuidv4();
keychainEntryValue = testEthAccount.privateKey;
keychainPlugin = new PluginKeychainMemory({
instanceId: uuidv4(),
keychainId: uuidv4(),
// pre-provision keychain with mock backend holding the private key of the
// test account that we'll reference while sending requests with the
// signing credential pointing to this keychain entry.
backend: new Map([[keychainEntryKey, keychainEntryValue]]),
logLevel,
});
});
it("setup", async () => {
keychainPlugin.set(
HelloWorldContractJson.contractName,
JSON.stringify(HelloWorldContractJson),
);
const factory = new PluginFactoryLedgerConnector({
pluginImportType: PluginImportType.Local,
});
connector = await factory.create({
logLevel,
rpcApiHttpHost,
instanceId: uuidv4(),
pluginRegistry: new PluginRegistry({ plugins: [keychainPlugin] }),
});
await connector.transact({
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
consistencyStrategy: {
blockConfirmations: 0,
receiptType: ReceiptType.NodeTxPoolAck,
},
transactionConfig: {
from: whalePubKey,
to: testEthAccount.address,
value: 10e9,
gas: 1000000,
},
});
const balance = await web3.eth.getBalance(testEthAccount.address);
expect(balance).toBeTruthy();
expect(parseInt(balance, 10)).toEqual(10e9);
});
it("deploys contract via .json file", async () => {
const deployOut = await connector.deployContract({
keychainId: keychainPlugin.getKeychainId(),
contractName: HelloWorldContractJson.contractName,
// contractAbi: HelloWorldContractJson.abi,
constructorArgs: [],
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
// bytecode: HelloWorldContractJson.bytecode,
gas: 1000000,
});
expect(deployOut).toBeTruthy();
expect(deployOut.transactionReceipt).toBeTruthy();
expect(deployOut.transactionReceipt.contractAddress).toBeTruthy();
contractAddress = deployOut.transactionReceipt.contractAddress as string;
expect(contractAddress).toBeString();
const { callOutput: helloMsg } = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Call,
methodName: "sayHello",
params: [],
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
expect(helloMsg).toBeTruthy();
expect(helloMsg).toBeString();
});
it("invoke Web3SigningCredentialType.NONE", async () => {
const testEthAccount2 = web3.eth.accounts.create(uuidv4());
const { rawTransaction } = await web3.eth.accounts.signTransaction(
{
from: testEthAccount.address,
to: testEthAccount2.address,
value: 10e6,
gas: 1000000,
},
testEthAccount.privateKey,
);
await connector.transact({
web3SigningCredential: {
type: Web3SigningCredentialType.None,
},
consistencyStrategy: {
blockConfirmations: 0,
receiptType: ReceiptType.NodeTxPoolAck,
},
transactionConfig: {
rawTransaction,
},
});
const balance2 = await web3.eth.getBalance(testEthAccount2.address);
expect(balance2).toBeTruthy();
expect(parseInt(balance2, 10)).toEqual(10e6);
});
it("invoke Web3SigningCredentialType.PrivateKeyHex", async () => {
const newName = `DrCactus${uuidv4()}`;
const setNameOut = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Send,
methodName: "setName",
params: [newName],
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
nonce: 1,
});
expect(setNameOut).toBeTruthy();
try {
await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Send,
methodName: "setName",
params: [newName],
gas: 1000000,
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
nonce: 1,
});
fail("invalid nonce should have thrown");
} catch (error: any) {
expect(error.message).toContain("Transaction nonce is too low.");
}
const { callOutput: getNameOut } = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Call,
methodName: "getName",
params: [],
gas: 1000000,
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
expect(getNameOut).toEqual(newName);
const getNameOut2 = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Send,
methodName: "getName",
params: [],
gas: 1000000,
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
expect(getNameOut2).toBeTruthy();
const response = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Send,
methodName: "deposit",
params: [],
gas: 1000000,
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
value: 10,
});
expect(response).toBeTruthy();
const { callOutput } = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Call,
methodName: "getNameByIndex",
params: [0],
gas: 1000000,
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
expect(callOutput).toEqual(newName);
});
it("invoke Web3SigningCredentialType.CACTUSKEYCHAINREF", async () => {
const newName = `DrCactus${uuidv4()}`;
const web3SigningCredential: Web3SigningCredentialCactusKeychainRef = {
ethAccount: testEthAccount.address,
keychainEntryKey,
keychainId: keychainPlugin.getKeychainId(),
type: Web3SigningCredentialType.CactusKeychainRef,
};
const setNameOut = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Send,
methodName: "setName",
params: [newName],
gas: 1000000,
web3SigningCredential,
nonce: 4,
});
expect(setNameOut).toBeTruthy();
try {
await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Send,
methodName: "setName",
params: [newName],
gas: 1000000,
web3SigningCredential,
nonce: 4,
});
fail("invalid nonce should have thrown");
} catch (error: any) {
expect(error.message).toContain(
"Transaction with the same hash was already imported",
);
}
const { callOutput: getNameOut } = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Call,
methodName: "getName",
params: [],
gas: 1000000,
web3SigningCredential,
});
expect(getNameOut).toEqual(newName);
const getNameOut2 = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Send,
methodName: "getName",
params: [],
gas: 1000000,
web3SigningCredential,
});
expect(getNameOut2).toBeTruthy();
const response = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Send,
methodName: "deposit",
params: [],
gas: 1000000,
web3SigningCredential,
value: 10,
});
expect(response).toBeTruthy();
const { callOutput: callOut } = await connector.invokeContract({
contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Call,
methodName: "getNameByIndex",
params: [1],
gas: 1000000,
web3SigningCredential,
});
expect(callOut).toEqual(newName);
});
}); | the_stack |
import * as React from "react";
import * as Monaco from "monaco-editor";
import { default as MonacoEditor } from "../src/MonacoEditor";
import { mount } from "enzyme";
// Common Props required to instantiate MonacoEditor View, shared by all tests.
const monacoEditorCommonProps = {
id: "foo",
contentRef: "bar",
editorType: "monaco",
theme: "vs",
value: "test_value",
enableCompletion: true,
language: "python",
onCursorPositionChange: () => {},
};
describe("MonacoEditor component is rendering correctly", () => {
it("Should render MonacoEditor component", () => {
const editorWrapper = mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={false}
/>
);
expect(editorWrapper).not.toBeNull();
});
});
// Setup items shared by all tests in this block
// Mock out the common API methods so that private function calls don't fail
const mockEditor = {
onDidContentSizeChange: jest.fn(),
onDidChangeModelContent: jest.fn(),
onDidFocusEditorText: jest.fn(),
onDidBlurEditorText: jest.fn(),
onDidChangeCursorSelection: jest.fn(),
onDidBlurEditorWidget: jest.fn(),
onMouseMove: jest.fn(),
updateOptions: jest.fn(),
getValue: jest.fn(),
setValue: jest.fn(),
getConfiguration: jest.fn(),
layout: jest.fn(),
getModel: jest.fn(),
getSelection: jest.fn(),
focus: jest.fn(),
hasTextFocus: jest.fn(),
addCommand: jest.fn(),
changeViewZones: jest.fn(),
};
const mockEditorModel = {
updateOptions: jest.fn(),
};
const mockCreateEditor = jest.fn().mockReturnValue(mockEditor);
Monaco.editor.create = mockCreateEditor;
Monaco.editor.createModel = jest.fn().mockReturnValue(mockEditorModel);
MonacoEditor.prototype.calculateHeight = jest.fn();
MonacoEditor.prototype.registerDefaultCompletionProvider = jest.fn();
describe("MonacoEditor default completion provider", () => {
beforeAll(() => {
jest.clearAllMocks();
});
afterEach(() => {
jest.clearAllMocks();
});
it("Should call registerDefaultCompletionProvider method when registerCompletionUsingDefault is set to true", () => {
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={true}
enableCompletion={true}
shouldRegisterDefaultCompletion={true}
/>
);
expect(mockCreateEditor).toHaveBeenCalledTimes(1);
expect(
MonacoEditor.prototype.registerDefaultCompletionProvider
).toHaveBeenCalledTimes(1);
});
it("Should not call registerDefaultCompletionProvider method when registerCompletionUsingDefault is set to false", () => {
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={true}
enableCompletion={true}
shouldRegisterDefaultCompletion={false}
/>
);
expect(mockCreateEditor).toHaveBeenCalledTimes(1);
expect(
MonacoEditor.prototype.registerDefaultCompletionProvider
).toHaveBeenCalledTimes(0);
});
});
describe("MonacoEditor lifeCycle methods set up", () => {
beforeAll(() => {
jest.clearAllMocks();
});
afterEach(() => {
jest.clearAllMocks();
});
it("Should call calculateHeight method before rendering editor", () => {
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={true}
/>
);
expect(mockCreateEditor).toHaveBeenCalledTimes(1);
expect(MonacoEditor.prototype.calculateHeight).toHaveBeenCalledTimes(1);
});
it("Should set editor's focus on render if editorFocused prop is set and editor does not have focus", () => {
mockEditor.hasTextFocus = jest.fn().mockReturnValue(false);
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={true}
/>
);
expect(mockCreateEditor).toHaveBeenCalledTimes(1);
expect(mockEditor.focus).toHaveBeenCalledTimes(1);
});
it("Should not set editor's focus on render if editorFocused prop is set but editor already has focus", () => {
mockEditor.hasTextFocus = jest.fn().mockReturnValue(true);
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={true}
/>
);
expect(mockCreateEditor).toHaveBeenCalledTimes(1);
expect(mockEditor.focus).toHaveBeenCalledTimes(0);
});
it("Should not set editor's focus on render if editorFocused prop is false", () => {
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={false}
/>
);
expect(mockCreateEditor).toHaveBeenCalledTimes(1);
expect(mockEditor.focus).toHaveBeenCalledTimes(0);
});
it("Should call editor setValue when value prop has changed on componentDidUpdate.", () => {
mockEditor.setValue = jest.fn();
const editorWrapper = mount(
<MonacoEditor
{...monacoEditorCommonProps}
value="initial_value"
/>
);
editorWrapper.setProps({ value: "different_value" });
// We expect setValue is called twice. First on componentDidMount and second on componentDidUpdate
// when the props.value has new different value.
expect(mockEditor.setValue).toHaveBeenCalledTimes(2);
});
it("Should not call editor setValue when value prop has not changed on componentDidUpdate.", () => {
mockEditor.setValue = jest.fn();
const editorWrapper = mount(
<MonacoEditor
{...monacoEditorCommonProps}
value="initial_value"
/>
);
editorWrapper.setProps({ value: "initial_value" });
// We expect setValue is called once on componentDidMount when the props.value does not have different value.
expect(mockEditor.setValue).toHaveBeenCalledTimes(1);
});
});
describe("MonacoEditor lineNumbers configuration", () => {
beforeAll(() => {
jest.clearAllMocks();
});
afterEach(() => {
jest.clearAllMocks();
});
it("Should set lineNumbers on editor when set in props", () => {
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={false}
lineNumbers={true}
/>
);
expect(mockCreateEditor).toHaveBeenCalledTimes(1);
// Get the second arg to Monaco.editor.create call
const editorCreateArgs = mockCreateEditor.mock.calls[0][1];
expect(editorCreateArgs).toHaveProperty("lineNumbers");
expect(editorCreateArgs.lineNumbers).toEqual("on");
});
it("Should not set lineNumbers on editor when set to false in props", () => {
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={false}
lineNumbers={false}
/>
);
expect(mockCreateEditor).toHaveBeenCalledTimes(1);
// Get the second arg to Monaco.editor.create call
const editorCreateArgs = mockCreateEditor.mock.calls[0][1];
expect(editorCreateArgs).toHaveProperty("lineNumbers");
expect(editorCreateArgs.lineNumbers).toEqual("off");
});
});
describe("MonacoEditor resize handler when window size changes", () => {
beforeAll(() => {
jest.clearAllMocks();
});
afterEach(() => {
jest.clearAllMocks();
});
it("Should not call resize handler at all when window is not resized", () => {
// Create a new editor instance with the mock layout
const mockEditorLayout = jest.fn();
const newMockEditor = {...mockEditor};
newMockEditor.layout = mockEditorLayout;
mockCreateEditor.mockReturnValue(newMockEditor);
// We spy on the resize handler calls without changing the implementation
const resizeHandlerSpy = jest.spyOn(MonacoEditor.prototype, "resize");
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={false}
/>
);
expect(mockCreateEditor).toHaveBeenCalledTimes(1);
// Resize handler should be called
expect(resizeHandlerSpy).toHaveBeenCalledTimes(0);
// editor.layout should not be called
expect(mockEditorLayout).toHaveBeenCalledTimes(0);
// Restore spy
resizeHandlerSpy.mockRestore();
});
it("Resize handler should not trigger editor.layout when it is not focused", () => {
// This is a perf optimization to reduce layout calls for unfocussed editors
// Create a new editor instance with the mock layout
const mockEditorLayout = jest.fn();
const newMockEditor = {...mockEditor};
newMockEditor.layout = mockEditorLayout;
mockCreateEditor.mockReturnValue(newMockEditor);
// We spy on the resize handler calls without changing the implementation
const resizeHandlerSpy = jest.spyOn(MonacoEditor.prototype, "resize");
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={false}
/>
);
(window as any).innerWidth = 500;
window.dispatchEvent(new Event('resize'));
// Resize handler should be called
expect(resizeHandlerSpy).toHaveBeenCalledTimes(1);
// editor.layout should not be called
expect(mockEditorLayout).toHaveBeenCalledTimes(0);
// Restore spy
resizeHandlerSpy.mockRestore();
});
it("Resize handler should trigger an editor.layout call for a focused editor", () => {
// Create a new editor instance with the mock layout
const mockEditorLayout = jest.fn();
const newMockEditor = {...mockEditor};
newMockEditor.layout = mockEditorLayout;
mockCreateEditor.mockReturnValue(newMockEditor);
// We spy on the resize handler calls without changing the implementation
const resizeHandlerSpy = jest.spyOn(MonacoEditor.prototype, "resize");;
mount(
<MonacoEditor
{...monacoEditorCommonProps}
channels={undefined}
onChange={jest.fn()}
onFocusChange={jest.fn()}
editorFocused={true}
/>
);
(window as any).innerWidth = 500;
window.dispatchEvent(new Event('resize'));
expect(resizeHandlerSpy).toHaveBeenCalledTimes(1);
expect(mockEditorLayout).toHaveBeenCalledTimes(1);
// Restore spy
resizeHandlerSpy.mockRestore();
});
}); | the_stack |
import * as React from 'react';
import { mount } from 'enzyme';
import { pluginDepsToComponents, getComputedState } from '@devexpress/dx-testing';
import { PluginHost } from '@devexpress/dx-react-core';
import {
closeGroupGetter,
rowsToExport,
buildGroupTree,
groupOutlineLevels,
exportSummaryGetter,
maximumGroupLevel,
} from '@devexpress/dx-grid-core';
import {
GridExporterCore,
} from './grid-exporter-core';
import {
createWorkbook,
createWorksheet,
} from './helpers';
/* tslint:disable no-submodule-imports */
import {
GroupingState,
IntegratedGrouping,
SummaryState,
IntegratedSummary,
SelectionState,
FilteringState,
IntegratedFiltering,
IntegratedSorting,
SortingState,
} from '@devexpress/dx-react-grid';
import { defaultSummaryMessages } from '@devexpress/dx-react-grid/src/components/summary/constants';
import {
GridCoreGetters, TableColumnsWithDataRowsGetter, TableColumnsWithGrouping,
VisibleTableColumns, OrderedTableColumns,
} from '@devexpress/dx-react-grid/src/plugins/internal';
/* tslint:enable no-submodule-imports */
jest.mock('@devexpress/dx-react-grid/src/plugins/internal', () => ({
GridCoreGetters: () => null,
TableColumnsWithGrouping: () => null,
TableColumnsWithDataRowsGetter: () => null,
VisibleTableColumns: () => null,
OrderedTableColumns: () => null,
}));
jest.mock('@devexpress/dx-grid-core', () => ({
getColumnExtensionValueGetter: jest.fn(),
groupedRows: jest.fn(),
expandedGroupRows: jest.fn(),
groupCollapsedRowsGetter: jest.fn(),
rowsToExport: jest.fn(),
groupOutlineLevels: jest.fn(),
buildGroupTree: jest.fn(),
maximumGroupLevel: jest.fn(),
closeGroupGetter: jest.fn(),
closeSheet: jest.fn(),
exportHeader: jest.fn(),
exportRows: jest.fn(),
exportSummaryGetter: jest.fn(),
prepareGroupSummaryItems: jest.fn(),
unwrappedFilteredRows: jest.fn(),
filteredCollapsedRowsGetter: jest.fn(),
filterExpression: jest.fn(),
filteredRows: jest.fn(),
sortedRows: jest.fn(),
}));
jest.mock('./helpers', () => ({
createWorkbook: jest.fn(),
createWorksheet: jest.fn(),
}));
const defaultProps = {
rows: [],
columns: [],
getRowId: () => {},
getCellValue: () => {},
onSave: jest.fn(),
};
const defaultDeps = {
getter: {
rows: [],
columns: [],
tableColumns: [],
grouping: [],
groupSummaryItems: [],
getCollapsedRows: () => null,
getRowId: () => null,
isGroupRow: () => null,
},
action: {
performExport: jest.fn(),
finishExport: jest.fn(),
},
};
describe('GridExporter', () => {
beforeEach(() => {
rowsToExport.mockReturnValue('rowsToExport');
buildGroupTree.mockReturnValue('buildGroupTree');
groupOutlineLevels.mockReturnValue('groupOutlineLevels');
maximumGroupLevel.mockReturnValue('maximumGroupLevel');
exportSummaryGetter.mockReturnValue('exportSummaryGetter');
createWorkbook.mockReturnValue('workbook');
createWorksheet.mockReturnValue('worksheet');
closeGroupGetter.mockReturnValue('closeGroupGetter');
});
afterEach(jest.clearAllMocks);
it('should export grid when rendered', () => {
mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
</PluginHost>
));
expect(defaultDeps.action.performExport)
.toHaveBeenCalledTimes(1);
expect(defaultDeps.action.finishExport)
.toHaveBeenCalledTimes(1);
});
describe('getters', () => {
it('should provide grid basic getters', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
</PluginHost>
));
expect(tree.find(GridCoreGetters).props())
.toEqual({
rows: defaultProps.rows,
columns: defaultProps.columns,
getRowId: defaultProps.getRowId,
getCellValue: defaultProps.getCellValue,
});
});
it('should provide tableColumns', () => {
const columnExtensions = [{ columnName: 'a', width: 200 }];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} columnExtensions={columnExtensions} />
</PluginHost>
));
expect(tree.find(TableColumnsWithDataRowsGetter).props())
.toEqual({
columnExtensions,
});
});
it('should provide workbook', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
{/* NOTE: exporter overwrites the root template */}
{pluginDepsToComponents({})}
</PluginHost>
));
expect(getComputedState(tree).workbook)
.toBe('workbook');
});
it('should provide worksheet', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
{pluginDepsToComponents({})}
</PluginHost>
));
expect(getComputedState(tree).worksheet)
.toBe('worksheet');
});
it('should provide maxGroupLevel', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
{pluginDepsToComponents({})}
</PluginHost>
));
expect(getComputedState(tree).maxGroupLevel)
.toBe('maximumGroupLevel');
expect(maximumGroupLevel)
.toHaveBeenCalledWith(
defaultDeps.getter.grouping,
);
});
it('should provide groupOutlineLevels', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
{pluginDepsToComponents({})}
</PluginHost>
));
expect(getComputedState(tree).outlineLevels)
.toBe('groupOutlineLevels');
expect(groupOutlineLevels)
.toHaveBeenCalledWith(
defaultDeps.getter.grouping,
);
});
it('should provide isExporting getter', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
{pluginDepsToComponents({})}
</PluginHost>
));
expect(getComputedState(tree).isExporting)
.toBe(true);
});
it('should extend rows', () => {
const selection = ['1', '2'];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
selection={selection}
exportSelected
/>
{pluginDepsToComponents({})}
</PluginHost>
));
expect(getComputedState(tree).rows)
.toBe('rowsToExport');
expect(rowsToExport)
.toHaveBeenCalledWith(
defaultDeps.getter.rows,
selection,
defaultDeps.getter.grouping,
defaultDeps.getter.getCollapsedRows,
defaultDeps.getter.getRowId,
defaultDeps.getter.isGroupRow,
);
});
it('should provide groupTree', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
{/* NOTE: exporter overwrites the root template */}
{pluginDepsToComponents({})}
</PluginHost>
));
expect(getComputedState(tree).groupTree)
.toBe('buildGroupTree');
expect(buildGroupTree)
.toHaveBeenCalledWith(
'rowsToExport',
'groupOutlineLevels',
defaultDeps.getter.grouping,
defaultDeps.getter.isGroupRow,
defaultDeps.getter.groupSummaryItems,
);
});
it('should provide exportSummary function', () => {
const customizeSummaryCell = () => {};
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
customizeSummaryCell={customizeSummaryCell}
/>
{pluginDepsToComponents({})}
</PluginHost>
));
expect(getComputedState(tree).exportSummary)
.toBe('exportSummaryGetter');
expect(exportSummaryGetter)
.toHaveBeenCalledWith(
'worksheet',
defaultDeps.getter.columns,
customizeSummaryCell,
defaultSummaryMessages,
);
});
it('should provide getCloseGroup function', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
/>
{pluginDepsToComponents({})}
</PluginHost>
));
expect(getComputedState(tree).getCloseGroup)
.toBe('closeGroupGetter');
expect(closeGroupGetter)
.toHaveBeenCalledWith(
'worksheet',
'buildGroupTree',
'groupOutlineLevels',
'maximumGroupLevel',
defaultDeps.getter.groupSummaryItems,
'exportSummaryGetter',
);
});
});
describe('feature plugins', () => {
describe('grouping', () => {
it('should render grouping plugins if grouping is provided', () => {
const grouping = [{ columnName: 'a' }];
const groupColumnExtensions = [{ columnName: 'a', showWhenGrouped: false }];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
grouping={grouping}
groupColumnExtensions={groupColumnExtensions}
showColumnsWhenGrouped={true}
/>
</PluginHost>
));
expect(tree.find(GroupingState).props())
.toMatchObject({
grouping,
});
expect(tree.find(TableColumnsWithGrouping).props())
.toMatchObject({
columnExtensions: groupColumnExtensions,
showColumnsWhenGrouped: true,
});
expect(tree.find(IntegratedGrouping).exists())
.toBeTruthy();
});
it('should not render grouping plugins if grouping is not provided', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
</PluginHost>
));
expect(tree.find(GroupingState).exists())
.toBeFalsy();
expect(tree.find(TableColumnsWithGrouping).exists())
.toBeFalsy();
expect(tree.find(IntegratedGrouping).exists())
.toBeFalsy();
});
});
describe('summary', () => {
it('should not render summary plugins if summary is not provided', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
</PluginHost>
));
expect(tree.find(SummaryState).exists())
.toBeFalsy();
expect(tree.find(IntegratedSummary).exists())
.toBeFalsy();
});
it('should render summary plugins if summary items are provided', () => {
const totalItems = [{ columnName: 'a', type: 'max' }];
const groupItems = [{ columnName: 'b', type: 'min' }];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
totalSummaryItems={totalItems}
groupSummaryItems={groupItems}
/>
</PluginHost>
));
expect(tree.find(SummaryState).props())
.toMatchObject({
totalItems,
groupItems,
});
expect(tree.find(IntegratedSummary).exists())
.toBeTruthy();
});
});
describe('selection', () => {
it('should not render SelectionState if selection is not provided', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} exportSelected />
</PluginHost>
));
expect(tree.find(SelectionState).exists())
.toBeFalsy();
});
it('should not render SelectionState if exportSelected is false', () => {
const selection = ['1', '2'];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} selection={selection} />
</PluginHost>
));
expect(tree.find(SelectionState).exists())
.toBeFalsy();
});
it('should render SelectionState if selection is provided', () => {
const selection = ['1', '2'];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
selection={selection}
exportSelected
/>
</PluginHost>
));
expect(tree.find(SelectionState).props())
.toMatchObject({ selection });
});
});
describe('filtering', () => {
it('should render filtering plugins if filters are provided', () => {
const filters = [{ columnName: 'a', value: 1 }];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
filters={filters}
/>
</PluginHost>
));
expect(tree.find(FilteringState).props())
.toMatchObject({
filters,
});
expect(tree.find(IntegratedFiltering).exists())
.toBeTruthy();
});
it('should not render filtering plugins if filters are not provided', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
</PluginHost>
));
expect(tree.find(FilteringState).exists())
.toBeFalsy();
expect(tree.find(IntegratedFiltering).exists())
.toBeFalsy();
});
});
describe('sorting', () => {
it('should render sorting plugins if sorting is provided', () => {
const sorting = [{ columnName: 'a', direction: 'asc' }];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
sorting={sorting}
/>
</PluginHost>
));
expect(tree.find(SortingState).props())
.toMatchObject({
sorting,
});
expect(tree.find(IntegratedSorting).exists())
.toBeTruthy();
});
it('should not render sorting plugins if sorting is not provided', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
</PluginHost>
));
expect(tree.find(SortingState).exists())
.toBeFalsy();
expect(tree.find(IntegratedSorting).exists())
.toBeFalsy();
});
});
describe('column visibility', () => {
it('should render column visibility plugin if hiddenColumnNames is provided', () => {
const hiddenColumnNames = ['a'];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
hiddenColumnNames={hiddenColumnNames}
/>
</PluginHost>
));
expect(tree.find(VisibleTableColumns).props())
.toMatchObject({
hiddenColumnNames,
});
});
it('should not render column visibility plugin if hiddenColumnNames not provided', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
</PluginHost>
));
expect(tree.find(VisibleTableColumns).exists())
.toBeFalsy();
});
});
describe('column order', () => {
it('should render column order plugin if order is provided', () => {
const columnOrder = ['a', 'b'];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore
{...defaultProps}
columnOrder={columnOrder}
/>
</PluginHost>
));
expect(tree.find(OrderedTableColumns).props())
.toMatchObject({
order: columnOrder,
});
});
it('should not render column order plugins if order is not provided', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GridExporterCore {...defaultProps} />
</PluginHost>
));
expect(tree.find(OrderedTableColumns).exists())
.toBeFalsy();
});
});
});
}); | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import { duration } from 'moment';
import { OpenSearchClientConfig, parseClientOptions } from './client_config';
import { DEFAULT_HEADERS } from '../default_headers';
const createConfig = (parts: Partial<OpenSearchClientConfig> = {}): OpenSearchClientConfig => {
return {
customHeaders: {},
logQueries: false,
sniffOnStart: false,
sniffOnConnectionFault: false,
sniffInterval: false,
requestHeadersWhitelist: ['authorization'],
hosts: ['http://localhost:80'],
...parts,
};
};
describe('parseClientOptions', () => {
it('includes headers designing the HTTP request as originating from OpenSearch Dashboards by default', () => {
const config = createConfig({});
expect(parseClientOptions(config, false)).toEqual(
expect.objectContaining({
headers: {
...DEFAULT_HEADERS,
},
})
);
});
describe('basic options', () => {
it('`customHeaders` option', () => {
const config = createConfig({
customHeaders: {
foo: 'bar',
hello: 'dolly',
},
});
expect(parseClientOptions(config, false)).toEqual(
expect.objectContaining({
headers: {
...DEFAULT_HEADERS,
foo: 'bar',
hello: 'dolly',
},
})
);
});
it('`customHeaders` take precedence to default opensearchDashboards headers', () => {
const customHeader = {
[Object.keys(DEFAULT_HEADERS)[0]]: 'foo',
};
const config = createConfig({
customHeaders: {
...customHeader,
},
});
expect(parseClientOptions(config, false)).toEqual(
expect.objectContaining({
headers: {
...customHeader,
},
})
);
});
it('`keepAlive` option', () => {
expect(parseClientOptions(createConfig({ keepAlive: true }), false)).toEqual(
expect.objectContaining({ agent: { keepAlive: true } })
);
expect(parseClientOptions(createConfig({ keepAlive: false }), false).agent).toBeUndefined();
});
it('`sniffOnStart` options', () => {
expect(
parseClientOptions(
createConfig({
sniffOnStart: true,
}),
false
).sniffOnStart
).toEqual(true);
expect(
parseClientOptions(
createConfig({
sniffOnStart: false,
}),
false
).sniffOnStart
).toEqual(false);
});
it('`sniffOnConnectionFault` options', () => {
expect(
parseClientOptions(
createConfig({
sniffOnConnectionFault: true,
}),
false
).sniffOnConnectionFault
).toEqual(true);
expect(
parseClientOptions(
createConfig({
sniffOnConnectionFault: false,
}),
false
).sniffOnConnectionFault
).toEqual(false);
});
it('`sniffInterval` options', () => {
expect(
parseClientOptions(
createConfig({
sniffInterval: false,
}),
false
).sniffInterval
).toEqual(false);
expect(
parseClientOptions(
createConfig({
sniffInterval: duration(100, 'ms'),
}),
false
).sniffInterval
).toEqual(100);
});
it('`hosts` option', () => {
const options = parseClientOptions(
createConfig({
hosts: ['http://node-A:9200', 'http://node-B', 'https://node-C'],
}),
false
);
expect(options.nodes).toMatchInlineSnapshot(`
Array [
Object {
"url": "http://node-a:9200/",
},
Object {
"url": "http://node-b/",
},
Object {
"url": "https://node-c/",
},
]
`);
});
});
describe('authorization', () => {
describe('when `scoped` is false', () => {
it('adds the `auth` option if both `username` and `password` are set', () => {
expect(
parseClientOptions(
createConfig({
username: 'user',
}),
false
).auth
).toBeUndefined();
expect(
parseClientOptions(
createConfig({
password: 'pass',
}),
false
).auth
).toBeUndefined();
expect(
parseClientOptions(
createConfig({
username: 'user',
password: 'pass',
}),
false
)
).toEqual(
expect.objectContaining({
auth: {
username: 'user',
password: 'pass',
},
})
);
});
it('does not add auth to the nodes', () => {
const options = parseClientOptions(
createConfig({
username: 'user',
password: 'pass',
hosts: ['http://node-A:9200'],
}),
true
);
expect(options.nodes).toMatchInlineSnapshot(`
Array [
Object {
"url": "http://node-a:9200/",
},
]
`);
});
});
describe('when `scoped` is true', () => {
it('does not add the `auth` option even if both `username` and `password` are set', () => {
expect(
parseClientOptions(
createConfig({
username: 'user',
password: 'pass',
}),
true
).auth
).toBeUndefined();
});
it('does not add auth to the nodes even if both `username` and `password` are set', () => {
const options = parseClientOptions(
createConfig({
username: 'user',
password: 'pass',
hosts: ['http://node-A:9200'],
}),
true
);
expect(options.nodes).toMatchInlineSnapshot(`
Array [
Object {
"url": "http://node-a:9200/",
},
]
`);
});
});
});
describe('ssl config', () => {
it('does not generate ssl option is ssl config is not set', () => {
expect(parseClientOptions(createConfig({}), false).ssl).toBeUndefined();
expect(parseClientOptions(createConfig({}), true).ssl).toBeUndefined();
});
it('handles the `certificateAuthorities` option', () => {
expect(
parseClientOptions(
createConfig({
ssl: { verificationMode: 'full', certificateAuthorities: ['content-of-ca-path'] },
}),
false
).ssl!.ca
).toEqual(['content-of-ca-path']);
expect(
parseClientOptions(
createConfig({
ssl: { verificationMode: 'full', certificateAuthorities: ['content-of-ca-path'] },
}),
true
).ssl!.ca
).toEqual(['content-of-ca-path']);
});
describe('verificationMode', () => {
it('handles `none` value', () => {
expect(
parseClientOptions(
createConfig({
ssl: {
verificationMode: 'none',
},
}),
false
).ssl
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
"rejectUnauthorized": false,
}
`);
});
it('handles `certificate` value', () => {
expect(
parseClientOptions(
createConfig({
ssl: {
verificationMode: 'certificate',
},
}),
false
).ssl
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
"checkServerIdentity": [Function],
"rejectUnauthorized": true,
}
`);
});
it('handles `full` value', () => {
expect(
parseClientOptions(
createConfig({
ssl: {
verificationMode: 'full',
},
}),
false
).ssl
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
"rejectUnauthorized": true,
}
`);
});
it('throws for invalid values', () => {
expect(
() =>
parseClientOptions(
createConfig({
ssl: {
verificationMode: 'unknown' as any,
},
}),
false
).ssl
).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: unknown"`);
});
it('throws for undefined values', () => {
expect(
() =>
parseClientOptions(
createConfig({
ssl: {
verificationMode: undefined as any,
},
}),
false
).ssl
).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: undefined"`);
});
});
describe('`certificate`, `key` and `passphrase`', () => {
it('are not added if `key` is not present', () => {
expect(
parseClientOptions(
createConfig({
ssl: {
verificationMode: 'full',
certificate: 'content-of-cert',
keyPassphrase: 'passphrase',
},
}),
false
).ssl
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
"rejectUnauthorized": true,
}
`);
});
it('are not added if `certificate` is not present', () => {
expect(
parseClientOptions(
createConfig({
ssl: {
verificationMode: 'full',
key: 'content-of-key',
keyPassphrase: 'passphrase',
},
}),
false
).ssl
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
"rejectUnauthorized": true,
}
`);
});
it('are added if `key` and `certificate` are present and `scoped` is false', () => {
expect(
parseClientOptions(
createConfig({
ssl: {
verificationMode: 'full',
key: 'content-of-key',
certificate: 'content-of-cert',
keyPassphrase: 'passphrase',
},
}),
false
).ssl
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
"cert": "content-of-cert",
"key": "content-of-key",
"passphrase": "passphrase",
"rejectUnauthorized": true,
}
`);
});
it('are not added if `scoped` is true unless `alwaysPresentCertificate` is true', () => {
expect(
parseClientOptions(
createConfig({
ssl: {
verificationMode: 'full',
key: 'content-of-key',
certificate: 'content-of-cert',
keyPassphrase: 'passphrase',
},
}),
true
).ssl
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
"rejectUnauthorized": true,
}
`);
expect(
parseClientOptions(
createConfig({
ssl: {
verificationMode: 'full',
key: 'content-of-key',
certificate: 'content-of-cert',
keyPassphrase: 'passphrase',
alwaysPresentCertificate: true,
},
}),
true
).ssl
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
"cert": "content-of-cert",
"key": "content-of-key",
"passphrase": "passphrase",
"rejectUnauthorized": true,
}
`);
});
});
});
}); | the_stack |
import $1 from "../Components/ScrollView/ScrollView";
import $2 from "../Components/View/View";
import * as React from "react";
import { ScrollResponderType } from "../Components/ScrollView/ScrollView";
import { ViewStyleProp } from "../StyleSheet/StyleSheet";
import { ViewabilityConfig } from "./ViewabilityHelper";
import { ViewToken } from "./ViewabilityHelper";
import { ViewabilityConfigCallbackPair } from "./ViewabilityHelper";
import { VirtualizedListContext } from "./VirtualizedListContext.js";
declare type Item = any;
declare type Separators = {
highlight: () => void;
unhighlight: () => void;
updateProps: (select: "leading" | "trailing", newProps: Object) => void;
};
declare type RenderItemProps<ItemT> = {
item: ItemT;
index: number;
separators: Separators;
};
declare type RenderItemType<ItemT> = (info: RenderItemProps<ItemT>) => React.Node;
declare type RequiredProps =
/*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/
{
/**
* The default accessor functions assume this is an Array<{key: string} | {id: string}> but you can override
* getItem, getItemCount, and keyExtractor to handle any type of index-based data.
*/
data?: any;
/**
* A generic accessor for extracting an item from any sort of data blob.
*/
getItem: (data: any, index: number) => null | undefined | Item;
/**
* Determines how many items are in the data blob.
*/
getItemCount: (data: any) => number;
};
declare type OptionalProps =
/*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/
{
renderItem?: null | undefined | RenderItemType<Item>;
/**
* `debug` will turn on extra logging and visual overlays to aid with debugging both usage and
* implementation, but with a significant perf hit.
*/
debug?: null | undefined | boolean;
/**
* DEPRECATED: Virtualization provides significant performance and memory optimizations, but fully
* unmounts react instances that are outside of the render window. You should only need to disable
* this for debugging purposes.
*/
disableVirtualization?: null | undefined | boolean;
/**
* A marker property for telling the list to re-render (since it implements `PureComponent`). If
* any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the
* `data` prop, stick it here and treat it immutably.
*/
extraData?: any;
// e.g. height, y
getItemLayout?: (data: any, index: number) => {
length: number;
offset: number;
index: number;
};
horizontal?: null | undefined | boolean;
/**
* How many items to render in the initial batch. This should be enough to fill the screen but not
* much more. Note these items will never be unmounted as part of the windowed rendering in order
* to improve perceived performance of scroll-to-top actions.
*/
initialNumToRender: number;
/**
* Instead of starting at the top with the first item, start at `initialScrollIndex`. This
* disables the "scroll to top" optimization that keeps the first `initialNumToRender` items
* always rendered and immediately renders the items starting at this initial index. Requires
* `getItemLayout` to be implemented.
*/
initialScrollIndex?: null | undefined | number;
/**
* Reverses the direction of scroll. Uses scale transforms of -1.
*/
inverted?: null | undefined | boolean;
keyExtractor: (item: Item, index: number) => string;
/**
* Each cell is rendered using this element. Can be a React Component Class,
* or a render function. Defaults to using View.
*/
CellRendererComponent?: null | undefined | React.ComponentType<any>;
/**
* Rendered in between each item, but not at the top or bottom. By default, `highlighted` and
* `leadingItem` props are provided. `renderItem` provides `separators.highlight`/`unhighlight`
* which will update the `highlighted` prop, but you can also add custom props with
* `separators.updateProps`.
*/
ItemSeparatorComponent?: null | undefined | React.ComponentType<any>;
/**
* Takes an item from `data` and renders it into the list. Example usage:
*
* <FlatList
* ItemSeparatorComponent={Platform.OS !== 'android' && ({highlighted}) => (
* <View style={[style.separator, highlighted && {marginLeft: 0}]} />
* )}
* data={[{title: 'Title Text', key: 'item1'}]}
* ListItemComponent={({item, separators}) => (
* <TouchableHighlight
* onPress={() => this._onPress(item)}
* onShowUnderlay={separators.highlight}
* onHideUnderlay={separators.unhighlight}>
* <View style={{backgroundColor: 'white'}}>
* <Text>{item.title}</Text>
* </View>
* </TouchableHighlight>
* )}
* />
*
* Provides additional metadata like `index` if you need it, as well as a more generic
* `separators.updateProps` function which let's you set whatever props you want to change the
* rendering of either the leading separator or trailing separator in case the more common
* `highlight` and `unhighlight` (which set the `highlighted: boolean` prop) are insufficient for
* your use-case.
*/
ListItemComponent?: null | undefined | (React.ComponentType<any> | React.Element<any>);
/**
* Rendered when the list is empty. Can be a React Component Class, a render function, or
* a rendered element.
*/
ListEmptyComponent?: null | undefined | (React.ComponentType<any> | React.Element<any>);
/**
* Rendered at the bottom of all the items. Can be a React Component Class, a render function, or
* a rendered element.
*/
ListFooterComponent?: null | undefined | (React.ComponentType<any> | React.Element<any>);
/**
* Styling for internal View for ListFooterComponent
*/
ListFooterComponentStyle?: ViewStyleProp;
/**
* Rendered at the top of all the items. Can be a React Component Class, a render function, or
* a rendered element.
*/
ListHeaderComponent?: null | undefined | (React.ComponentType<any> | React.Element<any>);
/**
* Styling for internal View for ListHeaderComponent
*/
ListHeaderComponentStyle?: ViewStyleProp;
/**
* A unique identifier for this list. If there are multiple VirtualizedLists at the same level of
* nesting within another VirtualizedList, this key is necessary for virtualization to
* work properly.
*/
listKey?: string;
/**
* The maximum number of items to render in each incremental render batch. The more rendered at
* once, the better the fill rate, but responsiveness may suffer because rendering content may
* interfere with responding to button taps or other interactions.
*/
maxToRenderPerBatch: number;
/**
* Called once when the scroll position gets within `onEndReachedThreshold` of the rendered
* content.
*/
onEndReached?: null | undefined | ((info: {
distanceFromEnd: number;
}) => void);
/**
* How far from the end (in units of visible length of the list) the bottom edge of the
* list must be from the end of the content to trigger the `onEndReached` callback.
* Thus a value of 0.5 will trigger `onEndReached` when the end of the content is
* within half the visible length of the list.
*/
onEndReachedThreshold?: null | undefined | number;
/**
* If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make
* sure to also set the `refreshing` prop correctly.
*/
onRefresh?: null | undefined | (() => void);
/**
* Used to handle failures when scrolling to an index that has not been measured yet. Recommended
* action is to either compute your own offset and `scrollTo` it, or scroll as far as possible and
* then try again after more items have been rendered.
*/
onScrollToIndexFailed?: null | undefined | ((info: {
index: number;
highestMeasuredFrameIndex: number;
averageItemLength: number;
}) => void);
/**
* Called when the viewability of rows changes, as defined by the
* `viewabilityConfig` prop.
*/
onViewableItemsChanged?: null | undefined | ((info: {
viewableItems: ViewToken[];
changed: ViewToken[];
}) => void);
persistentScrollbar?: null | undefined | boolean;
/**
* Set this when offset is needed for the loading indicator to show correctly.
* @platform android
*/
progressViewOffset?: number;
/**
* A custom refresh control element. When set, it overrides the default
* <RefreshControl> component built internally. The onRefresh and refreshing
* props are also ignored. Only works for vertical VirtualizedList.
*/
refreshControl?: null | undefined | React.Element<any>;
/**
* Set this true while waiting for new data from a refresh.
*/
refreshing?: null | undefined | boolean;
/**
* Note: may have bugs (missing content) in some circumstances - use at your own risk.
*
* This may improve scroll performance for large lists.
*/
removeClippedSubviews?: boolean;
/**
* Render a custom scroll component, e.g. with a differently styled `RefreshControl`.
*/
renderScrollComponent?: (props: Object) => React.Element<any>;
/**
* Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off
* screen. Similar fill rate/responsiveness tradeoff as `maxToRenderPerBatch`.
*/
updateCellsBatchingPeriod: number;
/**
* See `ViewabilityHelper` for flow type and further documentation.
*/
viewabilityConfig?: ViewabilityConfig;
/**
* List of ViewabilityConfig/onViewableItemsChanged pairs. A specific onViewableItemsChanged
* will be called when its corresponding ViewabilityConfig's conditions are met.
*/
viewabilityConfigCallbackPairs?: ViewabilityConfigCallbackPair[];
/**
* Determines the maximum number of items rendered outside of the visible area, in units of
* visible lengths. So if your list fills the screen, then `windowSize={21}` (the default) will
* render the visible screen area plus up to 10 screens above and 10 below the viewport. Reducing
* this number will reduce memory consumption and may improve performance, but will increase the
* chance that fast scrolling may reveal momentary blank areas of unrendered content.
*/
windowSize: number;
/**
* The legacy implementation is no longer supported.
*/
legacyImplementation?: never;
};
declare type Props =
/*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/
React.ElementConfig<typeof $1> & RequiredProps & OptionalProps & {};
declare type DefaultProps =
/*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/
{
disableVirtualization: boolean;
horizontal: boolean;
initialNumToRender: number;
keyExtractor: (item: Item, index: number) => string;
maxToRenderPerBatch: number;
onEndReachedThreshold: number;
scrollEventThrottle: number;
updateCellsBatchingPeriod: number;
windowSize: number;
};
declare type State = {
first: number;
last: number;
};
declare class VirtualizedList extends React.PureComponent<Props, State> {
static contextType: typeof VirtualizedListContext;
// scrollToEnd may be janky without getItemLayout prop
scrollToEnd(params?: null | undefined | {
animated?: null | undefined | boolean;
}): void;
// scrollToIndex may be janky without getItemLayout prop
scrollToIndex(params: {
animated?: null | undefined | boolean;
index: number;
viewOffset?: number;
viewPosition?: number;
}): void;
// scrollToItem may be janky without getItemLayout prop. Required linear scan through items -
// use scrollToIndex instead if possible.
scrollToItem(params: {
animated?: null | undefined | boolean;
item: Item;
viewPosition?: number;
}): void;
/**
* Scroll to a specific content pixel offset in the list.
*
* Param `offset` expects the offset to scroll to.
* In case of `horizontal` is true, the offset is the x-value,
* in any other case the offset is the y-value.
*
* Param `animated` (`true` by default) defines whether the list
* should do an animation while scrolling.
*/
scrollToOffset(params: {
animated?: null | undefined | boolean;
offset: number;
}): void;
recordInteraction(): void;
flashScrollIndicators(): void;
/**
* Provides a handle to the underlying scroll responder.
* Note that `this._scrollRef` might not be a `ScrollView`, so we
* need to check that it responds to `getScrollResponder` before calling it.
*/
getScrollResponder(): null | undefined | ScrollResponderType;
getScrollableNode(): null | undefined | number;
getScrollRef(): (null | undefined | React.ElementRef<typeof $1>) | (null | undefined | React.ElementRef<typeof $2>);
setNativeProps(props: Object): void;
static defaultProps: DefaultProps;
hasMore(): boolean;
state: State;
constructor(props: Props);
componentDidMount(): void;
componentWillUnmount(): void;
static getDerivedStateFromProps(newProps: Props, prevState: State): State;
render(): React.Node;
componentDidUpdate(prevProps: Props): void;
measureLayoutRelativeToContainingList(): void;
}
export type { Separators };
export type { RenderItemProps };
export type { RenderItemType };
export default VirtualizedList; | the_stack |
import { Subscription } from 'rxjs';
import { NxNumberStepperIntl } from './number-stepper-intl';
import { coerceBooleanProperty, BooleanInput } from '@angular/cdk/coercion';
import { mapClassNames, pad } from '@aposin/ng-aquila/utils';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
Output,
Renderer2,
ViewChild,
OnDestroy
} from '@angular/core';
import { ControlValueAccessor, FormControl, NG_VALIDATORS, NG_VALUE_ACCESSOR, Validator } from '@angular/forms';
import { MappedStyles } from '@aposin/ng-aquila/core';
import { NxAutoResizeDirective } from './auto-resize.directive';
import { Decimal } from 'decimal.js';
const SIZE_MAPPING = {
big: 'nx-stepper--big',
normal: ''
};
const DEFAULT_CLASSES = ['nx-stepper'];
const INPUT_CLASSES = ['nx-stepper__input'];
const ALLOWED_CHARACTERS = new RegExp(/^-?[0-9]\d*(\.\d+)?$/g);
const CUSTOM_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NxNumberStepperComponent),
multi: true
};
const CUSTOM_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => NxNumberStepperComponent),
multi: true
};
let nextUniqueId = 0;
/**
* `Input('nxSize') classNames` defines the size of the number stepper.
* Values: big | normal. Default: normal
*/
@Component({
selector: 'nx-number-stepper',
templateUrl: 'number-stepper.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrls: ['number-stepper.component.scss'],
inputs: ['classNames: nxSize'],
host: {
'[class.is-negative]': 'negative',
'[class.is-disabled]': 'disabled'
},
providers: [CUSTOM_VALUE_ACCESSOR, CUSTOM_VALIDATOR]
})
export class NxNumberStepperComponent extends MappedStyles
implements AfterViewInit, ControlValueAccessor, Validator, OnDestroy {
private _step: number = 1;
private _min: number = 0;
private _max: number = 100;
private _value: number | null = 0;
private _label!: string;
private _incrementAriaLabel = '';
private _decrementAriaLabel = '';
private _inputAriaLabel = '';
private _resize: boolean = false;
private _intlSubscription: Subscription;
private _negative: boolean = false;
private _leadingZero: boolean = true;
private _disabled: boolean = false;
/** @docs-private */
numberInputValue!: string;
/** @docs-private */
public inputClassNames: string = mapClassNames(
'regular',
INPUT_CLASSES
);
/** @docs-private */
public inputId = `nx-number-stepper-${nextUniqueId++}`;
/** @docs-private */
public inputWidth!: number;
/** @docs-private */
public ariaDescribedBy: string | null = null;
/** @docs-private */
@ViewChild('customLabel') ngContentWrapper!: ElementRef;
/** @docs-private */
@ViewChild(NxAutoResizeDirective, { static: true }) autoResize!: NxAutoResizeDirective;
/** @docs-private */
@ViewChild('nativeInput') nativeInput!: ElementRef;
/** An event emitted on value change. */
@Output('nxValueChange') valueChange = new EventEmitter<number>();
/** Whether the input should be resized. Default: false */
@Input('nxResize')
set resize(value: boolean) {
this._resize = coerceBooleanProperty(value);
this._changeDetectorRef.markForCheck();
}
get resize(): boolean {
return this._resize;
}
get label(): string {
return this._label;
}
/** Defines the the label shown above the stepper input. */
@Input('nxLabel')
set label(value: string) {
if (this._label !== value) {
this._label = value;
this._changeDetectorRef.markForCheck();
}
}
/** Sets the aria-label for the increment button. */
@Input()
set incrementAriaLabel(value: string) {
this._incrementAriaLabel = value;
}
get incrementAriaLabel(): string {
return this._incrementAriaLabel;
}
/** Sets the aria-label for the decrement button. */
@Input()
set decrementAriaLabel(value: string) {
this._decrementAriaLabel = value;
}
get decrementAriaLabel(): string {
return this._decrementAriaLabel;
}
/** Sets the aria-label for the input of the number stepper. */
@Input()
set inputAriaLabel(value: string) {
this._inputAriaLabel = value;
}
get inputAriaLabel(): string {
return this._inputAriaLabel;
}
/** Sets the step size. Default: 1 */
@Input('nxStep')
set step(value: number) {
// only internal changes no need to call markForCheck
this._step = Number(value);
}
get step(): number {
return this._step;
}
/** Sets the minimum accepted number. Default: 0 */
@Input('nxMin')
set min(value: number) {
this._min = Number(value);
}
get min(): number {
return this._min;
}
/** Sets the maximum accepted number. Default: 100 */
@Input('nxMax')
set max(value: number) {
this._max = Number(value);
}
get max(): number {
return this._max;
}
get value(): number | null {
return this._value;
}
/** Sets the value of the number-stepper. */
@Input('nxValue')
set value(value: number | null) {
this._value = value as number;
if (this._value) {
this.setInputValue(this._value);
} else {
this.setInputValue(0);
}
this._changeDetectorRef.markForCheck();
}
/** Whether the negative set of styling should be used. */
@Input()
set negative(value: boolean) {
if (this._negative !== value) {
this._negative = coerceBooleanProperty(value);
this._changeDetectorRef.markForCheck();
}
}
get negative(): boolean {
return this._negative;
}
/** Whether the number stepper value should have a leading zero.
*
* Default value is true.
*/
@Input()
set leadingZero(value: boolean) {
if (this._leadingZero !== value) {
this._leadingZero = coerceBooleanProperty(value);
this.setInputValue(this.value);
this._changeDetectorRef.markForCheck();
}
}
get leadingZero(): boolean {
return this._leadingZero;
}
/** Whether the user input in the number stepper should be disabled.
*
* Default value is false.
*/
@Input('nxDisabled')
set disabled(value: boolean) {
this._disabled = coerceBooleanProperty(value);
}
get disabled(): boolean {
return this._disabled;
}
constructor(
private _changeDetectorRef: ChangeDetectorRef,
_renderer: Renderer2,
_elementRef: ElementRef,
public _intl: NxNumberStepperIntl
) {
super(SIZE_MAPPING, DEFAULT_CLASSES, _elementRef, _renderer);
this._intlSubscription = this._intl.changes.subscribe(() => this._changeDetectorRef.markForCheck());
}
ngAfterViewInit() {
if (this.ngContentWrapper) {
this.ariaDescribedBy = this.ngContentWrapper.nativeElement.children.length > 0 ? `label-for-${this.inputId}` : '';
}
this.setInputValue(this._value);
}
ngOnDestroy() {
this._intlSubscription.unsubscribe();
}
/** @docs-private */
setInputValue(value: number | null) {
const parsedValue = value ? value : 0;
if (this.leadingZero) {
this.numberInputValue = pad(parsedValue.toString(), 2);
} else {
this.numberInputValue = parsedValue.toString();
}
if (this.nativeInput) {
// update the native input value with the transformed value.
this.nativeInput.nativeElement.value = this.numberInputValue;
}
// use timeout to get the current value of numberInputValue
setTimeout(() => {
this.triggerResize();
});
}
/* ControlValueAccessor Implementations */
writeValue(value: number | null): void {
this.value = value;
}
private onChangeCallback: Function = () => { };
registerOnChange(onChange: Function): void {
this.onChangeCallback = onChange;
}
/** @docs-private */
onTouchedCallback: Function = () => { };
registerOnTouched(onTouched: Function): void {
this.onTouchedCallback = onTouched;
}
/**
* Disables the stepper. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param isDisabled Sets whether the component is disabled.
*/
setDisabledState(isDisabled: boolean): void {
this._disabled = isDisabled;
this._changeDetectorRef.markForCheck();
}
/** @docs-private */
onInputChange(event: Event ) {
if (!this.validateUserInput((event.target as HTMLInputElement).value)) {
this._value = null;
} else {
this._value = Number((event.target as HTMLInputElement).value);
}
// setInputValue() should be called so that numberInputValue is updated with the user input
if (this._value !== null) {
this.setInputValue(this._value);
}
this.valueChange.emit(this._value!);
this.onChangeCallback(this._value);
}
/** @docs-private */
validateUserInput(input: string) {
return !!input.match(ALLOWED_CHARACTERS);
}
/** @docs-private */
incrementOnClick() {
this._increment();
this.onTouchedCallback();
}
/** @docs-private */
incrementOnKey(event: Event) {
this._increment();
event.preventDefault();
}
/** @docs-private */
_increment() {
let newValue;
if (this.isBetweenLimits(this._value || 0)) {
newValue = this.getNextGreaterValue(this._value || 0);
} else {
newValue = this.enforceLimits(this._value || 0);
}
this.value = newValue;
this.setInputValue(this.value);
this.valueChange.emit(this._value!);
this.onChangeCallback(this._value);
}
/** @docs-private */
triggerResize() {
if (this.resize) {
this.autoResize.updateInputWidth();
this._changeDetectorRef.markForCheck();
}
}
/** @docs-private */
decrementOnClick() {
this._decrement();
this.onTouchedCallback();
}
/** @docs-private */
decrementOnKey(event: Event) {
this._decrement();
event.preventDefault();
}
/** @docs-private */
_decrement() {
let newValue;
if (this.isBetweenLimits(this._value || 0)) {
newValue = this.getNextLowerValue(this._value || 0);
} else {
newValue = this.enforceLimits(this._value || 0);
}
this.value = newValue;
this.setInputValue(this.value);
this.valueChange.emit(this._value!);
this.onChangeCallback(this._value);
}
/** @docs-private */
enforceLimits(value: number): number {
if (value > this._max) {
return this._max;
} else if (value < this._min) {
return this._min;
}
return value;
}
/** @docs-private */
getNextLowerValue(start: number): number {
// if there is an invalid input start is null
if (!start) {
start = 0;
}
let next: number;
if (this.isValidStep(start)) {
next = (new Decimal(start).minus(new Decimal(this._step))).toNumber();
} else {
next = new Decimal(start).toNearest(this._step, Decimal.ROUND_DOWN).toNumber();
}
return this.enforceLimits(next);
}
/** @docs-private */
getNextGreaterValue(start: number) {
let next;
if (!start) {
start = 0;
}
if (this.isValidStep(start)) {
next = (new Decimal(start).plus(new Decimal(this._step))).toNumber();
} else {
next = new Decimal(start).toNearest(this._step, Decimal.ROUND_UP).toNumber();
}
return this.enforceLimits(next);
}
/** @docs-private */
isBetweenLimits(value: number | Decimal) {
return value <= this._max && value >= this._min;
}
/** @docs-private */
isMinimum() {
return this._value === this._min;
}
/** @docs-private */
isMaximum() {
return this._value === this._max;
}
/** @docs-private */
isValidStep(value: number | Decimal | null) {
if (value === null) {
value = new Decimal(0);
}
const min = new Decimal(this._min);
const valueDec = new Decimal(value);
const checkValue = (min.minus(valueDec)).mod(new Decimal(this._step)).toNumber();
if (
this.isBetweenLimits(value) && ((this.isMinimum() || this.isMaximum()) ||
checkValue === 0)
) {
return true;
}
return false;
}
/** @docs-private */
userInputToNumber(value: string): number {
return parseInt(value, 10) || 0;
}
_validateFn() {
// the manual user input must match min + n * step, e.g. minimum 1 step 2: 1, 3, 5, 7 etc.
if (!this.isValidStep(this._value)) {
return { nxNumberStepperStepError: 'Value is not a valid step' };
} else if (this._value === null) {
return { nxNumberStepperFormatError: 'Not a valid number' };
}
return null;
}
/** @docs-private */
validate(c: FormControl) {
return this._validateFn();
}
get _buttonType(): string {
return 'secondary' + (this.negative ? ' negative' : '');
}
static ngAcceptInputType_resize: BooleanInput;
static ngAcceptInputType_negative: BooleanInput;
static ngAcceptInputType_disabled: BooleanInput;
static ngAcceptInputType_leadingZero: BooleanInput;
static ngAcceptInputType_min: number | string | null | undefined;
static ngAcceptInputType_max: number | string | null | undefined;
static ngAcceptInputType_step: number | string | null | undefined;
} | the_stack |
import type { JSX } from 'preact';
import { h, createRef, Component } from 'preact';
import cx from 'classnames';
import { isSpecialClick, isEqual } from '../../lib/utils';
import type { PreparedTemplateProps } from '../../lib/utils/prepareTemplateProps';
import Template from '../Template/Template';
import RefinementListItem from './RefinementListItem';
import type {
SearchBoxComponentCSSClasses,
SearchBoxComponentTemplates,
} from '../SearchBox/SearchBox';
import SearchBox from '../SearchBox/SearchBox';
import type { HierarchicalMenuItem } from '../../connectors/hierarchical-menu/connectHierarchicalMenu';
import type { ComponentCSSClasses, CreateURL, Templates } from '../../types';
import type { RefinementListOwnCSSClasses } from '../../widgets/refinement-list/refinement-list';
import type { RatingMenuComponentCSSClasses } from '../../widgets/rating-menu/rating-menu';
import type { HierarchicalMenuComponentCSSClasses } from '../../widgets/hierarchical-menu/hierarchical-menu';
// CSS types
type RefinementListOptionalClasses =
| 'noResults'
| 'checkbox'
| 'labelText'
| 'showMore'
| 'disabledShowMore'
| 'searchBox'
| 'count';
type RefinementListWidgetCSSClasses =
ComponentCSSClasses<RefinementListOwnCSSClasses>;
type RefinementListRequiredCSSClasses = Omit<
RefinementListWidgetCSSClasses,
RefinementListOptionalClasses
> &
Partial<Pick<RefinementListWidgetCSSClasses, RefinementListOptionalClasses>>;
export type RefinementListComponentCSSClasses =
RefinementListRequiredCSSClasses & {
searchable?: SearchBoxComponentCSSClasses;
} & Partial<Pick<RatingMenuComponentCSSClasses, 'disabledItem'>> &
Partial<
Pick<HierarchicalMenuComponentCSSClasses, 'childList' | 'parentItem'>
>;
type FacetValue = {
value: string;
label: string;
highlighted?: string;
count?: number;
isRefined: boolean;
data?: HierarchicalMenuItem[] | null;
};
export type RefinementListProps<TTemplates extends Templates> = {
createURL: CreateURL<string>;
cssClasses: RefinementListComponentCSSClasses;
depth?: number;
facetValues?: FacetValue[];
attribute?: string;
templateProps: PreparedTemplateProps<TTemplates>;
toggleRefinement: (value: string) => void;
showMore?: boolean;
toggleShowMore?: () => void;
isShowingMore?: boolean;
hasExhaustiveItems?: boolean;
canToggleShowMore?: boolean;
className?: string;
children?: JSX.Element;
// searchable props are optional, but will definitely be present in a searchable context
isFromSearch?: boolean;
searchIsAlwaysActive?: boolean;
searchFacetValues?: (query: string) => void;
searchPlaceholder?: string;
searchBoxTemplateProps?: PreparedTemplateProps<SearchBoxComponentTemplates>;
};
const defaultProps = {
cssClasses: {},
depth: 0,
};
type RefinementListPropsWithDefaultProps<TTemplates extends Templates> =
RefinementListProps<TTemplates> & Readonly<typeof defaultProps>;
type RefinementListItemTemplateData<TTemplates extends Templates> =
FacetValue & {
url: string;
} & Pick<
RefinementListProps<TTemplates>,
'attribute' | 'cssClasses' | 'isFromSearch'
>;
function isHierarchicalMenuItem(
facetValue: FacetValue
): facetValue is HierarchicalMenuItem {
return (facetValue as HierarchicalMenuItem).data !== undefined;
}
class RefinementList<TTemplates extends Templates> extends Component<
RefinementListPropsWithDefaultProps<TTemplates>
> {
public static defaultProps = defaultProps;
private searchBox = createRef<SearchBox>();
public constructor(props: RefinementListPropsWithDefaultProps<TTemplates>) {
super(props);
this.handleItemClick = this.handleItemClick.bind(this);
}
public shouldComponentUpdate(
nextProps: RefinementListPropsWithDefaultProps<TTemplates>
) {
const areFacetValuesDifferent = !isEqual(
this.props.facetValues,
nextProps.facetValues
);
return areFacetValuesDifferent;
}
private refine(facetValueToRefine: string) {
this.props.toggleRefinement(facetValueToRefine);
}
private _generateFacetItem(facetValue: FacetValue) {
let subItems;
if (
isHierarchicalMenuItem(facetValue) &&
Array.isArray(facetValue.data) &&
facetValue.data.length > 0
) {
const { root, ...cssClasses } = this.props.cssClasses;
subItems = (
<RefinementList
{...this.props}
// We want to keep `root` required for external usage but not for the
// sub items.
cssClasses={cssClasses as RefinementListComponentCSSClasses}
depth={this.props.depth + 1}
facetValues={facetValue.data}
showMore={false}
className={this.props.cssClasses.childList}
/>
);
}
const url = this.props.createURL(facetValue.value);
const templateData: RefinementListItemTemplateData<TTemplates> = {
...facetValue,
url,
attribute: this.props.attribute,
cssClasses: this.props.cssClasses,
isFromSearch: this.props.isFromSearch,
};
let { value: key } = facetValue;
if (facetValue.isRefined !== undefined) {
key += `/${facetValue.isRefined}`;
}
if (facetValue.count !== undefined) {
key += `/${facetValue.count}`;
}
const refinementListItemClassName = cx(this.props.cssClasses.item, {
[this.props.cssClasses.selectedItem]: facetValue.isRefined,
// cx allows `undefined` as a key but typescript doesn't
[this.props.cssClasses.disabledItem!]: !facetValue.count,
[this.props.cssClasses.parentItem!]:
isHierarchicalMenuItem(facetValue) &&
Array.isArray(facetValue.data) &&
facetValue.data.length > 0,
});
return (
<RefinementListItem
templateKey="item"
key={key}
facetValueToRefine={facetValue.value}
handleClick={this.handleItemClick}
isRefined={facetValue.isRefined}
className={refinementListItemClassName}
subItems={subItems}
templateData={templateData}
templateProps={this.props.templateProps}
/>
);
}
// Click events on DOM tree like LABEL > INPUT will result in two click events
// instead of one.
// No matter the framework, see https://www.google.com/search?q=click+label+twice
//
// Thus making it hard to distinguish activation from deactivation because both click events
// are very close. Debounce is a solution but hacky.
//
// So the code here checks if the click was done on or in a LABEL. If this LABEL
// has a checkbox inside, we ignore the first click event because we will get another one.
//
// We also check if the click was done inside a link and then e.preventDefault() because we already
// handle the url
//
// Finally, we always stop propagation of the event to avoid multiple levels RefinementLists to fail: click
// on child would click on parent also
private handleItemClick({
facetValueToRefine,
isRefined,
originalEvent,
}: {
facetValueToRefine: string;
isRefined: boolean;
originalEvent: MouseEvent;
}) {
if (isSpecialClick(originalEvent)) {
// do not alter the default browser behavior
// if one special key is down
return;
}
if (
!(originalEvent.target instanceof HTMLElement) ||
!(originalEvent.target.parentNode instanceof HTMLElement)
) {
return;
}
if (
isRefined &&
originalEvent.target.parentNode.querySelector(
'input[type="radio"]:checked'
)
) {
// Prevent refinement for being reset if the user clicks on an already checked radio button
return;
}
if (originalEvent.target.tagName === 'INPUT') {
this.refine(facetValueToRefine);
return;
}
let parent = originalEvent.target;
while (parent !== originalEvent.currentTarget) {
if (
parent.tagName === 'LABEL' &&
(parent.querySelector('input[type="checkbox"]') ||
parent.querySelector('input[type="radio"]'))
) {
return;
}
if (parent.tagName === 'A' && (parent as HTMLAnchorElement).href) {
originalEvent.preventDefault();
}
parent = parent.parentNode as HTMLElement;
}
originalEvent.stopPropagation();
this.refine(facetValueToRefine);
}
public componentWillReceiveProps(
nextProps: RefinementListPropsWithDefaultProps<TTemplates>
) {
if (this.searchBox.current && !nextProps.isFromSearch) {
this.searchBox.current.resetInput();
}
}
private refineFirstValue() {
const firstValue = this.props.facetValues && this.props.facetValues[0];
if (firstValue) {
const actualValue = firstValue.value;
this.props.toggleRefinement(actualValue);
}
}
public render() {
const showMoreButtonClassName = cx(this.props.cssClasses.showMore, {
[this.props.cssClasses.disabledShowMore!]: !(
this.props.showMore === true && this.props.canToggleShowMore
),
});
const showMoreButton = this.props.showMore === true && (
<Template
{...this.props.templateProps}
templateKey="showMoreText"
rootTagName="button"
rootProps={{
className: showMoreButtonClassName,
disabled: !this.props.canToggleShowMore,
onClick: this.props.toggleShowMore,
}}
data={{
isShowingMore: this.props.isShowingMore,
}}
/>
);
const shouldDisableSearchBox =
this.props.searchIsAlwaysActive !== true &&
!(this.props.isFromSearch || !this.props.hasExhaustiveItems);
const searchBox = this.props.searchFacetValues && (
<div className={this.props.cssClasses.searchBox}>
<SearchBox
ref={this.searchBox}
placeholder={this.props.searchPlaceholder}
disabled={shouldDisableSearchBox}
cssClasses={this.props.cssClasses.searchable!}
templates={this.props.searchBoxTemplateProps!.templates}
onChange={(event: Event) =>
this.props.searchFacetValues!(
(event.target as HTMLInputElement).value
)
}
onReset={() => this.props.searchFacetValues!('')}
onSubmit={() => this.refineFirstValue()}
// This sets the search box to a controlled state because
// we don't rely on the `refine` prop but on `onChange`.
searchAsYouType={false}
/>
</div>
);
const facetValues = this.props.facetValues &&
this.props.facetValues.length > 0 && (
<ul className={this.props.cssClasses.list}>
{this.props.facetValues.map(this._generateFacetItem, this)}
</ul>
);
const noResults = this.props.searchFacetValues &&
this.props.isFromSearch &&
(!this.props.facetValues || this.props.facetValues.length === 0) && (
<Template
{...this.props.templateProps}
templateKey="searchableNoResults"
rootProps={{ className: this.props.cssClasses.noResults }}
/>
);
const rootClassName = cx(
this.props.cssClasses.root,
{
[this.props.cssClasses.noRefinementRoot]:
!this.props.facetValues || this.props.facetValues.length === 0,
},
this.props.className
);
return (
<div className={rootClassName}>
{this.props.children}
{searchBox}
{facetValues}
{noResults}
{showMoreButton}
</div>
);
}
}
export default RefinementList; | the_stack |
import { DiscoverySchemaChanges, IDiscoveryVersionable } from "../../MailboxSearch/Versioning";
import { EwsServiceJsonReader } from "../EwsServiceJsonReader";
import { EwsServiceXmlWriter } from "../EwsServiceXmlWriter";
import { ExchangeService } from "../ExchangeService";
import { ExchangeVersion } from "../../Enumerations/ExchangeVersion";
import { MailboxQuery } from "../../MailboxSearch/MailboxQuery";
import { MailboxSearchLocation } from "../../Enumerations/MailboxSearchLocation";
import { MailboxSearchScope } from "../../MailboxSearch/MailboxSearchScope";
import { MailboxSearchScopeType } from "../../Enumerations/MailboxSearchScopeType";
import { PreviewItemBaseShape } from "../../Enumerations/PreviewItemBaseShape";
import { PreviewItemResponseShape } from "../../MailboxSearch/PreviewItemResponseShape";
import { PropertyDefinitionBase } from "../../PropertyDefinitions/PropertyDefinitionBase";
import { SearchPageDirection } from "../../Enumerations/SearchPageDirection";
import { SearchResultType } from "../../Enumerations/SearchResultType";
import { ServiceErrorHandling } from "../../Enumerations/ServiceErrorHandling";
import { ServiceObjectSchema } from "../ServiceObjects/Schemas/ServiceObjectSchema";
import { ServiceResponseCollection } from "../Responses/ServiceResponseCollection";
import { ServiceValidationException } from "../../Exceptions/ServiceValidationException";
import { ServiceVersionException } from "../../Exceptions/ServiceVersionException";
import { SortDirection } from "../../Enumerations/SortDirection";
import { StringHelper } from "../../ExtensionMethods";
import { Strings } from "../../Strings";
import { XmlElementNames } from "../XmlElementNames";
import { XmlNamespace } from "../../Enumerations/XmlNamespace";
import { SearchMailboxesResponse } from "../Responses/SearchMailboxesResponse";
import { MultiResponseServiceRequest } from "./MultiResponseServiceRequest";
/**
* @internal Represents a SearchMailboxesRequest request.
*
* @sealed
*/
export class SearchMailboxesRequest extends MultiResponseServiceRequest<SearchMailboxesResponse> implements IDiscoveryVersionable {
private searchQueries: MailboxQuery[] = [];
private searchResultType: SearchResultType = SearchResultType.PreviewOnly;
private sortOrder: SortDirection = SortDirection.Ascending;
private sortByProperty: string = null;
private performDeduplication: boolean = false;
private pageSize: number = 0;
private pageItemReference: string = null;
private pageDirection: SearchPageDirection = SearchPageDirection.Next;
private previewItemResponseShape: PreviewItemResponseShape = null;
/**
* Collection of query + mailboxes
*/
get SearchQueries(): MailboxQuery[] {
return this.searchQueries;
}
set SearchQueries(value: MailboxQuery[]) {
this.searchQueries = value;
}
/**
* Search result type
*/
get ResultType(): SearchResultType {
return this.searchResultType;
}
set ResultType(value: SearchResultType) {
this.searchResultType = value;
}
/**
* Preview item response shape
*/
get PreviewItemResponseShape(): PreviewItemResponseShape {
return this.previewItemResponseShape;
}
set PreviewItemResponseShape(value: PreviewItemResponseShape) {
this.previewItemResponseShape = value;
}
/**
* Sort order
*/
get SortOrder(): SortDirection {
return this.sortOrder;
}
set SortOrder(value: SortDirection) {
this.sortOrder = value;
}
/**
* Sort by property name
*/
get SortByProperty(): string {
return this.sortByProperty;
}
set SortByProperty(value: string) {
this.sortByProperty = value;
}
/**
* Query language
*/
Language: string = null;
/**
* Perform deduplication or not
*/
get PerformDeduplication(): boolean {
return this.performDeduplication;
}
set PerformDeduplication(value: boolean) {
this.performDeduplication = value;
}
/**
* Page size
*/
get PageSize(): number {
return this.pageSize;
}
set PageSize(value: number) {
this.pageSize = value;
}
/**
* Page item reference
*/
get PageItemReference(): string {
return this.pageItemReference;
}
set PageItemReference(value: string) {
this.pageItemReference = value;
}
/**
* Page direction
*/
get PageDirection(): SearchPageDirection {
return this.pageDirection;
}
set PageDirection(value: SearchPageDirection) {
this.pageDirection = value;
}
/**
* Gets or sets the server version.
* @interface IDiscoveryVersionable
*/
ServerVersion: number = 0;
/**
* @internal Initializes a new instance of the **SearchMailboxesRequest** class.
*
* @param {ExchangeService} service The service.
* @param {ServiceErrorHandling} errorHandlingMode Indicates how errors should be handled.
*/
constructor(service: ExchangeService, errorHandlingMode: ServiceErrorHandling) {
super(service, errorHandlingMode);
}
/**
* @internal Creates the service response.
*
* @param {ExchangeService} service The service.
* @param {number} responseIndex Index of the response.
* @return {SearchMailboxesResponse} Service response.
*/
CreateServiceResponse(service: ExchangeService, responseIndex: number): SearchMailboxesResponse {
return new SearchMailboxesResponse();
}
/**
* @internal Gets the expected response message count.
*
* @return {number} Number of expected response messages.
*/
GetExpectedResponseMessageCount(): number {
return 1;
}
/**
* @internal Gets the request version.
*
* @return {ExchangeVersion} Earliest Exchange version in which this request is supported.
*/
GetMinimumRequiredServerVersion(): ExchangeVersion {
return ExchangeVersion.Exchange2013;
}
/**
* @internal Gets the name of the response message XML element.
*
* @return {string} Xml element name.
*/
GetResponseMessageXmlElementName(): string {
return XmlElementNames.SearchMailboxesResponseMessage;
}
/**
* @internal Gets the name of the response XML element.
*
* @return {string} Xml element name.
*/
GetResponseXmlElementName(): string {
return XmlElementNames.SearchMailboxesResponse;
}
/**
* @internal Gets the name of the XML element.
*
* @return {string} Xml element name.
*/
GetXmlElementName(): string {
return XmlElementNames.SearchMailboxes;
}
/**
* @internal Parses the response.
* See O15:324151 (OfficeDev bug/issue not visible to external world) on why we need to override ParseResponse here instead of calling the one in MultiResponseServiceRequest.cs
*
* @param {any} jsonBody The js object response body.
* @return {any} Response object.
*/
ParseResponse(jsonBody: any): any {
let serviceResponses: ServiceResponseCollection<SearchMailboxesResponse> = new ServiceResponseCollection<SearchMailboxesResponse>();
let jsResponseMessages = EwsServiceJsonReader.ReadAsArray(jsonBody[XmlElementNames.ResponseMessages], this.GetResponseMessageXmlElementName());
for (let jsResponseObject of jsResponseMessages) {
let response: SearchMailboxesResponse = new SearchMailboxesResponse();
response.LoadFromXmlJsObject(jsResponseObject, this.Service);
serviceResponses.Add(response);
}
return serviceResponses;
}
/**
* @internal Validate the request.
*/
Validate(): void {
super.Validate();
if (this.SearchQueries == null || this.SearchQueries.length == 0) {
throw new ServiceValidationException(Strings.MailboxQueriesParameterIsNotSpecified);
}
for (let searchQuery of this.SearchQueries) {
if (searchQuery.MailboxSearchScopes == null || searchQuery.MailboxSearchScopes.length == 0) {
throw new ServiceValidationException(Strings.MailboxQueriesParameterIsNotSpecified);
}
for (let searchScope of searchQuery.MailboxSearchScopes) {
if (searchScope.ExtendedAttributes != null && searchScope.ExtendedAttributes.length > 0 && !DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this)) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.ClassIncompatibleWithRequestVersion,
"ExtendedAttribute", //typeof (ExtendedAttribute).Name,
DiscoverySchemaChanges.SearchMailboxesExtendedData.MinimumServerVersion));
}
if (searchScope.SearchScopeType != MailboxSearchScopeType.LegacyExchangeDN && (!DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this) || !DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.IsCompatible(this))) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.EnumValueIncompatibleWithRequestVersion,
MailboxSearchScopeType[searchScope.SearchScopeType],
"MailboxSearchScopeType", //typeof (MailboxSearchScopeType).Name,
DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.MinimumServerVersion));
}
}
}
if (!StringHelper.IsNullOrEmpty(this.SortByProperty)) {
let prop: PropertyDefinitionBase = null;
try {
prop = ServiceObjectSchema.FindPropertyDefinition(this.SortByProperty);
}
catch (ex) { //KeyNotFoundException
}
if (prop == null) {
throw new ServiceValidationException(StringHelper.Format(Strings.InvalidSortByPropertyForMailboxSearch, this.SortByProperty));
}
}
}
/**
* @internal Writes XML elements.
*
* @param {EwsServiceXmlWriter} writer The writer.
*/
WriteElementsToXml(writer: EwsServiceXmlWriter): void {
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.SearchQueries);
for (let mailboxQuery of this.SearchQueries) {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxQuery);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Query, mailboxQuery.Query);
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxSearchScopes);
for (let mailboxSearchScope of mailboxQuery.MailboxSearchScopes) {
// The checks here silently downgrade the schema based on compatability checks, to recieve errors use the validate method
if (mailboxSearchScope.SearchScopeType == MailboxSearchScopeType.LegacyExchangeDN || DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.IsCompatible(this)) {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxSearchScope);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Mailbox, mailboxSearchScope.Mailbox);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.SearchScope, MailboxSearchLocation[mailboxSearchScope.SearchScope]);
if (DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this)) {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttributes);
if (mailboxSearchScope.SearchScopeType != MailboxSearchScopeType.LegacyExchangeDN) {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttribute);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeName, XmlElementNames.SearchScopeType);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeValue, MailboxSearchScopeType[mailboxSearchScope.SearchScopeType]);
writer.WriteEndElement();
}
if (mailboxSearchScope.ExtendedAttributes != null && mailboxSearchScope.ExtendedAttributes.length > 0) {
for (let attribute of mailboxSearchScope.ExtendedAttributes) {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttribute);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeName, attribute.Name);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeValue, attribute.Value);
writer.WriteEndElement();
}
}
writer.WriteEndElement(); // ExtendedData
}
writer.WriteEndElement(); // MailboxSearchScope
}
}
writer.WriteEndElement(); // MailboxSearchScopes
writer.WriteEndElement(); // MailboxQuery
}
writer.WriteEndElement(); // SearchQueries
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.ResultType, SearchResultType[this.ResultType]);
if (this.PreviewItemResponseShape != null) {
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.PreviewItemResponseShape);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.BaseShape, PreviewItemBaseShape[this.PreviewItemResponseShape.BaseShape]);
if (this.PreviewItemResponseShape.AdditionalProperties != null && this.PreviewItemResponseShape.AdditionalProperties.length > 0) {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.AdditionalProperties);
for (let additionalProperty of this.PreviewItemResponseShape.AdditionalProperties) {
additionalProperty.WriteToXml(writer);
}
writer.WriteEndElement(); // AdditionalProperties
}
writer.WriteEndElement(); // PreviewItemResponseShape
}
if (!StringHelper.IsNullOrEmpty(this.SortByProperty)) {
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.SortBy);
writer.WriteAttributeValue(XmlElementNames.Order, SortDirection[this.SortOrder]);
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.FieldURI);
writer.WriteAttributeValue(XmlElementNames.FieldURI, this.sortByProperty);
writer.WriteEndElement(); // FieldURI
writer.WriteEndElement(); // SortBy
}
// Language
if (!StringHelper.IsNullOrEmpty(this.Language)) {
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.Language, this.Language);
}
// Dedupe
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.Deduplication, this.performDeduplication);
if (this.PageSize > 0) {
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageSize, this.PageSize);
}
if (!StringHelper.IsNullOrEmpty(this.PageItemReference)) {
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageItemReference, this.PageItemReference);
}
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageDirection, SearchPageDirection[this.PageDirection]);
}
} | the_stack |
import compose from 'lodash/flowRight';
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import { shallowEqual, shallowEqualExcept, debugShouldComponentUpdate } from '../utils/componentUtils';
import { isClient } from '../executionEnvironment';
import * as _ from 'underscore';
type ComparisonFn = (prev: any, next: any)=>boolean
type ComparePropsDict = { [propName: string]: "shallow"|"ignore"|"deep"|ComparisonFn }
type AreEqualOption = ComparisonFn|ComparePropsDict|"auto"
// Options passed to registerComponent
interface ComponentOptions {
// JSS styles for this component. These will generate class names, which will
// be passed as an extra prop named "classes".
styles?: any
// Whether to ignore the presence of colors that don't come from the theme in
// the component's stylesheet. Use for things that don't change color with
// dark mode.
allowNonThemeColors?: boolean,
// Default is 0. If classes with overlapping attributes from two different
// components' styles wind up applied to the same node, the one with higher
// priority wins.
stylePriority?: number,
// Array of higher-order components that this component should be wrapped
// with.
hocs?: Array<any>
// Determines what changes to props are considered relevant, for rerendering.
// Takes either "auto" (meaning a shallow comparison of all props), a function
// that takes before-and-after props, or an object where keys are names of
// props, values are how those props are handled, and props that are not
// mentioned are equality-compared. The options for handling a prop are a
// function or one of:
// * ignore: Don't rerender this component on changes to this prop
// * shallow: Shallow-compare this prop (this is one level deeper than the
// shallow comparison of all props)
// * deep: Perform a deep comparison of before and after values of this
// prop. (Don't use on prop types that are or contain React components)
areEqual?: AreEqualOption
// If set, output console log messages reporting when this component is
// rerendered, and which props changed to trigger it.
debugRerenders?: boolean,
}
interface ComponentsTableEntry {
name: string
rawComponent: any
hocs: Array<any>
options?: ComponentOptions,
}
const componentsProxyHandler = {
get: function(obj: {}, prop: string) {
if (prop == "__isProxy") {
return true;
} else if (prop in PreparedComponents) {
return PreparedComponents[prop];
} else {
return prepareComponent(prop);
}
}
}
/**
* Acts like a mapping from component-name to component, based on
* registerComponents calls. Lazily loads those components when you dereference,
* using a proxy.
*/
export const Components: ComponentTypes = new Proxy({} as any, componentsProxyHandler);
const PreparedComponents: Record<string,any> = {};
// storage for infos about components
export const ComponentsTable: Record<string, ComponentsTableEntry> = {};
const DeferredComponentsTable: Record<string,()=>void> = {};
type EmailRenderContextType = {
isEmailRender: boolean
}
export const EmailRenderContext = React.createContext<EmailRenderContextType|null>(null);
const addClassnames = (componentName: string, styles: any) => {
const classesProxy = new Proxy({}, {
get: function(obj: any, prop: any) {
// Check that the prop is really a string. This isn't an error that comes
// up normally, but apparently React devtools will try to query for non-
// string properties sometimes when using the component debugger.
if (typeof prop === "string")
return `${componentName}-${prop}`;
else
return `${componentName}-invalid`;
}
});
return (WrappedComponent: any) => (props: any) => {
const emailRenderContext = React.useContext(EmailRenderContext);
if (emailRenderContext?.isEmailRender) {
const withStylesHoc = withStyles(styles, {name: componentName})
const StylesWrappedComponent = withStylesHoc(WrappedComponent)
return <StylesWrappedComponent {...props}/>
}
return <WrappedComponent {...props} classes={classesProxy}/>
}
}
// Register a component. Takes a name, a raw component, and ComponentOptions
// (see above). Components should be in their own file, imported with
// `importComponent`, and registered in that file; components that are
// registered this way can be accessed via the Components object and are lazy-
// loaded.
//
// Returns a dummy value--null, but coerced to a type that you can add to the
// ComponentTypes interface to type-check usages of the component in other
// files.
export function registerComponent<PropType>(name: string, rawComponent: React.ComponentType<PropType>,
options?: ComponentOptions): React.ComponentType<Omit<PropType,"classes">>
{
const { styles=null, hocs=[] } = options || {};
if (styles) {
if (isClient && window?.missingMainStylesheet) {
hocs.push(withStyles(styles, {name: name}));
} else {
hocs.push(addClassnames(name, styles));
}
}
rawComponent.displayName = name;
if (name in ComponentsTable && ComponentsTable[name].rawComponent !== rawComponent) {
throw new Error(`Two components with the same name: ${name}`);
}
// store the component in the table
ComponentsTable[name] = {
name,
rawComponent,
hocs,
options,
};
// The Omit is a hacky way of ensuring that hocs props are omitted from the
// ones required to be passed in by parent components. It doesn't work for
// hocs that share prop names that overlap with actually passed-in props, like
// `location`.
return (null as any as React.ComponentType<Omit<PropType,"classes">>);
}
// If true, `importComponent` imports immediately (rather than deferring until
// first use) and checks that the file registered the components named, with a
// lot of log-spam.
const debugComponentImports = false;
export function importComponent(componentName: keyof ComponentTypes|Array<keyof ComponentTypes>, importFn: ()=>void) {
if (Array.isArray(componentName)) {
for (let name of componentName) {
DeferredComponentsTable[name] = importFn;
}
} else {
DeferredComponentsTable[componentName] = importFn;
}
}
export function importAllComponents() {
for (let componentName of Object.keys(DeferredComponentsTable)) {
prepareComponent(componentName);
}
}
function prepareComponent(componentName: string): any
{
if (componentName in PreparedComponents) {
return PreparedComponents[componentName];
} else if (componentName in ComponentsTable) {
PreparedComponents[componentName] = getComponent(componentName);
return PreparedComponents[componentName];
} else if (componentName in DeferredComponentsTable) {
DeferredComponentsTable[componentName]();
if (!(componentName in ComponentsTable)) {
throw new Error(`Import did not provide component ${componentName}`);
}
return prepareComponent(componentName);
} else {
// eslint-disable-next-line no-console
console.error(`Missing component: ${componentName}`);
return null;
}
}
// Get a component registered with registerComponent, applying HoCs and other
// wrappings.
const getComponent = (name: string): any => {
const componentMeta = ComponentsTable[name];
if (!componentMeta) {
throw new Error(`Component ${name} not registered.`);
}
const componentWithMemo = componentMeta.options?.areEqual
? memoizeComponent(componentMeta.options.areEqual, componentMeta.rawComponent, name, !!componentMeta.options.debugRerenders)
: componentMeta.rawComponent;
if (componentMeta.hocs && componentMeta.hocs.length) {
const hocs = componentMeta.hocs.map(hoc => {
if (!Array.isArray(hoc)) {
if (typeof hoc !== 'function') {
throw new Error(`In registered component ${name}, an hoc is of type ${typeof hoc}`);
}
return hoc;
}
const [actualHoc, ...args] = hoc;
if (typeof actualHoc !== 'function') {
throw new Error(`In registered component ${name}, an hoc is of type ${typeof actualHoc}`);
}
return actualHoc(...args);
});
// @ts-ignore
return compose(...hocs)(componentWithMemo);
} else {
return componentWithMemo;
}
};
const memoizeComponent = (areEqual: AreEqualOption, component: any, name: string, debugRerenders: boolean): any => {
if (areEqual === "auto") {
if (debugRerenders) {
return React.memo(component, (oldProps, newProps) => {
// eslint-disable-next-line no-console
return debugShouldComponentUpdate(name, console.log, oldProps, {}, newProps, {});
});
} else {
return React.memo(component);
}
} else if (typeof areEqual==='function') {
return React.memo(component, areEqual);
} else {
return React.memo(component, (oldProps, newProps) => {
const speciallyHandledKeys = Object.keys(areEqual);
if (!shallowEqualExcept(oldProps, newProps, speciallyHandledKeys)) {
if (debugRerenders) {
// eslint-disable-next-line no-console
debugShouldComponentUpdate(name, console.log, oldProps, {}, newProps, {});
}
return false;
}
for (let key of speciallyHandledKeys) {
if (typeof areEqual[key]==="function") {
if (!(areEqual[key] as ComparisonFn)(oldProps[key], newProps[key])) {
if (debugRerenders) {
// eslint-disable-next-line no-console
console.log(`Updating ${name} because props.${key} changed`);
}
return false;
}
} else switch(areEqual[key]) {
case "ignore":
break;
case "default":
if (oldProps[key] !== newProps[key]) {
if (debugRerenders) {
// eslint-disable-next-line no-console
console.log(`Updating ${name} because props.${key} changed`);
}
return false;
}
break;
case "shallow":
if (!shallowEqual(oldProps[key], newProps[key])) {
if (debugRerenders) {
// eslint-disable-next-line no-console
console.log(`Updating ${name} because props.${key} changed`);
}
return false;
}
break;
case "deep":
if (!_.isEqual(oldProps[key], newProps[key])) {
if (debugRerenders) {
// eslint-disable-next-line no-console
console.log(`Updating ${name} because props.${key} changed`);
}
return false;
}
break;
}
}
return true;
});
}
}
/**
* Called once on app startup
*
* See debugComponentImports for intended use
*/
export const populateComponentsAppDebug = (): void => {
if (debugComponentImports) {
importAllComponents();
}
};
// Returns an instance of the given component name of function
//
// @param {string|function} component A component or registered component name
// @param {Object} [props] Optional properties to pass to the component
export const instantiateComponent = (component: any, props: any) => {
if (!component) {
return null;
} else if (typeof component === 'string') {
const Component: any = Components[component];
return <Component {...props} />;
} else if (
typeof component === 'function' &&
component.prototype &&
component.prototype.isReactComponent
) {
const Component = component;
return <Component {...props} />;
} else if (typeof component === 'function') {
return component(props);
} else {
return component;
}
};
// Given an optional set of override-components, return a Components object
// which wraps the main Components table, preserving Components'
// proxy/deferred-execution tricks.
export const mergeWithComponents = (myComponents: any) => {
if (!myComponents) return Components;
if (myComponents.__isProxy)
return myComponents;
const mergedComponentsProxyHandler = {
get: function(obj: any, prop: string) {
if (prop === "__isProxy") {
return true;
} else if (prop in myComponents) {
return myComponents[prop];
} else if (prop in PreparedComponents) {
return PreparedComponents[prop];
} else {
return prepareComponent(prop);
}
}
}
return new Proxy({}, mergedComponentsProxyHandler );
} | the_stack |
import "./helpers/dotenv_helper";
import { getTestId, getState, dispatch } from "./helpers/test_helper";
import { Api, Client, Model } from "@core/types";
import { registerWithEmail } from "./helpers/auth_helper";
import { getEnvironments } from "./helpers/envs_helper";
import { createApp } from "./helpers/apps_helper";
import { envkeyFetch, envkeyFetchExpectError } from "./helpers/fetch_helper";
import * as g from "@core/lib/graph";
import * as R from "ramda";
import { log } from "@core/lib/utils/logger";
import { getOrgGraph } from "@api_shared/graph";
describe("firewall", () => {
let email: string, orgId: string, ownerDeviceId: string, ownerId: string;
beforeEach(async () => {
email = `success+${getTestId()}@simulator.amazonses.com`;
({
orgId,
deviceId: ownerDeviceId,
userId: ownerId,
} = await registerWithEmail(email));
});
describe("local ips", () => {
test("can't make a request if current ip doesn't match localIpsAllowed", async () => {
const res = await dispatch(
{
type: Api.ActionType.SET_ORG_ALLOWED_IPS,
payload: {
localIpsAllowed: ["155.130.90.61", "192.168.0.1/24"],
environmentRoleIpsAllowed: {},
},
},
ownerId,
undefined,
undefined,
"155.130.90.60"
);
expect(res.success).toBe(false);
expect((res.resultAction as any).payload.error.code).toBe(422);
expect((res.resultAction as any).payload.error.message).toBe(
"Current user IP not allowed by localIpsAllowed"
);
});
test("can make a request if local ip matches an ip", async () => {
let res = await dispatch(
{
type: Api.ActionType.SET_ORG_ALLOWED_IPS,
payload: {
localIpsAllowed: ["155.130.90.61", "192.168.200.6/30"],
environmentRoleIpsAllowed: {},
},
},
ownerId,
undefined,
undefined,
"155.130.90.61"
);
expect(res.success).toBe(true);
res = await dispatch(
{
type: Client.ActionType.CREATE_APP,
payload: {
name: "Test App",
settings: {
autoCaps: true,
},
},
},
ownerId,
undefined,
undefined,
"155.130.90.61"
);
expect(res.success).toBe(true);
res = await dispatch(
{
type: Client.ActionType.CREATE_APP,
payload: {
name: "Test App",
settings: {
autoCaps: true,
},
},
},
ownerId,
undefined,
undefined,
"155.130.90.65"
);
expect(res.success).toBe(false);
expect((res.resultAction as any).payload.error.code).toBe(401);
expect((res.resultAction as any).payload.error.message).toBe(
"ip not permitted"
);
});
test("can update org ips and make a request if local ip matches a CIDR range", async () => {
let res = await dispatch(
{
type: Api.ActionType.SET_ORG_ALLOWED_IPS,
payload: {
localIpsAllowed: ["155.130.90.61", "192.168.200.4/30"],
environmentRoleIpsAllowed: {},
},
},
ownerId,
undefined,
undefined,
"192.168.200.5"
);
expect(res.success).toBe(true);
res = await dispatch(
{
type: Client.ActionType.CREATE_APP,
payload: {
name: "Test App",
settings: {
autoCaps: true,
},
},
},
ownerId,
undefined,
undefined,
"192.168.200.5"
);
expect(res.success).toBe(true);
res = await dispatch(
{
type: Client.ActionType.CREATE_APP,
payload: {
name: "Test App",
settings: {
autoCaps: true,
},
},
},
ownerId,
undefined,
undefined,
"192.168.202.1"
);
expect(res.success).toBe(false);
expect((res.resultAction as any).payload.error.code).toBe(401);
expect((res.resultAction as any).payload.error.message).toBe(
"ip not permitted"
);
});
});
describe("environment ips", () => {
test("when setting org environment ips allowed, it correctly protects ENVKEYs", async () => {
// create an app
const app = await createApp(ownerId);
const [development, staging, production] = getEnvironments(
ownerId,
app.id
);
// set some org allowed ips for different environments
let res = await dispatch(
{
type: Api.ActionType.SET_ORG_ALLOWED_IPS,
payload: {
environmentRoleIpsAllowed: {
[development.environmentRoleId]: ["::ffff:127.0.0.1"],
[staging.environmentRoleId]: ["192.168.202.9"],
[production.environmentRoleId]: ["192.168.200.4/30"],
},
},
},
ownerId
);
expect(res.success).toBe(true);
// set inherits, extends, and overrides for app environments
res = await dispatch(
{
type: Api.ActionType.SET_APP_ALLOWED_IPS,
payload: {
id: app.id,
environmentRoleIpsMergeStrategies: {
[development.environmentRoleId]: undefined,
[staging.environmentRoleId]: "extend",
[production.environmentRoleId]: "override",
},
environmentRoleIpsAllowed: {
[development.environmentRoleId]: undefined,
[staging.environmentRoleId]: ["192.168.202.1"],
[production.environmentRoleId]: ["192.166.209.4/30"],
},
},
},
ownerId
);
expect(res.success).toBe(true);
// generate some servers
await dispatch(
{
type: Client.ActionType.CREATE_SERVER,
payload: {
appId: app.id,
name: "Development Server",
environmentId: development.id,
},
},
ownerId
);
await dispatch(
{
type: Client.ActionType.CREATE_SERVER,
payload: {
appId: app.id,
name: "Staging Server",
environmentId: staging.id,
},
},
ownerId
);
await dispatch(
{
type: Client.ActionType.CREATE_SERVER,
payload: {
appId: app.id,
name: "Production Server",
environmentId: production.id,
},
},
ownerId
);
// ensure they all have the right allowedIps set
const orgGraph = await getOrgGraph(orgId, { transactionConn: undefined });
const generatedEnvkeys = g.graphTypes(orgGraph).generatedEnvkeys;
expect(generatedEnvkeys.length).toBe(3);
const generatedEnvkeysByEnvironmentId = R.indexBy(
R.prop("environmentId"),
generatedEnvkeys
) as Record<string, Api.Db.GeneratedEnvkey>;
expect(
generatedEnvkeysByEnvironmentId[development.id].allowedIps
).toEqual(expect.arrayContaining(["::ffff:127.0.0.1"]));
expect(generatedEnvkeysByEnvironmentId[staging.id].allowedIps).toEqual(
expect.arrayContaining(["192.168.202.9", "192.168.202.1"])
);
expect(generatedEnvkeysByEnvironmentId[production.id].allowedIps).toEqual(
expect.arrayContaining(["192.166.209.4/30"])
);
// ensure we can fetch with an allowed ip
let state = getState(ownerId);
const { servers } = g.graphTypes(state.graph),
devServer = servers.filter(
R.propEq("environmentId", development.id)
)[0],
stagingServer = servers.filter(
R.propEq("environmentId", staging.id)
)[0],
prodServer = servers.filter(
R.propEq("environmentId", production.id)
)[0];
const { envkeyIdPart: devEnvkeyIdPart, encryptionKey: devEncryptionKey } =
state.generatedEnvkeys[devServer.id],
{
envkeyIdPart: stagingEnvkeyIdPart,
encryptionKey: stagingEncryptionKey,
} = state.generatedEnvkeys[stagingServer.id],
{ envkeyIdPart: prodEnvkeyIdPart, encryptionKey: prodEncryptionKey } =
state.generatedEnvkeys[prodServer.id];
// ensure we can fetch with an allowed ip and can't fetch with a forbidden ip
// should be able to load development and not load staging or production
let env = await envkeyFetch(devEnvkeyIdPart, devEncryptionKey);
expect(env).toEqual({});
envkeyFetchExpectError(stagingEnvkeyIdPart, stagingEncryptionKey);
envkeyFetchExpectError(prodEnvkeyIdPart, prodEncryptionKey);
// update org allowed ips
res = await dispatch(
{
type: Api.ActionType.SET_ORG_ALLOWED_IPS,
payload: {
environmentRoleIpsAllowed: {
[development.environmentRoleId]: ["::ffff:127.0.0.9"],
[staging.environmentRoleId]: ["::ffff:127.0.0.1"],
[production.environmentRoleId]: ["::ffff:127.0.0.1"],
},
},
},
ownerId
);
expect(res.success).toBe(true);
// ensure update got through to ENVKEYs
envkeyFetchExpectError(devEnvkeyIdPart, devEncryptionKey);
env = await envkeyFetch(stagingEnvkeyIdPart, stagingEncryptionKey);
expect(env).toEqual({});
envkeyFetchExpectError(prodEnvkeyIdPart, prodEncryptionKey);
// updated app allowed ips
res = await dispatch(
{
type: Api.ActionType.SET_APP_ALLOWED_IPS,
payload: {
id: app.id,
environmentRoleIpsMergeStrategies: {
[development.environmentRoleId]: "override",
[staging.environmentRoleId]: "override",
[production.environmentRoleId]: "extend",
},
environmentRoleIpsAllowed: {
[development.environmentRoleId]: ["::ffff:127.0.0.1"],
[staging.environmentRoleId]: ["192.168.202.1"],
[production.environmentRoleId]: ["::ffff:127.0.0.0/30"],
},
},
},
ownerId
);
expect(res.success).toBe(true);
// ensure update got through to ENVKEYs
env = await envkeyFetch(devEnvkeyIdPart, devEncryptionKey);
expect(env).toEqual({});
envkeyFetchExpectError(stagingEnvkeyIdPart, stagingEncryptionKey);
env = await envkeyFetch(prodEnvkeyIdPart, prodEncryptionKey);
expect(env).toEqual({});
});
});
}); | the_stack |
import { Reducer, combineReducers } from 'redux'
import { handleActions } from 'redux-actions'
import omit from 'lodash/omit'
import mapValues from 'lodash/mapValues'
import pickBy from 'lodash/pickBy'
import { FIXED_TRASH_ID } from '../../constants'
import { getPDMetadata } from '../../file-types'
import {
SingleLabwareLiquidState,
LocationLiquidState,
LabwareLiquidState,
} from '@opentrons/step-generation'
import { Action, DeckSlot } from '../../types'
import { LiquidGroupsById, DisplayLabware } from '../types'
import { LoadFileAction } from '../../load-file'
import {
RemoveWellsContentsAction,
CreateContainerAction,
DeleteLiquidGroupAction,
DuplicateLabwareAction,
EditLiquidGroupAction,
SelectLiquidAction,
SetWellContentsAction,
RenameLabwareAction,
DeleteContainerAction,
OpenAddLabwareModalAction,
OpenIngredientSelectorAction,
CloseIngredientSelectorAction,
DrillDownOnLabwareAction,
DrillUpFromLabwareAction,
} from '../actions'
// REDUCERS
// modeLabwareSelection: boolean. If true, we're selecting labware to add to a slot
// (this state just toggles a modal)
// @ts-expect-error(sa, 2021-6-20): cannot use string literals as action type
// TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081
const modeLabwareSelection: Reducer<DeckSlot | false, any> = handleActions(
{
// @ts-expect-error(sa, 2021-6-20): cannot use string literals as action type
OPEN_ADD_LABWARE_MODAL: (state, action: OpenAddLabwareModalAction) =>
action.payload.slot,
CLOSE_LABWARE_SELECTOR: () => false,
CREATE_CONTAINER: () => false,
},
false
)
export type SelectedContainerId = string | null | undefined
// @ts-expect-error(sa, 2021-6-20): cannot use string literals as action type
// TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081
const selectedContainerId: Reducer<SelectedContainerId, any> = handleActions(
{
OPEN_INGREDIENT_SELECTOR: (
state,
action: OpenIngredientSelectorAction
): SelectedContainerId => action.payload,
CLOSE_INGREDIENT_SELECTOR: (
state,
action: CloseIngredientSelectorAction
): SelectedContainerId => null,
},
null
)
export type DrillDownLabwareId = string | null | undefined
// @ts-expect-error(sa, 2021-6-20): cannot use string literals as action type
// TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081
const drillDownLabwareId: Reducer<DrillDownLabwareId, any> = handleActions(
{
DRILL_DOWN_ON_LABWARE: (
state,
action: DrillDownOnLabwareAction
): DrillDownLabwareId => action.payload,
DRILL_UP_FROM_LABWARE: (
state,
action: DrillUpFromLabwareAction
): DrillDownLabwareId => null,
},
null
)
export type ContainersState = Record<string, DisplayLabware | null | undefined>
export interface SelectedLiquidGroupState {
liquidGroupId: string | null | undefined
newLiquidGroup?: true
}
const unselectedLiquidGroupState = {
liquidGroupId: null,
}
// This is only a concern of the liquid page.
// null = nothing selected, newLiquidGroup: true means user is creating new liquid
const selectedLiquidGroup = handleActions(
{
// @ts-expect-error(sa, 2021-6-20): cannot use string literals as action type
// TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081
SELECT_LIQUID_GROUP: (
state: SelectedLiquidGroupState,
action: SelectLiquidAction
): SelectedLiquidGroupState => ({
liquidGroupId: action.payload,
}),
DELETE_LIQUID_GROUP: () => unselectedLiquidGroupState,
DESELECT_LIQUID_GROUP: () => unselectedLiquidGroupState,
CREATE_NEW_LIQUID_GROUP_FORM: (): SelectedLiquidGroupState => ({
liquidGroupId: null,
newLiquidGroup: true,
}),
EDIT_LIQUID_GROUP: () => unselectedLiquidGroupState, // clear on form save
},
unselectedLiquidGroupState
)
const initialLabwareState: ContainersState = {
[FIXED_TRASH_ID]: {
nickname: 'Trash',
},
}
// @ts-expect-error(sa, 2021-6-20): cannot use string literals as action type
// TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081
export const containers: Reducer<ContainersState, any> = handleActions(
{
CREATE_CONTAINER: (
state: ContainersState,
action: CreateContainerAction
): ContainersState => {
const id = action.payload.id
return {
...state,
[id]: {
nickname: null, // create with null nickname, so we force explicit naming.
},
}
},
DELETE_CONTAINER: (
state: ContainersState,
action: DeleteContainerAction
): ContainersState =>
pickBy(
state,
// @ts-expect-error(sa, 2021-6-20): pickBy might return null or undefined
(value: DisplayLabware, key: string) => key !== action.payload.labwareId
),
RENAME_LABWARE: (
state: ContainersState,
action: RenameLabwareAction
): ContainersState => {
const { labwareId, name } = action.payload
// ignore renaming to whitespace
return name && name.trim()
? { ...state, [labwareId]: { ...state[labwareId], nickname: name } }
: state
},
DUPLICATE_LABWARE: (
state: ContainersState,
action: DuplicateLabwareAction
): ContainersState => {
const { duplicateLabwareId, duplicateLabwareNickname } = action.payload
return {
...state,
[duplicateLabwareId]: {
nickname: duplicateLabwareNickname,
},
}
},
LOAD_FILE: (
state: ContainersState,
action: LoadFileAction
): ContainersState => {
const { file } = action.payload
const allFileLabware = file.labware
const sortedLabwareIds: string[] = Object.keys(allFileLabware).sort(
(a, b) =>
Number(allFileLabware[a].slot) - Number(allFileLabware[b].slot)
)
return sortedLabwareIds.reduce(
(acc: ContainersState, id): ContainersState => {
const fileLabware = allFileLabware[id]
const nickname = fileLabware.displayName
const disambiguationNumber =
Object.keys(acc).filter(
(filterId: string) =>
allFileLabware[filterId].displayName === nickname
).length + 1
return {
...acc,
[id]: {
nickname,
disambiguationNumber,
},
}
},
{}
)
},
},
initialLabwareState
)
type SavedLabwareState = Record<string, boolean>
/** Keeps track of which labware have saved nicknames */
// @ts-expect-error(sa, 2021-6-20): cannot use string literals as action type
// TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081
export const savedLabware: Reducer<SavedLabwareState, any> = handleActions(
{
DELETE_CONTAINER: (
state: SavedLabwareState,
action: DeleteContainerAction
) => ({ ...state, [action.payload.labwareId]: false }),
RENAME_LABWARE: (
state: SavedLabwareState,
action: RenameLabwareAction
) => ({ ...state, [action.payload.labwareId]: true }),
DUPLICATE_LABWARE: (
state: SavedLabwareState,
action: DuplicateLabwareAction
) => ({ ...state, [action.payload.duplicateLabwareId]: true }),
LOAD_FILE: (
state: SavedLabwareState,
action: LoadFileAction
): SavedLabwareState => mapValues(action.payload.file.labware, () => true),
},
{}
)
export type IngredientsState = LiquidGroupsById
// @ts-expect-error(sa, 2021-6-20): cannot use string literals as action type
// TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081
export const ingredients: Reducer<IngredientsState, any> = handleActions(
{
EDIT_LIQUID_GROUP: (
state: IngredientsState,
action: EditLiquidGroupAction
): IngredientsState => {
const { liquidGroupId } = action.payload
return {
...state,
[liquidGroupId]: { ...state[liquidGroupId], ...action.payload },
}
},
DELETE_LIQUID_GROUP: (
state: IngredientsState,
action: DeleteLiquidGroupAction
): IngredientsState => {
const liquidGroupId = action.payload
return omit(state, liquidGroupId)
},
LOAD_FILE: (
state: IngredientsState,
action: LoadFileAction
): IngredientsState => getPDMetadata(action.payload.file).ingredients,
},
{}
)
type LocationsState = LabwareLiquidState
// @ts-expect-error(sa, 2021-6-20): cannot use string literals as action type
// TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081
export const ingredLocations: Reducer<LocationsState, any> = handleActions(
{
SET_WELL_CONTENTS: (
state: LocationsState,
action: SetWellContentsAction
): LocationsState => {
const { liquidGroupId, labwareId, wells, volume } = action.payload
const newWellContents: LocationLiquidState = {
[liquidGroupId]: {
volume,
},
}
const updatedWells = wells.reduce<SingleLabwareLiquidState>(
(acc, wellName) => ({ ...acc, [wellName]: newWellContents }),
{}
)
return { ...state, [labwareId]: { ...state[labwareId], ...updatedWells } }
},
DUPLICATE_LABWARE: (
state: LocationsState,
action: DuplicateLabwareAction
): LocationsState => {
const { templateLabwareId, duplicateLabwareId } = action.payload
return { ...state, [duplicateLabwareId]: { ...state[templateLabwareId] } }
},
REMOVE_WELLS_CONTENTS: (
state: LocationsState,
action: RemoveWellsContentsAction
): LocationsState => {
const { wells, labwareId } = action.payload
return { ...state, [labwareId]: { ...omit(state[labwareId], wells) } }
},
DELETE_LIQUID_GROUP: (
state: LocationsState,
action: DeleteLiquidGroupAction
): LocationsState => {
const liquidGroupId = action.payload
return mapValues(state, labwareContents =>
mapValues(labwareContents, well => omit(well, liquidGroupId))
)
},
DELETE_CONTAINER: (
state: LocationsState,
action: DeleteContainerAction
): LocationsState => omit(state, action.payload.labwareId),
LOAD_FILE: (
state: LocationsState,
action: LoadFileAction
): LocationsState => getPDMetadata(action.payload.file).ingredLocations,
},
{}
)
export interface RootState {
modeLabwareSelection: DeckSlot | false
selectedContainerId: SelectedContainerId
drillDownLabwareId: DrillDownLabwareId
containers: ContainersState
savedLabware: SavedLabwareState
selectedLiquidGroup: SelectedLiquidGroupState
ingredients: IngredientsState
ingredLocations: LocationsState
}
// TODO Ian 2018-01-15 factor into separate files
export const rootReducer: Reducer<RootState, Action> = combineReducers({
modeLabwareSelection,
selectedContainerId,
selectedLiquidGroup,
drillDownLabwareId,
containers,
savedLabware,
ingredients,
ingredLocations,
}) | the_stack |
import * as React from "react";
import { mount } from "enzyme";
import DateUtil from "#SRC/js/utils/DateUtil";
import JestUtil from "#SRC/js/utils/JestUtil";
import PodInstancesTable from "../PodInstancesTable";
import Pod from "../../../structs/Pod";
import PodFixture from "../../../../../../../tests/_fixtures/pods/PodFixture";
import Util from "#SRC/js/utils/Util";
let thisInstance;
describe("PodInstancesTable", () => {
// Fix the dates in order to test the relative date field
const fixture = Util.deepCopy(PodFixture);
fixture.instances[0].lastUpdated = new Date(
Date.now() - 86400000 * 1
).toString();
fixture.instances[0].lastChanged = new Date(
Date.now() - 86400000 * 2
).toString();
fixture.instances[0].containers[0].lastUpdated = new Date(
Date.now() - 86400000 * 3
).toString();
fixture.instances[0].containers[0].lastChanged = new Date(
Date.now() - 86400000 * 4
).toString();
fixture.instances[0].containers[1].lastUpdated = new Date(
Date.now() - 86400000 * 5
).toString();
fixture.instances[0].containers[1].lastChanged = new Date(
Date.now() - 86400000 * 6
).toString();
fixture.instances[1].lastUpdated = new Date(
Date.now() - 86400000 * 7
).toString();
fixture.instances[1].lastChanged = new Date(
Date.now() - 86400000 * 8
).toString();
fixture.instances[1].containers[0].lastUpdated = new Date(
Date.now() - 86400000 * 9
).toString();
fixture.instances[1].containers[0].lastChanged = new Date(
Date.now() - 86400000 * 10
).toString();
fixture.instances[1].containers[1].lastUpdated = new Date(
Date.now() - 86400000 * 11
).toString();
fixture.instances[1].containers[1].lastChanged = new Date(
Date.now() - 86400000 * 12
).toString();
fixture.instances[2].lastUpdated = new Date(
Date.now() - 86400000 * 13
).toString();
fixture.instances[2].lastChanged = new Date(
Date.now() - 86400000 * 14
).toString();
fixture.instances[2].containers[0].lastUpdated = new Date(
Date.now() - 86400000 * 15
).toString();
fixture.instances[2].containers[0].lastChanged = new Date(
Date.now() - 86400000 * 16
).toString();
fixture.instances[2].containers[1].lastUpdated = new Date(
Date.now() - 86400000 * 17
).toString();
fixture.instances[2].containers[1].lastChanged = new Date(
Date.now() - 86400000 * 18
).toString();
const pod = new Pod(fixture);
describe("#render", () => {
beforeEach(() => {
JestUtil.mockTimezone("Europe/Berlin");
});
afterEach(() => {
JestUtil.unmockTimezone();
});
describe("collapsed table", () => {
beforeEach(() => {
const WrappedComponent = JestUtil.withI18nProvider(PodInstancesTable);
thisInstance = mount(
<WrappedComponent
pod={pod}
instances={pod.getInstanceList().getItems()}
/>
);
});
it("renders the name column", () => {
const names = thisInstance
.find(".task-table-column-primary .collapsing-string-full-string")
.map((el) => el.text());
expect(names).toEqual(["instance-1", "instance-2", "instance-3"]);
});
it("renders the address column", () => {
const names = thisInstance
.find(
".task-table-column-host-address .collapsing-string-full-string"
)
.map((el) => el.text());
expect(names).toEqual(["agent-1", "agent-2", "agent-3"]);
});
it("renders the region column", () => {
const regions = thisInstance
.find("td.task-table-column-region")
.map((el) => el.text());
expect(regions).toEqual(["N/A", "N/A", "N/A"]);
});
it("renders the zone column", () => {
const zones = thisInstance
.find("td.task-table-column-zone")
.map((el) => el.text());
expect(zones).toEqual(["N/A", "N/A", "N/A"]);
});
it("renders the status column", () => {
const names = thisInstance
.find(".task-table-column-status span.status-text")
.map((el) => el.text());
expect(names).toEqual(["Running", "Running", "Staging"]);
});
it("renders the cpu column", () => {
const names = thisInstance
.find("td.task-table-column-cpus")
.map((el) => el.text());
expect(names).toEqual(["1", "1", "1"]);
});
it("renders the mem column", () => {
const names = thisInstance
.find("td.task-table-column-mem")
.map((el) => el.text());
expect(names).toEqual(["128 MiB", "128 MiB", "128 MiB"]);
});
it("renders the updated column", () => {
const names = thisInstance
.find("td.task-table-column-updated")
.map((el) => el.text());
expect(names).toEqual(["1 day ago", "7 days ago", "13 days ago"]);
});
it("renders the version column", () => {
const names = thisInstance
.find("td.task-table-column-version")
.map((el) => el.text());
expect(names).toEqual([
Intl.DateTimeFormat("en", DateUtil.getFormatOptions()).format(
new Date(PodFixture.spec.version)
),
Intl.DateTimeFormat("en", DateUtil.getFormatOptions()).format(
new Date(PodFixture.spec.version)
),
Intl.DateTimeFormat("en", DateUtil.getFormatOptions()).format(
new Date(PodFixture.spec.version)
),
]);
});
});
describe("collapsed table, sorted ascending by name", () => {
beforeEach(() => {
// Create a stub router context because when the items are expanded
// the are creating <Link /> instances.
const WrappedComponent = JestUtil.withI18nProvider(
JestUtil.stubRouterContext(PodInstancesTable)
);
thisInstance = mount(
<WrappedComponent
pod={pod}
instances={pod.getInstanceList().getItems()}
service={pod}
/>
);
// 1 click on the header (ascending)
thisInstance.find(".task-table-column-primary").at(0).simulate("click");
});
it("sorts the name column", () => {
const names = thisInstance
.find(".task-table-column-primary .collapsing-string-full-string")
.map((el) => el.text());
expect(names).toEqual(["instance-1", "instance-2", "instance-3"]);
});
});
describe("collapsed table, sorted descending by name", () => {
beforeEach(() => {
// Create a stub router context because when the items are expanded
// the are creating <Link /> instances.
const WrappedComponent = JestUtil.withI18nProvider(
JestUtil.stubRouterContext(PodInstancesTable)
);
thisInstance = mount(
<WrappedComponent
pod={pod}
instances={pod.getInstanceList().getItems()}
service={pod}
/>
);
// 2 clicks on the header (descending)
const columnHeader = thisInstance
.find(".task-table-column-primary")
.at(0);
columnHeader.simulate("click").simulate("click");
});
it("sorts the name column", () => {
const names = thisInstance
.find(".task-table-column-primary .collapsing-string-full-string")
.map((el) => el.text());
expect(names).toEqual(["instance-3", "instance-2", "instance-1"]);
});
});
describe("expanded table", () => {
beforeEach(() => {
// Create a stub router context because when the items are expanded
// the are creating <Link /> instances.
const WrappedComponent = JestUtil.withI18nProvider(
JestUtil.stubRouterContext(PodInstancesTable)
);
thisInstance = mount(
<WrappedComponent
pod={pod}
instances={pod.getInstanceList().getItems()}
service={pod}
/>
);
// Expand all table rows by clicking on each one of them
thisInstance
.find(".task-table-column-primary .is-expandable")
.forEach((el) => {
el.simulate("click");
});
});
it("renders the name column", () => {
const names = thisInstance
.find(".task-table-column-primary .collapsing-string-full-string")
.map((el) => el.text());
expect(names).toEqual([
"instance-1",
"container-1",
"container-2",
"instance-2",
"container-1",
"container-2",
"instance-3",
"container-1",
"container-2",
]);
});
it("renders the address column", () => {
const columns = thisInstance.find(".task-table-column-host-address");
const agents = columns
.find(".collapsing-string-full-string")
.map((el) => el.text());
const ports = columns
.find("a")
.filterWhere((el) => !el.hasClass("table-cell-link-secondary"))
.map((el) => el.text());
expect(agents).toEqual(["agent-1", "agent-2", "agent-3"]);
expect(ports).toEqual([
"31001",
"31002",
"31011",
"31012",
"31021",
"31022",
]);
});
it("renders the status column", () => {
const names = thisInstance
.find(".task-table-column-status span.status-text")
.map((el) => el.text());
expect(names).toEqual([
"Running",
"Running",
"Running",
"Running",
"Running",
"Running",
"Staging",
"Staging",
"Staging",
]);
});
it("renders the updated column", () => {
const names = thisInstance
.find("td.task-table-column-updated time")
.map((el) => el.text());
expect(names).toEqual([
"1 day ago",
"3 days ago",
"5 days ago",
"7 days ago",
"9 days ago",
"11 days ago",
"13 days ago",
"15 days ago",
"17 days ago",
]);
});
it("renders the version column", () => {
const names = thisInstance
.find("td.task-table-column-version")
.map((el) => el.text().trim());
expect(names).toEqual([
Intl.DateTimeFormat("en", DateUtil.getFormatOptions()).format(
new Date(PodFixture.spec.version)
),
Intl.DateTimeFormat("en", DateUtil.getFormatOptions()).format(
new Date(PodFixture.spec.version)
),
Intl.DateTimeFormat("en", DateUtil.getFormatOptions()).format(
new Date(PodFixture.spec.version)
),
]);
});
});
});
}); | the_stack |
import {
isString,
isBlank,
isType,
resolveDirectiveNameFromSelector,
isPresent,
stringify,
getFuncName,
normalizeBool,
isArray
} from '../../facade/lang';
import { Type } from '../../facade/type';
import { reflector } from '../reflection/reflection';
import { OpaqueToken } from './opaque_token';
import {
OutputMetadata,
HostBindingMetadata,
HostListenerMetadata,
InputMetadata
} from '../directives/metadata_directives';
import { InjectMetadata, SkipSelfMetadata, SelfMetadata, HostMetadata } from './metadata';
import { pipeProvider } from '../pipes/pipe_provider';
import { directiveProvider } from '../directives/directive_provider';
import { ListWrapper } from '../../facade/collections';
import { resolveForwardRef } from './forward_ref';
import { getErrorMsg } from '../../facade/exceptions';
import { isPipe, isOpaqueToken, isDirectiveLike, isService } from './provider_util';
import { isComponent } from './provider_util';
import { isInjectMetadata } from './provider_util';
export type PropMetaInst = InputMetadata | OutputMetadata | HostBindingMetadata | HostListenerMetadata;
export type ParamMetaInst = HostMetadata | InjectMetadata | SelfMetadata | SkipSelfMetadata;
export type ProviderType = Type | OpaqueToken | Function | string ;
export type ProviderAliasOptions = {useClass?: Type,useValue?: any,useFactory?: Function, deps?: Object[]};
export class Provider {
/**
* Token used when retrieving this provider. Usually, it is a type {@link Type}.
*/
token: any;
/**
* Binds a DI token to an implementation class.
*
* ### Example ([live demo](http://plnkr.co/edit/RSTG86qgmoxCyj9SWPwY?p=preview))
*
* Because `useExisting` and `useClass` are often confused, the example contains
* both use cases for easy comparison.
*
* ```typescript
* class Vehicle {}
*
* class Car extends Vehicle {}
*
* var injectorClass = Injector.resolveAndCreate([
* Car,
* {provide: Vehicle, useClass: Car }
* ]);
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* {provide: Vehicle, useExisting: Car }
* ]);
*
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
* expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
*
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
* expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
* ```
*/
useClass: Type;
/**
* Binds a DI token to a value.
*
* ### Example ([live demo](http://plnkr.co/edit/UFVsMVQIDe7l4waWziES?p=preview))
*
* ```javascript
* var injector = Injector.resolveAndCreate([
* new Provider("message", { useValue: 'Hello' })
* ]);
*
* expect(injector.get("message")).toEqual('Hello');
* ```
*/
useValue: any;
/**
* Binds a DI token to an existing token.
*
* {@link Injector} returns the same instance as if the provided token was used.
* This is in contrast to `useClass` where a separate instance of `useClass` is returned.
*
* ### Example ([live demo](http://plnkr.co/edit/QsatsOJJ6P8T2fMe9gr8?p=preview))
*
* Because `useExisting` and `useClass` are often confused the example contains
* both use cases for easy comparison.
*
* ```typescript
* class Vehicle {}
*
* class Car extends Vehicle {}
*
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* {provide: Vehicle, useExisting: Car }
* ]);
* var injectorClass = Injector.resolveAndCreate([
* Car,
* {provide: Vehicle, useClass: Car }
* ]);
*
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
* expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
*
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
* expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
* ```
*/
useExisting: any;
/**
* Binds a DI token to a function which computes the value.
*
* ### Example ([live demo](http://plnkr.co/edit/Scoxy0pJNqKGAPZY1VVC?p=preview))
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* {provide: Number, useFactory: () => { return 1+2; }},
* new Provider(String, { useFactory: (value) => { return "Value: " + value; },
* deps: [Number] })
* ]);
*
* expect(injector.get(Number)).toEqual(3);
* expect(injector.get(String)).toEqual('Value: 3');
* ```
*
* Used in conjunction with dependencies.
*/
useFactory: Function;
/**
* Specifies a set of dependencies
* (as `token`s) which should be injected into the factory function.
*
* ### Example ([live demo](http://plnkr.co/edit/Scoxy0pJNqKGAPZY1VVC?p=preview))
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* {provide: Number, useFactory: () => { return 1+2; }},
* new Provider(String, { useFactory: (value) => { return "Value: " + value; },
* deps: [Number] })
* ]);
*
* expect(injector.get(Number)).toEqual(3);
* expect(injector.get(String)).toEqual('Value: 3');
* ```
*
* Used in conjunction with `useFactory`.
*/
dependencies: Object[];
/** @internal */
_multi: boolean;
constructor(
token: any , {useClass, useValue, useExisting, useFactory, deps, multi}: {
useClass?: Type,
useValue?: any,
useExisting?: any,
useFactory?: Function,
deps?: Object[],
multi?: boolean
}) {
this.token = token;
this.useClass = useClass;
this.useValue = useValue;
this.useExisting = useExisting;
this.useFactory = useFactory;
this.dependencies = deps;
this._multi = multi;
}
/**
* Creates multiple providers matching the same token (a multi-provider).
*
* Multi-providers are used for creating pluggable service, where the system comes
* with some default providers, and the user can register additional providers.
* The combination of the default providers and the additional providers will be
* used to drive the behavior of the system.
*
* ### Example
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* new Provider("Strings", { useValue: "String1", multi: true}),
* new Provider("Strings", { useValue: "String2", multi: true})
* ]);
*
* expect(injector.get("Strings")).toEqual(["String1", "String2"]);
* ```
*
* Multi-providers and regular providers cannot be mixed. The following
* will throw an exception:
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* new Provider("Strings", { useValue: "String1", multi: true }),
* new Provider("Strings", { useValue: "String2"})
* ]);
* ```
*/
get multi(): boolean { return normalizeBool(this._multi); }
}
class ProviderBuilder{
static createFromType(
type: ProviderType,
{ useClass, useValue, useFactory, deps }: ProviderAliasOptions
): [string,Type|Function] {
// ...provide('myFactory',{useFactory: () => () => { return new Foo(); } })
if ( isPresent( useFactory ) ) {
const factoryToken = getInjectableName(type);
const injectableDeps = isArray( deps ) ? deps.map(getInjectableName) : [];
useFactory.$inject = injectableDeps;
return [
factoryToken,
useFactory
];
}
// ...provide(opaqueTokenInst,{useValue: {foo:12312} })
// ...provide('myValue',{useValue: {foo:12312} })
if ( isPresent( useValue ) ) {
const valueToken = getInjectableName(type);
return [
valueToken,
useValue
];
}
const injectableType = isString( type ) || isOpaqueToken( type )
? resolveForwardRef(useClass as Type)
: resolveForwardRef(type as Type);
const overrideName = isString( type ) || isOpaqueToken( type )
? getInjectableName(type)
: '';
if ( !isType( injectableType ) ) {
throw new Error( `
Provider registration: "${stringify( injectableType )}":
=======================================================
token ${ stringify( injectableType ) } must be type of Type, You cannot provide none class
` );
}
/**
*
* @type {any[]}
*/
const annotations = reflector.annotations( injectableType );
const [rootAnnotation] = annotations;
// No Annotation === it's config function !!!
// NOTE: we are not checking anymore if user annotated the class or not,
// we cannot do that anymore at the costs for nic config functions registration
if ( ListWrapper.isEmpty( annotations ) ) {
return [ injectableType ] as any;
}
if ( ListWrapper.size( annotations ) > 1 ) {
const hasComponentAnnotation = annotations.some( meta=>isComponent( meta ) );
const hasNotAllowedSecondAnnotation = annotations.some( meta=> {
return isDirectiveLike( meta ) || isService( meta ) || isPipe( meta );
} );
if ( !hasComponentAnnotation || (hasNotAllowedSecondAnnotation && hasComponentAnnotation) ) {
throw Error( `
Provider registration: "${ stringify( injectableType ) }":
=======================================================
- you cannot use more than 1 class decorator,
- you've used ${ annotations.map(meta=>stringify(meta.constructor)) }
Multiple class decorators are allowed only for component class: [ @Component, @StateConfig? ]
` )
}
}
injectableType.$inject = _dependenciesFor( injectableType );
if ( isPipe( rootAnnotation ) ) {
return pipeProvider.createFromType( injectableType );
}
if ( isDirectiveLike( rootAnnotation ) ) {
return directiveProvider.createFromType( injectableType );
}
if ( isService( rootAnnotation ) ) {
return [
overrideName || rootAnnotation.id,
injectableType
];
}
}
}
/**
* should extract the string token from provided Type and add $inject angular 1 annotation to constructor if @Inject
* was used
* @returns {[string,Type]}
* @deprecated
*/
export function provide(
type: ProviderType,
{ useClass, useValue, useFactory, deps }: ProviderAliasOptions = {}
): [string,Type|Function] {
return ProviderBuilder.createFromType( type, { useClass, useValue, useFactory, deps } );
}
/**
* creates $inject array Angular 1 DI annotation strings for provided Type
* @param typeOrFunc
* @returns {any}
* @private
* @internal
*/
export function _dependenciesFor(typeOrFunc: Type): string[] {
const params = reflector.parameters(typeOrFunc);
if ( isBlank( params ) ) return [];
if ( params.some( ( param ) => isBlank( param ) || ListWrapper.isEmpty( param ) ) ) {
throw new Error(
getErrorMsg(
typeOrFunc,
`you cannot have holes in constructor DI injection`
)
);
}
return params
.map( ( p: any[] ) => _extractToken( p ) );
}
/**
* should extract service/values/directives/pipes token from constructor @Inject() paramMetadata
* @param metadata
* @private
* @internal
*/
export function _extractToken( metadata: ParamMetaInst[] ): string {
// this is token obtained via design:paramtypes via Reflect.metadata
const [paramMetadata] = metadata.filter( isType );
// this is token obtained from @Inject() usage for DI
const [injectMetadata] = metadata.filter( isInjectMetadata ) as InjectMetadata[];
if(isBlank(injectMetadata) && isBlank(paramMetadata)){
return;
}
const { token=undefined } = injectMetadata || {};
const injectable = resolveForwardRef( token ) || paramMetadata;
return getInjectableName( injectable );
}
/**
* A utility function that can be used to get the angular 1 injectable's name. Needed for some cases, since
* injectable names are auto-created.
*
* Works for string/OpaqueToken/Type
* Note: Type must be decorated otherwise it throws
*
* @example
* ```typescript
* import { Injectable, getInjectableName } from 'ng-metadata/core';
* // this is given some random name like 'myService48' when it's created with `module.service`
*
* @Injectable
* class MyService {}
*
* console.log(getInjectableName(MyService)); // 'myService48'
* ```
*
* @param {ProviderType} injectable
* @returns {string}
*/
export function getInjectableName( injectable: ProviderType ): string {
// @Inject('foo') foo
if ( isString( injectable ) ) {
return injectable;
}
// const fooToken = new OpaqueToken('foo')
// @Inject(fooToken) foo
if ( isOpaqueToken(injectable) ) {
return injectable.desc;
}
// @Injectable()
// class SomeService(){}
//
// @Inject(SomeService) someSvc
// someSvc: SomeService
if ( isType( injectable ) ) {
// only the first class annotations is injectable
const [annotation] = reflector.annotations( injectable );
if ( isBlank( annotation ) ) {
throw new Error( `
cannot get injectable name token from none decorated class ${ getFuncName( injectable ) }
Only decorated classes by one of [ @Injectable,@Directive,@Component,@Pipe ], can be injected by reference
` );
}
if ( isPipe(annotation) ) {
return annotation.name;
}
if ( isDirectiveLike( annotation ) ) {
return resolveDirectiveNameFromSelector( annotation.selector );
}
if ( isService( annotation ) ) {
return annotation.id;
}
}
}
/**
*
* @param metadata
* @returns {boolean}
* @private
* @internal
* @deprecated
*
* @TODO: delete this
*/
export function _areAllDirectiveInjectionsAtTail( metadata: ParamMetaInst[][] ): boolean {
return metadata.every( ( paramMetadata, idx, arr )=> {
const isCurrentDirectiveInjection = paramMetadata.length > 1;
const hasPrev = idx > 0;
const hasNext = idx < arr.length - 1;
if ( hasPrev ) {
const prevInjection = arr[ idx - 1 ];
const isPrevDirectiveInjection = prevInjection.length > 1;
if ( isPrevDirectiveInjection && !isCurrentDirectiveInjection ) {
return false;
}
}
if ( hasNext ) {
const nextInjection = arr[ idx + 1 ];
const isNextDirectiveInjection = nextInjection.length > 1;
if ( !isNextDirectiveInjection && isNextDirectiveInjection ) {
return false;
}
}
return true;
} );
} | the_stack |
import * as _ from "lodash";
import * as ExtensionApi from "@extraterm/extraterm-extension-api";
import { EventEmitter } from "extraterm-event-emitter";
import { CustomElement } from "extraterm-web-component-decorators";
import * as ThemeTypes from "../../../theme/Theme";
import { EtTerminal, LineRangeChange } from "../../Terminal";
import { InternalExtensionContext, InternalWindow, InternalSessionSettingsEditor, InternalSessionEditor, ViewerTabDisplay } from "../InternalTypes";
import { Logger, getLogger, log } from "extraterm-logging";
import { WorkspaceSessionEditorRegistry } from "../WorkspaceSessionEditorRegistry";
import { WorkspaceViewerRegistry, ExtensionViewerBaseImpl } from "../WorkspaceViewerRegistry";
import { CommonExtensionWindowState } from "../CommonExtensionState";
import { SessionSettingsEditorFactory, SessionConfiguration, ViewerMetadata, ViewerPosture } from "@extraterm/extraterm-extension-api";
import { ViewerElement } from "../../viewers/ViewerElement";
import { WorkspaceSessionSettingsRegistry } from "../WorkspaceSessionSettingsRegistry";
import { TerminalProxy } from "../proxy/TerminalProxy";
import { ExtensionContainerElement } from "../ExtensionContainerElement";
import { ExtensionTabContribution } from "extraterm/src/ExtensionMetadata";
import { ThemeableElementBase } from "../../ThemeableElementBase";
/**
* The implementation behind the `Window` object on the `ExtensionContext`
* which is given to extensions when loading them.
*
* Each extension gets its own instance of this.
*/
export class WindowProxy implements InternalWindow {
private _log: Logger = null;
#internalExtensionContext: InternalExtensionContext = null;
#commonExtensionState: CommonExtensionWindowState = null;
#windowSessionEditorRegistry: WorkspaceSessionEditorRegistry = null;
#windowSessionSettingsRegistry: WorkspaceSessionSettingsRegistry = null;
#windowViewerRegistry: WorkspaceViewerRegistry = null;
#terminalBorderWidgetFactoryMap = new Map<string, ExtensionApi.TerminalBorderWidgetFactory>();
#onDidCreateTerminalEventEmitter = new EventEmitter<ExtensionApi.Terminal>();
onDidCreateTerminal: ExtensionApi.Event<ExtensionApi.Terminal>;
#allTerminals: EtTerminal[] = [];
constructor(internalExtensionContext: InternalExtensionContext, commonExtensionState: CommonExtensionWindowState) {
this._log = getLogger("WorkspaceProxy", this);
this.#internalExtensionContext = internalExtensionContext;
this. #commonExtensionState = commonExtensionState;
this.onDidCreateTerminal = this.#onDidCreateTerminalEventEmitter.event;
this.#windowSessionEditorRegistry = new WorkspaceSessionEditorRegistry(this.#internalExtensionContext);
this.#windowSessionSettingsRegistry = new WorkspaceSessionSettingsRegistry(this.#internalExtensionContext);
this.#windowViewerRegistry = new WorkspaceViewerRegistry(this.#internalExtensionContext);
this.extensionViewerBaseConstructor = ExtensionViewerBaseImpl;
}
newTerminalCreated(newTerminal: EtTerminal, allTerminals: EtTerminal[]): void {
this.#allTerminals = allTerminals;
if (this.#onDidCreateTerminalEventEmitter.hasListeners()) {
const terminal = this.#internalExtensionContext._proxyFactory.getTerminalProxy(newTerminal);
this.#onDidCreateTerminalEventEmitter.fire(terminal);
}
}
terminalDestroyed(deadTerminal: EtTerminal, allTerminals: EtTerminal[]): void {
this.#allTerminals = allTerminals;
}
terminalAppendedViewer(terminal: EtTerminal, viewer: ViewerElement): void {
if (this.#internalExtensionContext._proxyFactory.hasTerminalProxy(terminal)) {
const proxy = <TerminalProxy> this.#internalExtensionContext._proxyFactory.getTerminalProxy(terminal);
if (proxy._onDidAppendBlockEventEmitter.hasListeners()) {
proxy._onDidAppendBlockEventEmitter.fire(this.#internalExtensionContext._proxyFactory.getBlock(viewer));
}
}
}
terminalEnvironmentChanged(terminal: EtTerminal, changeList: string[]): void {
if (this.#internalExtensionContext._proxyFactory.hasTerminalProxy(terminal)) {
const proxy = <TerminalProxy> this.#internalExtensionContext._proxyFactory.getTerminalProxy(terminal);
if (proxy.environment._onChangeEventEmitter.hasListeners()) {
proxy.environment._onChangeEventEmitter.fire(changeList);
}
}
}
terminalDidAppendScrollbackLines(terminal: EtTerminal, ev: LineRangeChange): void {
if (this.#internalExtensionContext._proxyFactory.hasTerminalProxy(terminal)) {
const proxy = <TerminalProxy> this.#internalExtensionContext._proxyFactory.getTerminalProxy(terminal);
if (proxy._onDidAppendScrollbackLinesEventEmitter.hasListeners()) {
const block = this.#internalExtensionContext._proxyFactory.getBlock(ev.viewer);
proxy._onDidAppendScrollbackLinesEventEmitter.fire({
block,
startLine: ev.startLine,
endLine: ev.endLine
});
}
}
}
terminalDidScreenChange(terminal: EtTerminal, ev: LineRangeChange): void {
if (this.#internalExtensionContext._proxyFactory.hasTerminalProxy(terminal)) {
const proxy = <TerminalProxy> this.#internalExtensionContext._proxyFactory.getTerminalProxy(terminal);
if (proxy._onDidScreenChangeEventEmitter.hasListeners()) {
const block = this.#internalExtensionContext._proxyFactory.getBlock(ev.viewer);
if (ev.startLine !== -1 && ev.endLine !== -1) {
proxy._onDidScreenChangeEventEmitter.fire({
block,
startLine: ev.startLine,
endLine: ev.endLine
});
}
}
}
}
get activeTerminal(): ExtensionApi.Terminal {
return this.#internalExtensionContext._proxyFactory.getTerminalProxy(this.#commonExtensionState.activeTerminal);
}
get activeBlock(): ExtensionApi.Block {
return this.#internalExtensionContext._proxyFactory.getBlock(this.#commonExtensionState.activeViewerElement);
}
get activeHyperlinkURL(): string {
return this.#commonExtensionState.activeHyperlinkURL;
}
get terminals(): ExtensionApi.Terminal[] {
return this.#allTerminals.map(t => this.#internalExtensionContext._proxyFactory.getTerminalProxy(t));
}
// ---- Viewers ----
extensionViewerBaseConstructor: ExtensionApi.ExtensionViewerBaseConstructor;
registerViewer(name: string, viewerClass: ExtensionApi.ExtensionViewerBaseConstructor): void {
this.#windowViewerRegistry.registerViewer(name, viewerClass);
}
findViewerElementTagByMimeType(mimeType: string): string {
return this.#windowViewerRegistry.findViewerElementTagByMimeType(mimeType);
}
// ---- Session Editors ----
registerSessionEditor(type: string, factory: ExtensionApi.SessionEditorFactory): void {
this.#windowSessionEditorRegistry.registerSessionEditor(type, factory);
}
createSessionEditor(sessionType: string, sessionConfiguration: SessionConfiguration): InternalSessionEditor {
return this.#windowSessionEditorRegistry.createSessionEditor(sessionType, sessionConfiguration);
}
// ---- Tab Title Widgets ----
registerTabTitleWidget(name: string, factory: ExtensionApi.TabTitleWidgetFactory): void {
this.#internalExtensionContext._registerTabTitleWidget(name, factory);
}
// ---- Terminal Border Widgets ----
registerTerminalBorderWidget(name: string, factory: ExtensionApi.TerminalBorderWidgetFactory): void {
const borderWidgetMeta = this.#internalExtensionContext._extensionMetadata.contributes.terminalBorderWidgets;
for (const data of borderWidgetMeta) {
if (data.name === name) {
this.#terminalBorderWidgetFactoryMap.set(name, factory);
return;
}
}
this.#internalExtensionContext.logger.warn(
`Unknown terminal border widget '${name}' given to registerTerminalBorderWidget().`);
}
getTerminalBorderWidgetFactory(name: string): ExtensionApi.TerminalBorderWidgetFactory {
return this.#terminalBorderWidgetFactoryMap.get(name);
}
// ---- Session Settings editors ----
registerSessionSettingsEditor(id: string, factory: SessionSettingsEditorFactory): void {
this.#windowSessionSettingsRegistry.registerSessionSettingsEditor(id, factory);
}
createSessionSettingsEditors(sessionType: string,
sessionConfiguration: SessionConfiguration): InternalSessionSettingsEditor[] {
return this.#windowSessionSettingsRegistry.createSessionSettingsEditors(sessionType, sessionConfiguration);
}
createExtensionTab(name: string): ExtensionApi.ExtensionTab {
const etc = this._findExtensionTabContribution(name);
if (etc == null) {
this.#internalExtensionContext.logger.warn(
`Unknown extension tab '${name}' given to openExtensionTab().`);
return null;
}
const extensionContainerElement = <ExtensionContainerElement> document.createElement(ExtensionContainerElement.TAG_NAME);
extensionContainerElement._setExtensionContext(this.#internalExtensionContext);
extensionContainerElement._setExtensionCss(etc.css);
const extensionTabViewer = <ExtensionContainerViewer> document.createElement("et-extension-container-viewer");
extensionTabViewer.shadowRoot.appendChild(extensionContainerElement);
return new ExtensionTabImpl(extensionContainerElement, extensionTabViewer,
this.#internalExtensionContext._extensionManager.getViewerTabDisplay());
}
private _findExtensionTabContribution(name: string): ExtensionTabContribution {
const extensionTabs = this.#internalExtensionContext._extensionMetadata.contributes.tabs;
for (const t of extensionTabs) {
if (t.name === name) {
return t;
}
}
return null;
}
}
class ExtensionTabImpl implements ExtensionApi.ExtensionTab {
#extensionContainerElement: ExtensionContainerElement = null;
#extensionContainerViewer: ExtensionContainerViewer = null;
#viewerTabDisplay: ViewerTabDisplay = null;
#isOpen = false;
onClose: ExtensionApi.Event<void>;
#onCloseEventEmitter = new EventEmitter<void>();
constructor(extensionContainerElement: ExtensionContainerElement,
extensionContainerViewer: ExtensionContainerViewer, viewerTabDisplay: ViewerTabDisplay) {
this.#extensionContainerElement = extensionContainerElement;
this.#extensionContainerViewer = extensionContainerViewer;
this.#viewerTabDisplay = viewerTabDisplay;
this.onClose = this.#onCloseEventEmitter.event;
extensionContainerViewer.onClose(() => {
this.#isOpen = false;
this.#onCloseEventEmitter.fire();
});
}
get containerElement(): HTMLElement {
return this.#extensionContainerElement.getContainerElement();
}
open(): void {
if ( ! this.#isOpen) {
this.#viewerTabDisplay.openViewerTab(this.#extensionContainerViewer);
this.#isOpen = true;
}
this.#viewerTabDisplay.switchToTab(this.#extensionContainerViewer);
}
close(): void {
this.#viewerTabDisplay.closeViewerTab(this.#extensionContainerViewer);
this.#isOpen = false;
}
get icon(): string {
return this.#extensionContainerViewer.getIcon();
}
set icon(icon: string) {
this.#extensionContainerViewer.setIcon(icon);
}
get title(): string {
return this.#extensionContainerViewer.getTitle();
}
set title(title: string) {
this.#extensionContainerViewer.setTitle(title);
}
}
@CustomElement("et-extension-container-viewer")
class ExtensionContainerViewer extends ViewerElement {
#viewerMetadata: ViewerMetadata = null;
onClose: ExtensionApi.Event<void>;
#onCloseEventEmitter = new EventEmitter<void>();
constructor() {
super();
this.onClose = this.#onCloseEventEmitter.event;
this.#viewerMetadata = {
title: "",
icon: null,
posture: ViewerPosture.NEUTRAL,
moveable: true,
deleteable: true,
toolTip: null
};
const shadow = this.attachShadow({ mode: "open", delegatesFocus: false });
const themeStyle = document.createElement("style");
themeStyle.id = ThemeableElementBase.ID_THEME;
shadow.appendChild(themeStyle);
this.updateThemeCss();
}
protected _themeCssFiles(): ThemeTypes.CssFile[] {
return [ThemeTypes.CssFile.EXTENSION_TAB];
}
getMetadata(): ViewerMetadata {
return this.#viewerMetadata;
}
getIcon(): string {
return this.#viewerMetadata.icon;
}
setIcon(icon: string): void {
this.#viewerMetadata.icon = icon;
this.metadataChanged();
}
getTitle(): string {
return this.#viewerMetadata.title;
}
setTitle(title: string): void {
this.#viewerMetadata.title = title;
this.metadataChanged();
}
didClose(): void {
super.didClose();
this.#onCloseEventEmitter.fire();
}
} | the_stack |
import React, {ReactNode} from 'react';
import Types from '../types';
import { IComponent} from "../types/component";
import { IInfrastructure } from "../types";
import {
setEntry, ddbGetEntry, ddbListEntries, getEntryListQuery, getEntryQuery, setEntryMutation, deleteEntryMutation,
deleteEntry, getEntryScanQuery, ddbScan
} from './datalayer-libs';
import createMiddleware from '../middleware/middleware-component';
import {
graphql,
GraphQLObjectType,
GraphQLString,
GraphQLNonNull,
GraphQLList,
GraphQLInputObjectType
} from 'graphql';
export const ENTRY_INSTANCE_TYPE = "EntryComponent";
/**
* Specifies all the properties that a Entity-Component must have
*/
export interface IEntryArgs {
/**
* the id must be unique across all entities of the data-layer
*/
id: string,
/**
* the primary key, not necessarily unique, but must be unique in combination with the rangeKey
*/
primaryKey: string,
/**
* second part of the overall primary key
*/
rangeKey: string,
/**
* any jsonifyable object that holds data
*/
data: any
};
export interface IEntryProps {
createEntryFields: () => any,
createEntryType: (prefix: string) => any,
createKeyArgs: () => any,
/**
* creates an argument list of all the data of the entry, keys+jsonData
* @param entry
* @returns {{}}
*/
createEntryArgs: () => any,
/**
* Get a list of entries that satisfy the query
*
* @param dictKey an object that has one key that specifies the pk or sk to query with its value
*/
getEntryListQuery: (dictKey: any) => any,
getEntryQuery: (dictKey: any) => any,
getEntryScanQuery: (dictKey: any) => any,
/**
* set an entry with the specified values
*
* @param values
*/
setEntryMutation: (values: any) => any,
setEntry: (args, context, tableName, isOffline) => any,
listEntries: (args, context, tableName, key, isOffline) => any,
getEntry: (args, context, tableName, isOffline) => any,
scan: (args, context, tableName, isOffline) => any,
middleware: any,
/**
* delete an entry with the specified values
*
* @param values
*/
deleteEntryMutation: (values: any) => any,
deleteEntry: (args, context, tableName, isOffline) => any,
/**
* Provide the name of the list-query with primary entity
*/
getPrimaryListQueryName: () => string,
getSecondaryListQueryName: () => string,
getGetQueryName: () => string,
getSetMutationName: () => string,
getPrimaryScanName: () => string,
getRangeScanName: () => string,
getScanName: () => string,
/**
* Returns whether this entry provides the query/mutation with the specified name
* @param name
*/
providesQuery: (name: string) => boolean
}
export const createEntryProps = (props): IEntryProps => {
const entryProps = {
createEntryFields: () => {
const fields = Object.keys(props.data).reduce((result, key)=> {
result[key] = {type: props.data[key]};
return result;
}, {});
if (props.primaryKey) {
fields[props.primaryKey] = {type: GraphQLString};
}
if (props.rangeKey) {
fields[props.rangeKey] = {type: GraphQLString};
}
return fields;
},
createEntryType: (prefix) => {
return new GraphQLObjectType({
name: prefix + props.id,
fields: () => entryProps.createEntryFields()
})
},
createKeyArgs: () => {
const args = {};
if (props.primaryKey) {
args[props.primaryKey] = {name: props.primaryKey, type: GraphQLString};
}
if (props.rangeKey) {
args[props.rangeKey] = {name: props.rangeKey, type: GraphQLString};
}
return args;
},
createEntryArgs: () => {
const args = Object.keys(props.data).reduce((result, key)=> {
result[key] = {name: key, type: GraphQLString};
return result;
}, {});
if (props.primaryKey) {
args[props.primaryKey] = {name: props.primaryKey, type: GraphQLString};
}
if (props.rangeKey) {
args[props.rangeKey] = {name: props.rangeKey, type: GraphQLString};
}
return args;
},
getEntryListQuery: (dictKey) => {
const fields = entryProps.createEntryFields();
//console.log("fields: ", fields);
return getEntryListQuery(
props.id,
dictKey,
fields
);
},
getEntryQuery: (dictKey) => {
const fields = entryProps.createEntryFields();
//console.log("fields: ", fields);
return getEntryQuery(
props.id,
dictKey,
fields
);
},
getEntryScanQuery: (dictKey) => {
const fields = entryProps.createEntryFields();
//console.log("fields: ", fields);
return getEntryScanQuery(
props.id,
dictKey,
fields
);
},
setEntryMutation: (values) => {
const fields = entryProps.createEntryFields();
//console.log("fields: ", fields);
return setEntryMutation(
props.id,
values,
fields
);
},
setEntry: (args, context, tableName, isOffline) => {
//console.log("setEntry: ", args, "offline: ", isOffline);
return setEntry(
tableName, //"code-architect-dev-data-layer",
props.primaryKey, // schema.Entry.ENTITY, //pkEntity
args[props.primaryKey], // pkId
props.rangeKey, //schema.Data.ENTITY, // skEntity
args[props.rangeKey], // skId
Object.keys(args).reduce((result, key) => {
if (Object.keys(props.data).find(datakey => datakey === key) !== undefined) {
result[key] = args[key];
}
return result;
}, {}), // jsonData
isOffline // do we run offline?
);
},
listEntries: (args, context, tableName, key, isOffline) => {
const entity = key === "pk" ? props.primaryKey : props.rangeKey;
const range = key === "pk" ? props.rangeKey : props.primaryKey;
//console.log("listEntries: offline? ", isOffline)
return ddbListEntries(
tableName, //tablename
key, // key
entity, //entity
args[entity], //value
range, //rangeEntity
isOffline
).then(results => {
//console.log("promised: ", results);
return results.map(item => {
const data = item.jsonData !== undefined ? JSON.parse(item.jsonData) : {};
data[props.primaryKey] = item.pk.substring(item.pk.indexOf("|") + 1);
data[props.rangeKey] = item.sk.substring(item.sk.indexOf("|") + 1);
return data;
});
});
},
getEntry: (args, context, tableName, isOffline) => {
return ddbGetEntry(
tableName, //tablename
props.primaryKey, // pkEntity,
args[props.primaryKey], // pkValue,
props.rangeKey, // skEntity,
args[props.rangeKey], // skValue
isOffline
).then((result: any)=> {
//console.log("entry-component getEntry result: ", result);
const data = result.jsonData !== undefined ? JSON.parse(result.jsonData) : {};
if (result && result.pk && result.sk) {
data[props.primaryKey] = result.pk.substring(result.pk.indexOf("|") + 1);
data[props.rangeKey] = result.sk.substring(result.sk.indexOf("|") + 1);
}
return data;
});
},
scan: (args, context, tableName, key, isOffline) => {
//console.log("scan entry! ", args, "offline: ", isOffline)
return ddbScan(
tableName, //tablename
key, // key
key === "pk" ? props.primaryKey : props.rangeKey, // pkEntity,
args.scanall ? undefined : args[`start_${key === "pk" ? props.primaryKey : props.rangeKey}`], // start_value,
args.scanall ? undefined : args[`end_${key === "pk" ? props.primaryKey : props.rangeKey}`], // end_Value,
key === "pk" ? props.rangeKey : props.primaryKey, // skEntity,
isOffline
).then((result: any)=> {
//console.log("entry-component scan result: ", result);
return result.map(entry => {
//console.log("scanned entry: ", entry);
const data = entry.jsonData !== undefined ? JSON.parse(entry.jsonData) : {};
if (entry && entry.pk && entry.sk) {
data[props.primaryKey] = entry.pk.substring(entry.pk.indexOf("|") + 1);
data[props.rangeKey] = entry.sk.substring(entry.sk.indexOf("|") + 1);
}
//console.log("returned data: ", data);
return data;
});
});
},
deleteEntryMutation: (values) => {
const fields = entryProps.createEntryFields();
//const fields = entryProps.createEntryFields();
//console.log("fields: ", fields);
return deleteEntryMutation(
props.id,
values,
fields
);
},
deleteEntry: (args, context, tableName, isOffline) => {
return deleteEntry(
tableName, //"code-architect-dev-data-layer",
props.primaryKey, // schema.Entry.ENTITY, //pkEntity
args[props.primaryKey], // pkId
props.rangeKey, //schema.Data.ENTITY, // skEntity
args[props.rangeKey], // skId
isOffline
);
},
middleware: createMiddleware({ callback: (req, res, next) => {
//console.log("this is the mw of the entry: ", props.id)
return next();
}}),
getPrimaryListQueryName: () => "list_"+props.id+"_"+props.primaryKey,
getRangeListQueryName: () => "list_"+props.id+"_"+props.rangeKey,
getGetQueryName: () => "get_"+props.id,
getSetMutationName: () => "set_"+props.id,
getDeleteMutationName: () => "delete_"+props.id,
getPrimaryScanName: () => "scan_"+props.id+"_"+props.primaryKey,
getRangeScanName: () => "scan_"+props.id+"_"+props.rangeKey,
getScanName: () => "scan_"+props.id,
/**
* Returns whether this entry provides the query/mutation with the specified name
* @param name
*/
providesQuery: (name: string) => {
const result = name === entryProps.getPrimaryListQueryName() ||
name === entryProps.getRangeListQueryName() ||
name === entryProps.getSetMutationName() ||
name === entryProps.getDeleteMutationName() ||
name === entryProps.getPrimaryScanName() ||
name === entryProps.getRangeScanName() ||
name === entryProps.getScanName()
;
//console.log("does ", props.id , " provide ", name, "? ", result)
return result;
}
};
return Object.assign({}, props, entryProps);
};
/**
* an entry specifies a kind of data that can be stored in a line of the table
*/
export default (props: IEntryArgs | any) => {
// the component must have the properties of IComponent
const componentProps: IInfrastructure & IComponent = {
infrastructureType: Types.INFRASTRUCTURE_TYPE_COMPONENT,
instanceType: ENTRY_INSTANCE_TYPE,
instanceId: props.id
};
return createEntryProps(Object.assign({}, props, componentProps));
};
export const isEntry = (component) => {
return component !== undefined && component.instanceType === ENTRY_INSTANCE_TYPE;
}; | the_stack |
var Validation = require('../../src/validation/Validation.js');
var Validators = require('../../src/validation/BasicValidators.js');
var Util = require('../../src/validation/Utils.js');
var expect = require('expect.js');
var _:UnderscoreStatic = require('underscore');
import Q = require('q');
import dateCompareValidator = require('../../src/customValidators/DateCompareValidator');
import moment = require('moment')
interface IPerson{
Checked:boolean;
FirstName:string;
LastName:string;
BirthDate:Date;
Job:string;
}
describe('localization of error messages', function () {
var defaultMessages = {
"required": "This field is required.",
"maxlength": "Please enter no more than {MaxLength} characters.",
"contains": "Please enter a value from list of values. Attempted value '{AttemptedValue}'.",
"custom":"Please, fix the field."
};
describe('simple property validators', function () {
beforeEach(function () {
//setup
this.Data = {};
this.PersonValidator = personValidator.CreateRule("Person");
this.Messages = defaultMessages;
});
//create new validator for object with structure<IPerson>
var personValidator = new Validation.AbstractValidator<IPerson>();
//basic validators
var required = new Validators.RequiredValidator();
var maxLength = new Validators.MaxLengthValidator(15);
var lowerOrEqualThanToday = new dateCompareValidator();
lowerOrEqualThanToday.CompareTo = new Date();
lowerOrEqualThanToday.CompareOperator = Validation.CompareOperator.LessThanEqual;
//assigned validators to property
personValidator.RuleFor("FirstName", required);
personValidator.RuleFor("FirstName", maxLength);
//assigned validators to property
personValidator.RuleFor("LastName", required);
personValidator.RuleFor("LastName", maxLength);
it('en errors - default', function () {
//when
this.Data.FirstName = "";
this.Data.LastName = "Smith toooooooooooooooooooooooooooooooo long";
//excercise
var result = this.PersonValidator.Validate(this.Data);
//verify
expect(result.Errors["FirstName"].ValidationFailures["required"].ErrorMessage).to.equal(this.Messages["required"]);
expect(result.Errors["LastName"].ValidationFailures["maxlength"].ErrorMessage).to.equal(Util.StringFce.format(this.Messages["maxlength"],{MaxLength:15}));
});
it('cz errors', function () {
//when
this.Data.FirstName = "";
this.Data.LastName = "Smith toooooooooooooooooooooooooooooooo long";
_.extend(this.Messages, {
required: "Tento údaj je povinný.",
maxlength: "Prosím, zadejte nejvíce {MaxLength} znaků."
});
//excercise
var result = this.PersonValidator.Validate(this.Data);
//verify
expect(Util.StringFce.format(this.Messages["required"],result.Errors["FirstName"].ValidationFailures["required"].TranslateArgs.MessageArgs))
.to.equal(this.Messages["required"]);
expect(Util.StringFce.format(this.Messages["maxlength"],result.Errors["LastName"].ValidationFailures["maxlength"].TranslateArgs.MessageArgs))
.to.equal(Util.StringFce.format(this.Messages["maxlength"],{MaxLength:15}));
});
});
describe('simple async validators', function () {
beforeEach(function () {
//setup
this.Data = {};
this.PersonValidator = personValidator.CreateRule("Person");
this.Messages = defaultMessages;
});
//create new validator for object with structure<IPerson>
var personValidator = new Validation.AbstractValidator<IPerson>();
//async functions return list of values
var optionsFce = function () {
var deferral = Q.defer();
setTimeout(function () {
deferral.resolve([
"business man",
"unemployed",
"construction worker",
"programmer",
"shop assistant"
]);
}, 1000);
return deferral.promise;
};
//async basic validators - return true if specified param contains any value
var param = new Validators.ContainsValidator();
param.Options = optionsFce();
//assigned validator to property
personValidator.RuleFor("Job", param);
it('en errors - default', function (done) {
//when
this.Data.Job = "unknow job";
//excercise
var promiseResult = this.PersonValidator.ValidateAsync(this.Data);
var expectedMsg = this.Messages["contains"];
promiseResult.then(function (response) {
//verify
expect(response.Errors["Job"].ValidationFailures["contains"].ErrorMessage).to.equal(Util.StringFce.format(expectedMsg,{AttemptedValue:"unknow job"}));
done();
}).done(null, done);
});
it('cz errors', function (done) {
//when
this.Data.Job = "unknow job";
_.extend(this.Messages, {
contains: "Prosím, zadejte hodnotu ze seznamu. Zadaná hodnota {AttemptedValue}."
});
//excercise
var promiseResult = this.PersonValidator.ValidateAsync(this.Data);
var expectedMsg = this.Messages["contains"];
promiseResult.then(function (response) {
//verify
expect(Util.StringFce.format(expectedMsg,response.Errors["Job"].ValidationFailures["contains"].TranslateArgs.MessageArgs))
.to.equal(Util.StringFce.format(expectedMsg,{AttemptedValue:"unknow job"}));
done();
}).done(null, done);
});
});
describe('shared validators', function () {
beforeEach(function () {
//setup
this.Data = {};
this.PersonValidator = personValidator.CreateRule("Person");
this.Messages = defaultMessages;
});
//create new validator for object with structure<IPerson>
var personValidator = new Validation.AbstractValidator<IPerson>();
//shared validation function
var oneSpaceFce = function (args:any) {
args.HasError = false;
if (!this.Checked) return;
if (this.FirstName.indexOf(' ') != -1 || this.LastName.indexOf(' ') != -1) {
args.HasError = true;
args.TranslateArgs = {TranslateId:'FullNameOneSpace',MessageArgs:{AttemptedValue: this.FirstName + " " + this.LastName}};
args.ErrorMessage = Util.StringFce.format("Full name can contain only one space. Attempted full name:'{AttemptedValue}'.",args.TranslateArgs.MessageArgs);
}
};
//create named validation function
var validatorFce = {Name: "OneSpaceForbidden", ValidationFce: oneSpaceFce};
//assign validation function to properties
personValidator.ValidationFor("FirstName", validatorFce);
personValidator.ValidationFor("LastName", validatorFce);
it('en error - default', function () {
//when
this.Data.Checked = true;
this.Data.FirstName = "John Junior";
this.Data.LastName = "Smith";
//excercise
var result = this.PersonValidator.Validate(this.Data);
//verify
expect(this.PersonValidator.ValidationResult.ErrorMessage).
to.equal(Util.StringFce.format("Full name can contain only one space. Attempted full name:'{AttemptedValue}'.", { AttemptedValue: "John Junior Smith" }));
});
it('cz error messsage', function () {
//when
this.Data.Checked = true;
this.Data.FirstName = "John Junior";
this.Data.LastName = "Smith";
_.extend(this.Messages, {
FullNameOneSpace: "Celé jméno může obsahovat pouze jednu mezeru. Zadané celé jméno: '{AttemptedValue}'."
});
//excercise
var result = this.PersonValidator.Validate(this.Data);
//verify
expect(Util.StringFce.format(this.Messages["FullNameOneSpace"],this.PersonValidator.Validators["OneSpaceForbidden"].TranslateArgs[0].MessageArgs))
.to.equal(Util.StringFce.format(this.Messages["FullNameOneSpace"], { AttemptedValue: "John Junior Smith" }));
});
});
describe('custom property validators', function () {
beforeEach(function () {
//setup
this.Data = {};
this.PersonValidator = personValidator.CreateRule("Person");
this.Messages = defaultMessages;
});
//create new validator for object with structure<IPerson>
var personValidator = new Validation.AbstractValidator();
//basic validators
var required = new Validators.RequiredValidator();
var lowerOrEqualThanToday = new dateCompareValidator();
lowerOrEqualThanToday.CompareTo = new Date();
lowerOrEqualThanToday.CompareOperator = Validation.CompareOperator.LessThanEqual;
//assigned custom validators to property
personValidator.RuleFor("BirthDate", required);
personValidator.RuleFor("BirthDate", lowerOrEqualThanToday);
//custom error message function
var customErrorMessage = function (config, args) {
var msg = '';
var messages = config;
var format = messages["Format"];
if (format != undefined) {
_.extend(args, {
FormatedCompareTo: moment(args.CompareTo).format(format),
FormatedAttemptedValue: moment(args.AttemptedValue).format(format)
});
}
switch (args.CompareOperator) {
case Validation.CompareOperator.LessThan:
msg = messages["LessThan"];
break;
case Validation.CompareOperator.LessThanEqual:
msg = messages["LessThanEqual"];
break;
case Validation.CompareOperator.Equal:
msg = messages["Equal"];
break;
case Validation.CompareOperator.NotEqual:
msg = messages["NotEqual"];
break;
case Validation.CompareOperator.GreaterThanEqual:
msg = messages["GreaterThanEqual"];
break;
case Validation.CompareOperator.GreaterThan:
msg = messages["GreaterThan"];
break;
}
msg = msg.replace('CompareTo', 'FormatedCompareTo');
msg = msg.replace('AttemptedValue', 'FormatedAttemptedValue');
return Util.StringFce.format(msg, args);
};
it('en errors - default', function () {
//when
//future birth day is not possible
this.Data.BirthDate = moment(new Date()).add({ days: 1 }).toDate();
//excercise
var result = this.PersonValidator.Validate(this.Data);
//verify
expect(result.Errors["BirthDate"].ValidationFailures["dateCompare"].ErrorMessage).to.equal(this.Messages["custom"]);
});
it('en errors - custom', function () {
//when
//future birth day is not possible
this.Data.BirthDate = moment(new Date()).add({ days: 1 }).toDate();
//add english messages
_.extend(this.Messages, {
"dateCompare": {
Format: "MM/DD/YYYY",
LessThan: "Please enter date less than {CompareTo}.",
LessThanEqual: "Please enter date less than or equal {CompareTo}.",
Equal: "Please enter date equal {CompareTo}.",
NotEqual: "Please enter date different than {CompareTo}.",
GreaterThanEqual: "Please enter date greater than or equal {CompareTo}.",
GreaterThan: "Please enter date greter than {CompareTo}."
}
});
//excercise
var result = this.PersonValidator.Validate(this.Data);
//verify
var expectedMsg = Util.StringFce.format(this.Messages["dateCompare"]["LessThanEqual"],
{
CompareTo: moment(new Date()).format(this.Messages["dateCompare"]["Format"]),
AttemptedValue: moment(this.Data.BirthDate).format(this.Messages["dateCompare"]["Format"])
});
expect(customErrorMessage(this.Messages["dateCompare"],result.Errors["BirthDate"].ValidationFailures["dateCompare"].TranslateArgs.MessageArgs))
.to.equal(expectedMsg);
});
it('cz errors', function () {
//when
//future birth day is not possible
this.Data.BirthDate = moment(new Date()).add({ days: 1 }).toDate();
_.extend(this.Messages, {
required: "Tento údaj je povinný.",
maxlength: "Prosím, zadejte nejvíce {MaxLength} znaků.",
dateCompare: {
Format: "DD.MM.YYYY",
LessThan: "Prosím, zadejte datum menší než {CompareTo}.",
LessThanEqual: "Prosím, zadejte datum menší nebo rovné {CompareTo}.",
Equal: "Prosím, zadejte {CompareTo}.",
NotEqual: "Prosím, zadejte datum různé od {CompareTo}.",
GreaterThanEqual: "Prosím, zadejte datum větší nebo rovné {CompareTo}.",
GreaterThan: "Prosím, zadejte datum větší než {CompareTo}."
}
});
//excercise
var result = this.PersonValidator.Validate(this.Data);
//verify
var expectedMsg = Util.StringFce.format(this.Messages["dateCompare"]["LessThanEqual"],
{
CompareTo: moment(new Date()).format(this.Messages["dateCompare"]["Format"]),
AttemptedValue: moment(this.Data.BirthDate).format(this.Messages["dateCompare"]["Format"])
});
expect(customErrorMessage(this.Messages["dateCompare"],result.Errors["BirthDate"].ValidationFailures["dateCompare"].TranslateArgs.MessageArgs))
.to.equal(expectedMsg);
});
});
}); | the_stack |
import {
AEventDispatcher,
debounce,
ISequence,
OrderedSet,
IDebounceContext,
IEventListener,
suffix,
IEventContext,
} from '../internal';
import {
Column,
IColumnConstructor,
Ranking,
AggregateGroupColumn,
createAggregateDesc,
IAggregateGroupColumnDesc,
isSupportType,
EDirtyReason,
RankColumn,
createRankDesc,
createSelectionDesc,
IColumnDesc,
IDataRow,
IGroup,
IndicesArray,
IOrderedGroup,
ISelectionColumnDesc,
EAggregationState,
IColumnDump,
IRankingDump,
IColorMappingFunctionConstructor,
IMappingFunctionConstructor,
ITypeFactory,
} from '../model';
import { models } from '../model/models';
import { forEachIndices, everyIndices, toGroupID, unifyParents } from '../model/internal';
import { IDataProvider, IDataProviderDump, IDataProviderOptions, SCHEMA_REF, IExportOptions } from './interfaces';
import { exportRanking, map2Object, object2Map, exportTable, isPromiseLike } from './utils';
import type { IRenderTasks } from '../renderer';
import { restoreCategoricalColorMapping } from '../model/CategoricalColorMappingFunction';
import { createColorMappingFunction, colorMappingFunctions } from '../model/ColorMappingFunction';
import { createMappingFunction, mappingFunctions } from '../model/MappingFunction';
import { convertAggregationState } from './internal';
/**
* emitted when a column has been added
* @asMemberOf ADataProvider
* @event
*/
export declare function addColumn(col: Column, index: number): void;
/**
* emitted when a column has been moved within this composite column
* @asMemberOf ADataProvider
* @event
*/
export declare function moveColumn(col: Column, index: number, oldIndex: number): void;
/**
* emitted when a column has been removed
* @asMemberOf ADataProvider
* @event
*/
export declare function removeColumn(col: Column, index: number): void;
/**
* @asMemberOf ADataProvider
* @event
*/
export declare function orderChanged(
previous: number[],
current: number[],
previousGroups: IOrderedGroup[],
currentGroups: IOrderedGroup[],
dirtyReason: EDirtyReason[]
): void;
/**
* emitted when state of the column is dirty
* @asMemberOf ADataProvider
* @event
*/
export declare function dirty(): void;
/**
* emitted when state of the column related to its header is dirty
* @asMemberOf ADataProvider
* @event
*/
export declare function dirtyHeader(): void;
/**
* emitted when state of the column related to its values is dirty
* @asMemberOf ADataProvider
* @event
*/
export declare function dirtyValues(): void;
/**
* emitted when state of the column related to cached values (hist, compare, ...) is dirty
* @asMemberOf ADataProvider
* @event
*/
export declare function dirtyCaches(): void;
/**
* emitted when the data changes
* @asMemberOf ADataProvider
* @param rows the new data rows
* @event
*/
export declare function dataChanged(rows: IDataRow[]): void;
/**
* emitted when the selection changes
* @asMemberOf ADataProvider
* @param dataIndices the selected data indices
* @event
*/
export declare function selectionChanged(dataIndices: number[]): void;
/**
* @asMemberOf ADataProvider
* @event
*/
export declare function addRanking(ranking: Ranking, index: number): void;
/**
* @asMemberOf ADataProvider
* @param ranking if null all rankings are removed else just the specific one
* @event
*/
export declare function removeRanking(ranking: Ranking | null, index: number): void;
/**
* @asMemberOf ADataProvider
* @event
*/
export declare function addDesc(desc: IColumnDesc): void;
/**
* @asMemberOf ADataProvider
* @event
*/
export declare function removeDesc(desc: IColumnDesc): void;
/**
* @asMemberOf ADataProvider
* @event
*/
export declare function clearDesc(): void;
/**
* @asMemberOf ADataProvider
* @event
*/
export declare function showTopNChanged(previous: number, current: number): void;
/**
* emitted when the selection changes
* @asMemberOf ADataProvider
* @param dataIndices the selected data indices
* @event
*/
export declare function jumpToNearest(dataIndices: number[]): void;
/**
* @asMemberOf ADataProvider
* @event
*/
export declare function aggregate(
ranking: Ranking,
group: IGroup | IGroup[],
previousTopN: number | number[],
currentTopN: number | number[]
): void;
/**
* @asMemberOf ADataProvider
* @event
*/
export declare function busy(busy: boolean): void;
function toDirtyReason(ctx: IEventContext) {
const primary = ctx.primaryType;
switch (primary || '') {
case Ranking.EVENT_DIRTY_ORDER:
return ctx.args[0] || [EDirtyReason.UNKNOWN];
case Ranking.EVENT_SORT_CRITERIA_CHANGED:
return [EDirtyReason.SORT_CRITERIA_CHANGED];
case Ranking.EVENT_GROUP_CRITERIA_CHANGED:
return [EDirtyReason.GROUP_CRITERIA_CHANGED];
case Ranking.EVENT_GROUP_SORT_CRITERIA_CHANGED:
return [EDirtyReason.GROUP_SORT_CRITERIA_CHANGED];
default:
return [EDirtyReason.UNKNOWN];
}
}
function mergeDirtyOrderContext(current: IDebounceContext, next: IDebounceContext) {
const currentReason = toDirtyReason(current.self);
const nextReason = toDirtyReason(next.self);
const combined = new Set(currentReason);
for (const r of nextReason) {
combined.add(r);
}
const args = [Array.from(combined)];
return {
self: {
primaryType: Ranking.EVENT_DIRTY_ORDER,
args,
},
args,
};
}
/**
* a basic data provider holding the data and rankings
*/
abstract class ADataProvider extends AEventDispatcher implements IDataProvider {
static readonly EVENT_SELECTION_CHANGED = 'selectionChanged';
static readonly EVENT_DATA_CHANGED = 'dataChanged';
static readonly EVENT_ADD_COLUMN = Ranking.EVENT_ADD_COLUMN;
static readonly EVENT_MOVE_COLUMN = Ranking.EVENT_MOVE_COLUMN;
static readonly EVENT_REMOVE_COLUMN = Ranking.EVENT_REMOVE_COLUMN;
static readonly EVENT_ADD_RANKING = 'addRanking';
static readonly EVENT_REMOVE_RANKING = 'removeRanking';
static readonly EVENT_DIRTY = Ranking.EVENT_DIRTY;
static readonly EVENT_DIRTY_HEADER = Ranking.EVENT_DIRTY_HEADER;
static readonly EVENT_DIRTY_VALUES = Ranking.EVENT_DIRTY_VALUES;
static readonly EVENT_DIRTY_CACHES = Ranking.EVENT_DIRTY_CACHES;
static readonly EVENT_ORDER_CHANGED = Ranking.EVENT_ORDER_CHANGED;
static readonly EVENT_SHOWTOPN_CHANGED = 'showTopNChanged';
static readonly EVENT_ADD_DESC = 'addDesc';
static readonly EVENT_CLEAR_DESC = 'clearDesc';
static readonly EVENT_REMOVE_DESC = 'removeDesc';
static readonly EVENT_JUMP_TO_NEAREST = 'jumpToNearest';
static readonly EVENT_GROUP_AGGREGATION_CHANGED = AggregateGroupColumn.EVENT_AGGREGATE;
static readonly EVENT_BUSY = 'busy';
private static readonly FORWARD_RANKING_EVENTS = suffix(
'.provider',
Ranking.EVENT_ADD_COLUMN,
Ranking.EVENT_REMOVE_COLUMN,
Ranking.EVENT_DIRTY,
Ranking.EVENT_DIRTY_HEADER,
Ranking.EVENT_MOVE_COLUMN,
Ranking.EVENT_ORDER_CHANGED,
Ranking.EVENT_DIRTY_VALUES,
Ranking.EVENT_DIRTY_CACHES
);
/**
* all rankings
* @type {Array}
* @private
*/
private readonly rankings: Ranking[] = [];
/**
* the current selected indices
* @type {OrderedSet}
*/
private readonly selection = new OrderedSet<number>();
//Map<ranking.id@group.name, -1=expand,0=collapse,N=topN>
private readonly aggregations = new Map<string, number>(); // not part of = show all
private uid = 0;
private readonly typeFactory: ITypeFactory;
private readonly options: Readonly<IDataProviderOptions> = {
columnTypes: {},
colorMappingFunctionTypes: {},
mappingFunctionTypes: {},
singleSelection: false,
showTopN: 10,
aggregationStrategy: 'item',
propagateAggregationState: true,
};
/**
* lookup map of a column type to its column implementation
*/
readonly columnTypes: { [columnType: string]: IColumnConstructor };
readonly colorMappingFunctionTypes: { [colorMappingFunctionType: string]: IColorMappingFunctionConstructor };
readonly mappingFunctionTypes: { [mappingFunctionType: string]: IMappingFunctionConstructor };
private showTopN: number;
constructor(options: Partial<IDataProviderOptions> = {}) {
super();
Object.assign(this.options, options);
this.columnTypes = Object.assign(models(), this.options.columnTypes);
this.colorMappingFunctionTypes = Object.assign(colorMappingFunctions(), this.options.colorMappingFunctionTypes);
this.mappingFunctionTypes = Object.assign(mappingFunctions(), this.options.mappingFunctionTypes);
this.showTopN = this.options.showTopN;
this.typeFactory = this.createTypeFactory();
}
private createTypeFactory() {
const factory = ((d: IColumnDump) => {
const desc = this.fromDescRef(d.desc);
if (!desc || !desc.type) {
console.warn('cannot restore column dump', d);
return new Column(d.id || '', d.desc || {});
}
this.fixDesc(desc);
const type = this.columnTypes[desc.type];
if (type == null) {
console.warn('invalid column type in column dump using column', d);
return new Column(d.id || '', desc);
}
const c = this.instantiateColumn(type, '', desc, this.typeFactory);
c.restore(d, factory);
return c;
}) as ITypeFactory;
factory.colorMappingFunction = createColorMappingFunction(this.colorMappingFunctionTypes, factory);
factory.mappingFunction = createMappingFunction(this.mappingFunctionTypes);
factory.categoricalColorMappingFunction = restoreCategoricalColorMapping;
return factory;
}
getTypeFactory() {
return this.typeFactory;
}
/**
* events:
* * column changes: addColumn, removeColumn
* * ranking changes: addRanking, removeRanking
* * dirty: dirty, dirtyHeder, dirtyValues
* * selectionChanged
* @returns {string[]}
*/
protected createEventList() {
return super
.createEventList()
.concat([
ADataProvider.EVENT_DATA_CHANGED,
ADataProvider.EVENT_BUSY,
ADataProvider.EVENT_SHOWTOPN_CHANGED,
ADataProvider.EVENT_ADD_COLUMN,
ADataProvider.EVENT_REMOVE_COLUMN,
ADataProvider.EVENT_MOVE_COLUMN,
ADataProvider.EVENT_ADD_RANKING,
ADataProvider.EVENT_REMOVE_RANKING,
ADataProvider.EVENT_DIRTY,
ADataProvider.EVENT_DIRTY_HEADER,
ADataProvider.EVENT_DIRTY_VALUES,
ADataProvider.EVENT_DIRTY_CACHES,
ADataProvider.EVENT_ORDER_CHANGED,
ADataProvider.EVENT_SELECTION_CHANGED,
ADataProvider.EVENT_ADD_DESC,
ADataProvider.EVENT_CLEAR_DESC,
ADataProvider.EVENT_JUMP_TO_NEAREST,
ADataProvider.EVENT_GROUP_AGGREGATION_CHANGED,
]);
}
on(type: typeof ADataProvider.EVENT_BUSY, listener: typeof busy | null): this;
on(type: typeof ADataProvider.EVENT_DATA_CHANGED, listener: typeof dataChanged | null): this;
on(type: typeof ADataProvider.EVENT_SHOWTOPN_CHANGED, listener: typeof showTopNChanged | null): this;
on(type: typeof ADataProvider.EVENT_ADD_COLUMN, listener: typeof addColumn | null): this;
on(type: typeof ADataProvider.EVENT_MOVE_COLUMN, listener: typeof moveColumn | null): this;
on(type: typeof ADataProvider.EVENT_REMOVE_COLUMN, listener: typeof removeColumn | null): this;
on(type: typeof ADataProvider.EVENT_ADD_RANKING, listener: typeof addRanking | null): this;
on(type: typeof ADataProvider.EVENT_REMOVE_RANKING, listener: typeof removeRanking | null): this;
on(type: typeof ADataProvider.EVENT_DIRTY, listener: typeof dirty | null): this;
on(type: typeof ADataProvider.EVENT_DIRTY_HEADER, listener: typeof dirtyHeader | null): this;
on(type: typeof ADataProvider.EVENT_DIRTY_VALUES, listener: typeof dirtyValues | null): this;
on(type: typeof ADataProvider.EVENT_DIRTY_CACHES, listener: typeof dirtyCaches | null): this;
on(type: typeof ADataProvider.EVENT_ORDER_CHANGED, listener: typeof orderChanged | null): this;
on(type: typeof ADataProvider.EVENT_ADD_DESC, listener: typeof addDesc | null): this;
on(type: typeof ADataProvider.EVENT_REMOVE_DESC, listener: typeof removeDesc | null): this;
on(type: typeof ADataProvider.EVENT_CLEAR_DESC, listener: typeof clearDesc | null): this;
on(type: typeof ADataProvider.EVENT_JUMP_TO_NEAREST, listener: typeof jumpToNearest | null): this;
on(type: typeof ADataProvider.EVENT_GROUP_AGGREGATION_CHANGED, listener: typeof aggregate | null): this;
on(type: typeof ADataProvider.EVENT_SELECTION_CHANGED, listener: typeof selectionChanged | null): this;
on(type: string | string[], listener: IEventListener | null): this; // required for correct typings in *.d.ts
on(type: string | string[], listener: IEventListener | null): this {
return super.on(type, listener);
}
abstract getTotalNumberOfRows(): number;
/**
* returns a list of all known column descriptions
* @returns {Array}
*/
abstract getColumns(): IColumnDesc[];
abstract getTaskExecutor(): IRenderTasks;
/**
* adds a new ranking
* @param existing an optional existing ranking to clone
* @return the new ranking
*/
pushRanking(existing?: Ranking): Ranking {
const r = this.cloneRanking(existing);
this.insertRanking(r);
return r;
}
protected fireBusy(busy: boolean) {
this.fire(ADataProvider.EVENT_BUSY, busy);
}
takeSnapshot(col: Column): Ranking {
this.fireBusy(true);
const r = this.cloneRanking();
const ranking = col.findMyRanker();
// by convention copy all support types and the first string column
let hasString = col.desc.type === 'string';
let hasColumn = false;
const toClone = !ranking
? [col]
: ranking.children.filter((c) => {
if (c === col) {
hasColumn = true;
return true;
}
if (!hasString && c.desc.type === 'string') {
hasString = true;
return true;
}
return isSupportType(c);
});
if (!hasColumn) {
// maybe a nested one thus not in the top level
toClone.push(col);
}
toClone.forEach((c) => {
const clone = this.clone(c);
r.push(clone);
if (c === col) {
clone.sortByMe();
}
});
this.insertRanking(r);
this.fireBusy(false);
return r;
}
insertRanking(r: Ranking, index = this.rankings.length) {
this.rankings.splice(index, 0, r);
this.forward(r, ...ADataProvider.FORWARD_RANKING_EVENTS);
//delayed reordering per ranking
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
r.on(
`${Ranking.EVENT_DIRTY_ORDER}.provider`,
debounce(
function (this: IEventContext) {
that.triggerReorder(r, toDirtyReason(this));
},
100,
mergeDirtyOrderContext
)
);
this.fire(
[
ADataProvider.EVENT_ADD_RANKING,
ADataProvider.EVENT_DIRTY_HEADER,
ADataProvider.EVENT_DIRTY_VALUES,
ADataProvider.EVENT_DIRTY,
],
r,
index
);
this.triggerReorder(r);
}
private triggerReorder(ranking: Ranking, dirtyReason?: EDirtyReason[]) {
this.fireBusy(true);
const reason = dirtyReason || [EDirtyReason.UNKNOWN];
Promise.resolve(this.sort(ranking, reason)).then(({ groups, index2pos }) => {
if (ranking.getGroupSortCriteria().length === 0) {
groups = unifyParents(groups);
}
this.initAggregateState(ranking, groups);
ranking.setGroups(groups, index2pos, reason);
this.fireBusy(false);
});
}
/**
* removes a ranking from this data provider
* @param ranking
* @returns {boolean}
*/
removeRanking(ranking: Ranking) {
const i = this.rankings.indexOf(ranking);
if (i < 0) {
return false;
}
this.unforward(ranking, ...ADataProvider.FORWARD_RANKING_EVENTS);
this.rankings.splice(i, 1);
ranking.on(`${Ranking.EVENT_DIRTY_ORDER}.provider`, null);
this.cleanUpRanking(ranking);
this.fire(
[
ADataProvider.EVENT_REMOVE_RANKING,
ADataProvider.EVENT_DIRTY_HEADER,
ADataProvider.EVENT_DIRTY_VALUES,
ADataProvider.EVENT_DIRTY,
],
ranking,
i
);
return true;
}
/**
* removes all rankings
*/
clearRankings() {
this.rankings.forEach((ranking) => {
this.unforward(ranking, ...ADataProvider.FORWARD_RANKING_EVENTS);
ranking.on(`${Ranking.EVENT_DIRTY_ORDER}.provider`, null);
this.cleanUpRanking(ranking);
});
// clear
this.rankings.splice(0, this.rankings.length);
this.fire(
[
ADataProvider.EVENT_REMOVE_RANKING,
ADataProvider.EVENT_DIRTY_HEADER,
ADataProvider.EVENT_DIRTY_VALUES,
ADataProvider.EVENT_DIRTY,
],
null,
-1
);
}
clearFilters() {
this.rankings.forEach((ranking) => ranking.clearFilters());
}
/**
* returns a list of all current rankings
* @returns {Ranking[]}
*/
getRankings() {
return this.rankings.slice();
}
/**
* returns the last ranking for quicker access
* @returns {Ranking}
*/
getFirstRanking() {
return this.rankings[0] || null;
}
/**
* returns the last ranking for quicker access
* @returns {Ranking}
*/
getLastRanking() {
return this.rankings[this.rankings.length - 1];
}
ensureOneRanking() {
if (this.rankings.length === 0) {
const r = this.pushRanking();
this.push(r, createRankDesc());
}
}
destroy() {
// dummy
}
/**
* hook method for cleaning up a ranking
* @param _ranking
*/
cleanUpRanking(_ranking: Ranking) {
// dummy
}
/**
* abstract method for cloning a ranking
* @param existing
* @returns {null}
*/
abstract cloneRanking(existing?: Ranking): Ranking;
/**
* adds a column to a ranking described by its column description
* @param ranking the ranking to add the column to
* @param desc the description of the column
* @return {Column} the newly created column or null
*/
push(ranking: Ranking, desc: IColumnDesc): Column | null {
const r = this.create(desc);
if (r) {
ranking.push(r);
return r;
}
return null;
}
/**
* adds a column to a ranking described by its column description
* @param ranking the ranking to add the column to
* @param index the position to insert the column
* @param desc the description of the column
* @return {Column} the newly created column or null
*/
insert(ranking: Ranking, index: number, desc: IColumnDesc) {
const r = this.create(desc);
if (r) {
ranking.insert(r, index);
return r;
}
return null;
}
/**
* creates a new unique id for a column
* @returns {string}
*/
private nextId() {
return `col${this.uid++}`;
}
private fixDesc(desc: IColumnDesc) {
//hacks for provider dependent descriptors
if (desc.type === 'selection') {
(desc as ISelectionColumnDesc).accessor = (row: IDataRow) => this.isSelected(row.i);
(desc as ISelectionColumnDesc).setter = (index: number, value: boolean) =>
value ? this.select(index) : this.deselect(index);
(desc as ISelectionColumnDesc).setterAll = (indices: IndicesArray, value: boolean) =>
value ? this.selectAll(indices) : this.deselectAll(indices);
} else if (desc.type === 'aggregate') {
(desc as IAggregateGroupColumnDesc).isAggregated = (ranking: Ranking, group: IGroup) =>
this.getAggregationState(ranking, group);
(desc as IAggregateGroupColumnDesc).setAggregated = (ranking: Ranking, group: IGroup, value: EAggregationState) =>
this.setAggregationState(ranking, group, value);
}
return desc;
}
protected cleanDesc(desc: IColumnDesc) {
//hacks for provider dependent descriptors
if (desc.type === 'selection') {
delete (desc as ISelectionColumnDesc).accessor;
delete (desc as ISelectionColumnDesc).setter;
delete (desc as ISelectionColumnDesc).setterAll;
} else if (desc.type === 'aggregate') {
delete (desc as IAggregateGroupColumnDesc).isAggregated;
delete (desc as IAggregateGroupColumnDesc).setAggregated;
}
return desc;
}
/**
* creates an internal column model out of the given column description
* @param desc
* @returns {Column} the new column or null if it can't be created
*/
create(desc: IColumnDesc): Column | null {
this.fixDesc(desc);
//find by type and instantiate
const type = this.columnTypes[desc.type];
if (type) {
return this.instantiateColumn(type, this.nextId(), desc, this.typeFactory);
}
return null;
}
protected instantiateColumn(type: IColumnConstructor, id: string, desc: IColumnDesc, typeFactory: ITypeFactory) {
return new type(id, desc, typeFactory);
}
/**
* clones a column by dumping and restoring
* @param col
* @returns {Column}
*/
clone(col: Column) {
const dump = this.dumpColumn(col);
return this.restoreColumn(dump);
}
/**
* restores a column from a dump
* @param dump
* @returns {Column}
*/
restoreColumn(dump: any): Column {
const c = this.typeFactory(dump);
c.assignNewId(this.nextId.bind(this));
return c;
}
/**
* finds a column in all rankings returning the first match
* @param idOrFilter by id or by a filter function
* @returns {Column}
*/
find(idOrFilter: string | ((col: Column) => boolean)): Column | null {
//convert to function
const filter = typeof idOrFilter === 'string' ? (col: Column) => col.id === idOrFilter : idOrFilter;
for (const ranking of this.rankings) {
const r = ranking.find(filter);
if (r) {
return r;
}
}
return null;
}
/**
* dumps this whole provider including selection and the rankings
* @returns {{uid: number, selection: number[], rankings: *[]}}
*/
dump(): IDataProviderDump {
return {
$schema: SCHEMA_REF,
uid: this.uid,
selection: this.getSelection(),
aggregations: map2Object(this.aggregations),
rankings: this.rankings.map((r) => r.dump(this.toDescRef.bind(this))),
showTopN: this.showTopN,
};
}
/**
* dumps a specific column
*/
dumpColumn(col: Column): IColumnDump {
return col.dump(this.toDescRef.bind(this));
}
/**
* for better dumping describe reference, by default just return the description
*/
toDescRef(desc: any): any {
return desc;
}
/**
* inverse operation of toDescRef
*/
fromDescRef(descRef: any): any {
return descRef;
}
restoreRanking(dump: IRankingDump) {
const ranking = this.cloneRanking();
ranking.restore(dump, this.typeFactory);
const idGenerator = this.nextId.bind(this);
ranking.children.forEach((c) => c.assignNewId(idGenerator));
return ranking;
}
restore(dump: IDataProviderDump) {
//clean old
this.clearRankings();
//restore selection
this.uid = dump.uid || 0;
if (dump.selection) {
dump.selection.forEach((s: number) => this.selection.add(s));
}
if (dump.showTopN != null) {
this.showTopN = dump.showTopN;
}
if (dump.aggregations) {
this.aggregations.clear();
if (Array.isArray(dump.aggregations)) {
dump.aggregations.forEach((a: string) => this.aggregations.set(a, 0));
} else {
object2Map(dump.aggregations).forEach((v, k) => this.aggregations.set(k, v));
}
}
//restore rankings
if (dump.rankings) {
dump.rankings.forEach((r: any) => {
const ranking = this.cloneRanking();
ranking.restore(r, this.typeFactory);
//if no rank column add one
if (!ranking.children.some((d) => d instanceof RankColumn)) {
ranking.insert(this.create(createRankDesc())!, 0);
}
this.insertRanking(ranking);
});
}
//assign new ids
const idGenerator = this.nextId.bind(this);
this.rankings.forEach((r) => {
r.children.forEach((c) => c.assignNewId(idGenerator));
});
}
abstract findDesc(ref: string): IColumnDesc | null;
/**
* generates a default ranking by using all column descriptions ones
*/
deriveDefault(addSupportType = true) {
const r = this.pushRanking();
if (addSupportType) {
r.push(this.create(createAggregateDesc())!);
r.push(this.create(createRankDesc())!);
if (this.options.singleSelection !== true) {
r.push(this.create(createSelectionDesc())!);
}
}
this.getColumns().forEach((col) => {
const c = this.create(col);
if (!c || isSupportType(c)) {
return;
}
r.push(c);
});
return r;
}
isAggregated(ranking: Ranking, group: IGroup) {
return this.getTopNAggregated(ranking, group) >= 0;
}
getAggregationState(ranking: Ranking, group: IGroup) {
const n = this.getTopNAggregated(ranking, group);
return n < 0 ? EAggregationState.EXPAND : n === 0 ? EAggregationState.COLLAPSE : EAggregationState.EXPAND_TOP_N;
}
setAggregated(ranking: Ranking, group: IGroup | IGroup[], value: boolean) {
return this.setAggregationState(ranking, group, value ? EAggregationState.COLLAPSE : EAggregationState.EXPAND);
}
setAggregationState(ranking: Ranking, group: IGroup | IGroup[], value: EAggregationState) {
this.setTopNAggregated(
ranking,
group,
value === EAggregationState.COLLAPSE ? 0 : value === EAggregationState.EXPAND_TOP_N ? this.showTopN : -1
);
}
getTopNAggregated(ranking: Ranking, group: IGroup) {
let g: IGroup | undefined | null = group;
while (g) {
const key = `${ranking.id}@${toGroupID(g)}`;
if (this.aggregations.has(key)) {
// propagate to leaf
const v = this.aggregations.get(key)!;
if (this.options.propagateAggregationState && group !== g) {
this.aggregations.set(`${ranking.id}@${toGroupID(group)}`, v);
}
return v;
}
g = g.parent;
}
return -1;
}
private unaggregateParents(ranking: Ranking, group: IGroup) {
let g: IGroup | undefined | null = group.parent;
let changed = false;
while (g) {
changed = this.aggregations.delete(`${ranking.id}@${toGroupID(g)}`) || changed;
g = g.parent;
}
return changed;
}
getAggregationStrategy() {
return this.options.aggregationStrategy;
}
private initAggregateState(ranking: Ranking, groups: IGroup[]) {
let initial = -1;
switch (this.getAggregationStrategy()) {
case 'group':
initial = 0;
break;
case 'item':
case 'group+item':
case 'group+item+top':
initial = -1;
break;
case 'group+top+item':
initial = this.showTopN;
break;
}
for (const group of groups) {
const key = `${ranking.id}@${toGroupID(group)}`;
if (!this.aggregations.has(key) && initial >= 0) {
this.aggregations.set(key, initial);
}
}
}
setTopNAggregated(ranking: Ranking, group: IGroup | IGroup[], value: number | number[]) {
const groups = Array.isArray(group) ? group : [group];
const changed: IGroup[] = [];
const previous: number[] = [];
let changedParents = false;
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
const target = typeof value === 'number' ? value : value[i];
changedParents = this.unaggregateParents(ranking, group) || changedParents;
const current = this.getTopNAggregated(ranking, group);
if (current === target) {
continue;
}
changed.push(group);
previous.push(current);
const key = `${ranking.id}@${toGroupID(group)}`;
if (target >= 0) {
this.aggregations.set(key, target);
} else {
this.aggregations.delete(key);
}
}
if (!changedParents && changed.length === 0) {
// no change
return;
}
if (!Array.isArray(group)) {
// single change
this.fire(
[ADataProvider.EVENT_GROUP_AGGREGATION_CHANGED, ADataProvider.EVENT_DIRTY_VALUES, ADataProvider.EVENT_DIRTY],
ranking,
group,
previous.length === 0 ? value : previous[0],
value
);
} else {
this.fire(
[ADataProvider.EVENT_GROUP_AGGREGATION_CHANGED, ADataProvider.EVENT_DIRTY_VALUES, ADataProvider.EVENT_DIRTY],
ranking,
group,
previous,
value
);
}
}
aggregateAllOf(ranking: Ranking, aggregateAll: boolean | number | EAggregationState, groups = ranking.getGroups()) {
const value = convertAggregationState(aggregateAll, this.showTopN);
this.setTopNAggregated(ranking, groups, value);
}
getShowTopN() {
return this.showTopN;
}
setShowTopN(value: number) {
if (this.showTopN === value) {
return;
}
// update entries
for (const [k, v] of Array.from(this.aggregations.entries())) {
if (v === this.showTopN) {
this.aggregations.set(k, value);
}
}
this.fire(
[ADataProvider.EVENT_SHOWTOPN_CHANGED, ADataProvider.EVENT_DIRTY_VALUES, ADataProvider.EVENT_DIRTY],
this.showTopN,
(this.showTopN = value)
);
}
/**
* sorts the given ranking and eventually return a ordering of the data items
* @param ranking
* @return {Promise<any>}
*/
abstract sort(
ranking: Ranking,
dirtyReason: EDirtyReason[]
):
| Promise<{ groups: IOrderedGroup[]; index2pos: IndicesArray }>
| { groups: IOrderedGroup[]; index2pos: IndicesArray };
/**
* returns a view in the order of the given indices
* @param indices
* @return {Promise<any>}
*/
abstract view(indices: ArrayLike<number>): Promise<any[]> | any[];
abstract getRow(index: number): Promise<IDataRow> | IDataRow;
/**
* returns a data sample used for the mapping editor
* @param col
* @return {Promise<any>}
*/
abstract mappingSample(col: Column): Promise<ISequence<number>> | ISequence<number>;
/**
* is the given row selected
* @param index
* @return {boolean}
*/
isSelected(index: number) {
return this.selection.has(index);
}
/**
* also select the given row
* @param index
*/
select(index: number) {
if (this.selection.has(index)) {
return; //no change
}
if (this.options.singleSelection === true && this.selection.size > 0) {
this.selection.clear();
}
this.selection.add(index);
this.fire(ADataProvider.EVENT_SELECTION_CHANGED, this.getSelection());
}
/**
* hook for selecting elements matching the given arguments
* @param search
* @param col
*/
abstract searchAndJump(search: string | RegExp, col: Column): void;
jumpToNearest(indices: number[]) {
if (indices.length === 0) {
return;
}
this.fire(ADataProvider.EVENT_JUMP_TO_NEAREST, indices);
}
/**
* also select all the given rows
* @param indices
*/
selectAll(indices: IndicesArray) {
if (everyIndices(indices, (i) => this.selection.has(i))) {
return; //no change
}
if (this.options.singleSelection === true) {
this.selection.clear();
if (indices.length > 0) {
this.selection.add(indices[0]);
}
} else {
forEachIndices(indices, (index) => {
this.selection.add(index);
});
}
this.fire(ADataProvider.EVENT_SELECTION_CHANGED, this.getSelection());
}
selectAllOf(ranking: Ranking) {
this.setSelection(Array.from(ranking.getOrder()));
}
/**
* set the selection to the given rows
* @param indices
*/
setSelection(indices: number[]) {
if (indices.length === 0) {
return this.clearSelection();
}
if (this.selection.size === indices.length && indices.every((i) => this.selection.has(i))) {
return; //no change
}
this.selection.clear();
this.selectAll(indices);
}
/**
* toggles the selection of the given data index
* @param index
* @param additional just this element or all
* @returns {boolean} whether the index is currently selected
*/
toggleSelection(index: number, additional = false) {
if (this.isSelected(index)) {
if (additional) {
this.deselect(index);
} else {
this.clearSelection();
}
return false;
}
if (additional) {
this.select(index);
} else {
this.setSelection([index]);
}
return true;
}
/**
* deselect the given row
* @param index
*/
deselect(index: number) {
if (!this.selection.has(index)) {
return; //no change
}
this.selection.delete(index);
this.fire(ADataProvider.EVENT_SELECTION_CHANGED, this.getSelection());
}
/**
* also select all the given rows
* @param indices
*/
deselectAll(indices: IndicesArray) {
if (everyIndices(indices, (i) => !this.selection.has(i))) {
return; //no change
}
forEachIndices(indices, (index) => {
this.selection.delete(index);
});
this.fire(ADataProvider.EVENT_SELECTION_CHANGED, this.getSelection());
}
/**
* returns a promise containing the selected rows
* @return {Promise<any[]>}
*/
selectedRows(): Promise<any[]> | any[] {
if (this.selection.size === 0) {
return [];
}
return this.view(this.getSelection());
}
/**
* returns the currently selected indices
* @returns {Array}
*/
getSelection() {
return Array.from(this.selection);
}
/**
* clears the selection
*/
clearSelection() {
if (this.selection.size === 0) {
return; //no change
}
this.selection.clear();
this.fire(ADataProvider.EVENT_SELECTION_CHANGED, [], false);
}
/**
* utility to export a ranking to a table with the given separator
* @param ranking
* @param options
* @returns {Promise<string>}
*/
exportTable(ranking: Ranking, options: Partial<IExportOptions> = {}): Promise<string> | string {
const data = this.view(ranking.getOrder());
if (isPromiseLike(data)) {
return data.then((dataImpl) => exportRanking(ranking, dataImpl, options));
}
return exportRanking(ranking, data, options);
}
/**
* utility to export the selection within the given ranking to a table with the given separator
* @param ranking
* @param options
* @returns {Promise<string>}
*/
exportSelection(options: Partial<IExportOptions> & { ranking?: Ranking } = {}): Promise<string> | string {
const selection = this.getSelection();
const ranking = options.ranking || this.getFirstRanking();
if (!ranking) {
return '';
}
const rows = selection.map((s) => this.getRow(s));
if (rows.some((row) => isPromiseLike(row))) {
return Promise.all(rows).then((data) => {
return exportTable(ranking, data, options);
});
}
return exportTable(ranking, rows as IDataRow[], options);
}
}
export default ADataProvider; | the_stack |
import {
CdmCorpusDefinition,
CdmDocumentDefinition,
resolveOptions,
importsLoadStrategy,
cdmLogCode
} from '../../internal';
import { LocalAdapter } from '../../Storage';
import { testHelper } from '../testHelper';
/**
* Testing loading imports on a cdm file
*/
// tslint:disable-next-line: max-func-body-length
describe('Cdm/ImportsTest', () => {
const testsSubpath: string = 'Cdm/Imports';
/**
* Does not fail with a missing import
*/
it('TestEntityWithMissingImport', async () => {
const expectedLogCodes = new Set<cdmLogCode>([cdmLogCode.ErrPersistFileReadFailure, cdmLogCode.WarnResolveImportFailed, cdmLogCode.WarnDocImportNotLoaded]);
const cdmCorpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestEntityWithMissingImport', undefined, false, expectedLogCodes);
const resOpt = new resolveOptions();
resOpt.importsLoadStrategy = importsLoadStrategy.load;
const doc: CdmDocumentDefinition = await cdmCorpus.fetchObjectAsync<CdmDocumentDefinition>('local:/missingImport.cdm.json', null, resOpt);
expect(doc)
.not
.toBeUndefined();
expect(doc.imports.length)
.toBe(1);
expect(doc.imports.allItems[0].corpusPath)
.toBe('missing.cdm.json');
expect((doc.imports.allItems[0]).document)
.toBeUndefined();
});
/**
* Does not fail with a missing nested import
*/
it('TestEntityWithMissingNestedImportsAsync', async () => {
const expectedLogCodes = new Set<cdmLogCode>([cdmLogCode.ErrPersistFileReadFailure, cdmLogCode.WarnResolveImportFailed, cdmLogCode.WarnDocImportNotLoaded]);
const cdmCorpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestEntityWithMissingNestedImportsAsync', undefined, false, expectedLogCodes);
const resOpt = new resolveOptions();
resOpt.importsLoadStrategy = importsLoadStrategy.load;
const doc: CdmDocumentDefinition = await cdmCorpus.fetchObjectAsync<CdmDocumentDefinition>('local:/missingNestedImport.cdm.json', null, resOpt);
expect(doc)
.not
.toBeUndefined();
expect(doc.imports.length)
.toBe(1);
const firstImport: CdmDocumentDefinition = (doc.imports.allItems[0]).document;
expect(firstImport.imports.length)
.toBe(1);
expect(firstImport.name)
.toBe('notMissing.cdm.json');
const nestedImport: CdmDocumentDefinition = (firstImport.imports.allItems[0]).document;
expect(nestedImport)
.toBeUndefined();
});
/**
* Testing loading where import is listed multiple times in different files
*/
it('TestEntityWithSameImportsAsync', async () => {
const expectedLogCodes = new Set<cdmLogCode>([cdmLogCode.ErrPersistFileReadFailure, cdmLogCode.WarnResolveImportFailed, cdmLogCode.WarnDocImportNotLoaded]);
const cdmCorpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestEntityWithSameImportsAsync', undefined, false, expectedLogCodes);
const resOpt = new resolveOptions();
resOpt.importsLoadStrategy = importsLoadStrategy.load;
const doc: CdmDocumentDefinition = await cdmCorpus.fetchObjectAsync<CdmDocumentDefinition>('local:/multipleImports.cdm.json', null, resOpt);
expect(doc)
.not
.toBeUndefined();
expect(doc.imports.length)
.toBe(2);
const firstImport: CdmDocumentDefinition = (doc.imports.allItems[0]).document;
expect(firstImport.name)
.toBe('missingImport.cdm.json');
expect(firstImport.imports.length)
.toBe(1);
const secondImport: CdmDocumentDefinition = (doc.imports.allItems[1]).document;
expect(secondImport.name)
.toBe('notMissing.cdm.json');
});
/**
* Testing an import with a non-existing namespace name.
*/
it('TestNonExistingAdapterNamespace', async () => {
const expectedLogCodes = new Set<cdmLogCode>([cdmLogCode.ErrPersistFileReadFailure]);
const cdmCorpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestNonExistingAdapterNamespace', undefined, false, expectedLogCodes);
cdmCorpus.storage.mount('erp', new LocalAdapter(testHelper.getInputFolderPath(testsSubpath, 'TestNonExistingAdapterNamespace')));
// Set local as our default.
cdmCorpus.storage.defaultNamespace = 'erp';
const manifestPath: string = cdmCorpus.storage.createAbsoluteCorpusPath('erp.missingImportManifest.cdm');
// Load a manifest that is trying to import from 'cdm' namespace.
// The manifest does't exist since the import couldn't get resolved,
// so the error message will be logged and the null value will be propagated back to a user.
expect(await cdmCorpus.fetchObjectAsync<CdmDocumentDefinition>('erp.missingImportManifest.cdm', null, null))
.toBeUndefined();
});
/**
* Testing docs that load the same import
*/
it('TestLoadingSameImportsAsync', async () => {
const cdmCorpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestLoadingSameImportsAsync');
const resOpt = new resolveOptions();
resOpt.importsLoadStrategy = importsLoadStrategy.load;
const mainDoc: CdmDocumentDefinition = await cdmCorpus.fetchObjectAsync<CdmDocumentDefinition>('mainEntity.cdm.json', null, resOpt);
expect(mainDoc)
.not
.toBeUndefined();
expect(mainDoc.imports.length)
.toBe(2);
const firstImport: CdmDocumentDefinition = mainDoc.imports.allItems[0].document;
const secondImport: CdmDocumentDefinition = mainDoc.imports.allItems[1].document;
// since these two imports are loaded asyncronously, we need to make sure that
// the import that they share (targetImport) was loaded, and that the
// targetImport doc is attached to both of these import objects
expect(firstImport.imports.length)
.toBe(1);
expect(firstImport.imports.allItems[0].document)
.toBeDefined();
expect(secondImport.imports.length)
.toBe(1);
expect(secondImport.imports.allItems[0].document)
.toBeDefined();
});
/**
* Testing docs that load the same import of which, the file cannot be found
*/
it('TestLoadingSameMissingImportsAsync', async () => {
const expectedLogCodes = new Set<cdmLogCode>([cdmLogCode.ErrPersistFileReadFailure, cdmLogCode.WarnResolveImportFailed, cdmLogCode.WarnDocImportNotLoaded]);
const cdmCorpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestLoadingSameMissingImportsAsync', undefined, false, expectedLogCodes);
const resOpt = new resolveOptions();
resOpt.importsLoadStrategy = importsLoadStrategy.load;
const mainDoc: CdmDocumentDefinition = await cdmCorpus.fetchObjectAsync<CdmDocumentDefinition>('mainEntity.cdm.json', null, resOpt);
expect(mainDoc)
.not
.toBeUndefined();
expect(mainDoc.imports.length)
.toBe(2);
// make sure imports loaded correctly, despite them missing imports
const firstImport: CdmDocumentDefinition = (mainDoc.imports.allItems[0]).document;
const secondImport: CdmDocumentDefinition = (mainDoc.imports.allItems[1]).document;
expect(firstImport.imports.length)
.toBe(1);
expect(firstImport.imports.allItems[0].document)
.toBeUndefined();
expect(secondImport.imports.length)
.toBe(1);
expect(firstImport.imports.allItems[0].document)
.toBeUndefined();
});
/**
* Testing doc that loads an import that has already been loaded before
*/
it('TestLoadingAlreadyPresentImportsAsync', async () => {
const cdmCorpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestLoadingAlreadyPresentImportsAsync');
const resOpt = new resolveOptions();
resOpt.importsLoadStrategy = importsLoadStrategy.load;
// load the first doc
const mainDoc: CdmDocumentDefinition = await cdmCorpus.fetchObjectAsync<CdmDocumentDefinition>('mainEntity.cdm.json', null, resOpt);
expect(mainDoc)
.not
.toBeUndefined();
expect(mainDoc.imports.length)
.toBe(1);
const importDoc: CdmDocumentDefinition = (mainDoc.imports.allItems[0]).document;
expect(importDoc)
.toBeDefined();
// now load the second doc, which uses the same import
// the import should not be loaded again, it should be the same object
const secondDoc: CdmDocumentDefinition = await cdmCorpus.fetchObjectAsync<CdmDocumentDefinition>('secondEntity.cdm.json', null, resOpt);
expect(secondDoc)
.not
.toBeUndefined();
expect(secondDoc.imports.length)
.toBe(1);
const secondImportDoc: CdmDocumentDefinition = (mainDoc.imports.allItems[0]).document;
expect(secondImportDoc)
.toBeDefined();
expect(importDoc)
.toBe(secondImportDoc);
});
/**
* Testing that import priorites update correctly when imports are changed
*/
it('TestPrioritizingImportsAfterEdit', async () => {
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestPrioritizingImportsAfterEdit');
var document = await corpus.fetchObjectAsync<CdmDocumentDefinition>('local:/mainDoc.cdm.json');
await document.refreshAsync(new resolveOptions(document));
expect(document.imports.length)
.toEqual(0);
// the current doc itself is added to the list of priorities
expect(document.importPriorities.importPriority.size)
.toEqual(1);
document.imports.push('importDoc.cdm.json', true);
await document.refreshAsync(new resolveOptions(document));
expect(document.imports.length)
.toEqual(1);
expect(document.importPriorities.importPriority.size)
.toEqual(2);
});
}); | the_stack |
import { AbstractCrdt, Doc, ApplyResult } from "./AbstractCrdt";
import { deserialize, isCrdt } from "./utils";
import {
CrdtType,
CreateObjectOp,
DeleteObjectKeyOp,
Op,
OpType,
SerializedCrdtWithId,
UpdateObjectOp,
} from "./live";
/**
* The LiveObject class is similar to a JavaScript object that is synchronized on all clients.
* Keys should be a string, and values should be serializable to JSON.
* If multiple clients update the same property simultaneously, the last modification received by the Liveblocks servers is the winner.
*/
export class LiveObject<
T extends Record<string, any> = Record<string, any>
> extends AbstractCrdt {
#map: Map<string, any>;
#propToLastUpdate: Map<string, string> = new Map<string, string>();
constructor(object: T = {} as T) {
super();
for (const key in object) {
const value = object[key] as any;
if (value instanceof AbstractCrdt) {
value._setParentLink(this, key);
}
}
this.#map = new Map(Object.entries(object));
}
/**
* INTERNAL
*/
_serialize(parentId?: string, parentKey?: string): Op[] {
if (this._id == null) {
throw new Error("Cannot serialize item is not attached");
}
const ops = [];
const op: CreateObjectOp = {
id: this._id,
type: OpType.CreateObject,
parentId,
parentKey,
data: {},
};
ops.push(op);
for (const [key, value] of this.#map) {
if (value instanceof AbstractCrdt) {
ops.push(...value._serialize(this._id, key));
} else {
op.data[key] = value;
}
}
return ops;
}
/**
* INTERNAL
*/
static _deserialize(
[id, item]: SerializedCrdtWithId,
parentToChildren: Map<string, SerializedCrdtWithId[]>,
doc: Doc
) {
if (item.type !== CrdtType.Object) {
throw new Error(
`Tried to deserialize a record but item type is "${item.type}"`
);
}
const object = new LiveObject(item.data);
object._attach(id, doc);
const children = parentToChildren.get(id);
if (children == null) {
return object;
}
for (const entry of children) {
const crdt = entry[1];
if (crdt.parentKey == null) {
throw new Error(
"Tried to deserialize a crdt but it does not have a parentKey and is not the root"
);
}
const child = deserialize(entry, parentToChildren, doc);
child._setParentLink(object, crdt.parentKey);
object.#map.set(crdt.parentKey, child);
}
return object;
}
/**
* INTERNAL
*/
_attach(id: string, doc: Doc) {
super._attach(id, doc);
for (const [key, value] of this.#map) {
if (value instanceof AbstractCrdt) {
value._attach(doc.generateId(), doc);
}
}
}
/**
* INTERNAL
*/
_attachChild(id: string, key: keyof T, child: AbstractCrdt): ApplyResult {
if (this._doc == null) {
throw new Error("Can't attach child if doc is not present");
}
const previousValue = this.#map.get(key as string);
let reverse: Op[];
if (isCrdt(previousValue)) {
reverse = previousValue._serialize(this._id!, key as string);
previousValue._detach();
} else if (previousValue === undefined) {
reverse = [
{ type: OpType.DeleteObjectKey, id: this._id!, key: key as string },
];
} else {
reverse = [
{
type: OpType.UpdateObject,
id: this._id!,
data: { [key]: previousValue },
} as any, // TODO
];
}
this.#map.set(key as string, child);
child._setParentLink(this, key as string);
child._attach(id, this._doc);
return { reverse, modified: this };
}
/**
* INTERNAL
*/
_detachChild(child: AbstractCrdt) {
for (const [key, value] of this.#map) {
if (value === child) {
this.#map.delete(key);
}
}
if (child) {
child._detach();
}
}
/**
* INTERNAL
*/
_detach() {
super._detach();
for (const value of this.#map.values()) {
if (isCrdt(value)) {
value._detach();
}
}
}
/**
* INTERNAL
*/
_apply(op: Op): ApplyResult {
if (op.type === OpType.UpdateObject) {
return this.#applyUpdate(op);
} else if (op.type === OpType.DeleteObjectKey) {
return this.#applyDeleteObjectKey(op);
}
return super._apply(op);
}
#applyUpdate(op: UpdateObjectOp): ApplyResult {
let isModified = false;
const reverse: Op[] = [];
const reverseUpdate: UpdateObjectOp = {
type: OpType.UpdateObject,
id: this._id!,
data: {},
};
reverse.push(reverseUpdate);
for (const key in op.data as Partial<T>) {
const oldValue = this.#map.get(key);
if (oldValue instanceof AbstractCrdt) {
reverse.push(...oldValue._serialize(this._id!, key));
oldValue._detach();
} else if (oldValue !== undefined) {
reverseUpdate.data[key] = oldValue;
} else if (oldValue === undefined) {
reverse.push({ type: OpType.DeleteObjectKey, id: this._id!, key });
}
}
let isLocal = false;
if (op.opId == null) {
isLocal = true;
op.opId = this._doc!.generateOpId();
}
for (const key in op.data as Partial<T>) {
if (isLocal) {
this.#propToLastUpdate.set(key, op.opId);
} else if (this.#propToLastUpdate.get(key) == null) {
// Not modified localy so we apply update
isModified = true;
} else if (this.#propToLastUpdate.get(key) === op.opId) {
// Acknowlegment from local operation
this.#propToLastUpdate.delete(key);
continue;
} else {
// Conflict, ignore remote operation
continue;
}
const oldValue = this.#map.get(key);
if (isCrdt(oldValue)) {
oldValue._detach();
}
isModified = true;
this.#map.set(key, op.data[key]);
}
if (Object.keys(reverseUpdate.data).length !== 0) {
reverse.unshift(reverseUpdate);
}
return isModified ? { modified: this, reverse } : { modified: false };
}
#applyDeleteObjectKey(op: DeleteObjectKeyOp): ApplyResult {
const key = op.key;
// If property does not exist, exit without notifying
if (this.#map.has(key) === false) {
return { modified: false };
}
const oldValue = this.#map.get(key);
let reverse: Op[] = [];
if (isCrdt(oldValue)) {
reverse = oldValue._serialize(this._id!, op.key);
oldValue._detach();
} else if (oldValue !== undefined) {
reverse = [
{
type: OpType.UpdateObject,
id: this._id!,
data: { [key]: oldValue },
},
];
}
this.#map.delete(key);
return { modified: this, reverse };
}
/**
* Transform the LiveObject into a javascript object
*/
toObject(): T {
return Object.fromEntries(this.#map) as T;
}
/**
* Adds or updates a property with a specified key and a value.
* @param key The key of the property to add
* @param value The value of the property to add
*/
set<TKey extends keyof T>(key: TKey, value: T[TKey]) {
// TODO: Find out why typescript complains
this.update({ [key]: value } as any as Partial<T>);
}
/**
* Returns a specified property from the LiveObject.
* @param key The key of the property to get
*/
get<TKey extends keyof T>(key: TKey): T[TKey] {
return this.#map.get(key as string);
}
/**
* Deletes a key from the LiveObject
* @param key The key of the property to delete
*/
delete(key: keyof T): void {
const keyAsString = key as string;
const oldValue = this.#map.get(keyAsString);
if (oldValue === undefined) {
return;
}
if (this._doc == null || this._id == null) {
if (oldValue instanceof AbstractCrdt) {
oldValue._detach();
}
this.#map.delete(keyAsString);
return;
}
let reverse: Op[];
if (oldValue instanceof AbstractCrdt) {
oldValue._detach();
reverse = oldValue._serialize(this._id, keyAsString);
} else {
reverse = [
{
type: OpType.UpdateObject,
data: { [keyAsString]: oldValue },
id: this._id,
},
];
}
this.#map.delete(keyAsString);
this._doc.dispatch(
[{ type: OpType.DeleteObjectKey, key: keyAsString, id: this._id }],
reverse,
[this]
);
}
/**
* Adds or updates multiple properties at once with an object.
* @param overrides The object used to overrides properties
*/
update(overrides: Partial<T>) {
if (this._doc == null || this._id == null) {
for (const key in overrides) {
const oldValue = this.#map.get(key);
if (oldValue instanceof AbstractCrdt) {
oldValue._detach();
}
const newValue = overrides[key] as any;
if (newValue instanceof AbstractCrdt) {
newValue._setParentLink(this, key);
}
this.#map.set(key, newValue);
}
return;
}
const ops: Op[] = [];
const reverseOps: Op[] = [];
const opId = this._doc.generateOpId();
const updatedProps: Partial<T> = {};
const reverseUpdateOp: UpdateObjectOp = {
id: this._id,
type: OpType.UpdateObject,
data: {},
};
for (const key in overrides) {
this.#propToLastUpdate.set(key, opId);
const oldValue = this.#map.get(key);
if (oldValue instanceof AbstractCrdt) {
reverseOps.push(...oldValue._serialize(this._id, key));
oldValue._detach();
} else if (oldValue === undefined) {
reverseOps.push({ type: OpType.DeleteObjectKey, id: this._id, key });
} else {
reverseUpdateOp.data[key] = oldValue;
}
const newValue = overrides[key] as any;
if (newValue instanceof AbstractCrdt) {
newValue._setParentLink(this, key);
newValue._attach(this._doc.generateId(), this._doc);
ops.push(...newValue._serialize(this._id, key));
} else {
updatedProps[key] = newValue;
}
this.#map.set(key, newValue);
}
if (Object.keys(reverseUpdateOp.data).length !== 0) {
reverseOps.unshift(reverseUpdateOp);
}
if (Object.keys(updatedProps).length !== 0) {
ops.unshift({
opId,
id: this._id,
type: OpType.UpdateObject,
data: updatedProps,
});
}
this._doc.dispatch(ops, reverseOps, [this]);
}
} | the_stack |
import {
CodeEditorInfo,
CustomLanguageInfo,
DocumentsInfo,
IDocumentFactory,
IDocumentPanel,
IDocumentService,
} from "@abstractions/document-service";
import { setDocumentFrameStateAction } from "@state/document-frame-reducer";
import { ILiteEvent, LiteEvent } from "@core/utils/lite-event";
import { getNodeExtension, getNodeFile } from "../../../core/abstractions/project-node";
import { CodeEditorFactory } from "./CodeEditorFactory";
import { dispatch, getState } from "@core/service-registry";
/**
* Represenst a service that handles document panels
*/
export class DocumentService implements IDocumentService {
private _documents: IDocumentPanel[];
private _activeDocument: IDocumentPanel | null;
private _activationStack: IDocumentPanel[];
private _documentsChanged = new LiteEvent<DocumentsInfo>();
private _fileBoundFactories = new Map<string, IDocumentFactory>();
private _extensionBoundFactories = new Map<string, IDocumentFactory>();
private _editorExtensions = new Map<string, CodeEditorInfo>();
private _languageExtensions = new Map<string, CustomLanguageInfo>();
constructor() {
this._documents = [];
this._activeDocument = null;
this._activationStack = [];
}
/**
* Gets the registered document panels
*/
getDocuments(): IDocumentPanel[] {
return this._documents;
}
/**
* Registers a factory for the specified file name
* @param filename Filename to use as the key for the factory
* @param factory Factory instance
*/
registerFileBoundFactory(filename: string, factory: IDocumentFactory): void {
this._fileBoundFactories.set(filename, factory);
}
/**
* Registers a factory for the specified file extension
* @param extension File extension the factory belongs to
* @param factory factory isntance
*/
registerExtensionBoundFactory(
extension: string,
factory: IDocumentFactory
): void {
this._extensionBoundFactories.set(extension, factory);
}
/**
* Registers a code editor for the specified extension
* @param extension File extendion
* @param editorInfo Editor information
*/
registerCodeEditor(extension: string, editorInfo: CodeEditorInfo): void {
this._editorExtensions.set(extension, editorInfo);
}
/**
* Registers a custom language
* @param language Language definition
*/
registerCustomLanguage(language: CustomLanguageInfo): void {
this._languageExtensions.set(language.id, language);
}
/**
* Gets code editor information for the specified resouce
* @param resource Resource namse
* @returns Code editor, if found; otherwise, undefined
*/
getCodeEditorInfo(resource: string): CodeEditorInfo | undefined {
return this._editorExtensions.get(getNodeExtension(resource));
}
/**
* Gets a custom language extension
* @param id Language id
*/
getCustomLanguage(id: string): CustomLanguageInfo | undefined {
return this._languageExtensions.get(id);
}
/**
* Gets a factory for the specified resource
* @param resource Resouce name
*/
getResourceFactory(resource: string): IDocumentFactory | null {
// --- Get the file name from the full resource name
const filename = getNodeFile(resource);
const extension = getNodeExtension(resource);
// --- Test if the file has a factory
const fileNameFactory = this._fileBoundFactories.get(filename);
if (fileNameFactory) {
return fileNameFactory;
}
// --- Test if the extension has a factory
if (!extension) {
return null;
}
const extensionFactory = this._extensionBoundFactories.get(extension);
if (extensionFactory) {
return extensionFactory;
}
// --- Test if extension has an editor factory
const codeEditorInfo = this._editorExtensions.get(extension);
const language = codeEditorInfo?.language ?? "";
return new CodeEditorFactory(language);
}
/**
* Registers a document
* @param doc Document instance to register
* @param index Document index
* @param makeActive Make this document the active one?
*/
registerDocument(
doc: IDocumentPanel,
makeActive: boolean = true,
index?: number
): IDocumentPanel {
// --- Do not register a document already registered
let existingDoc = this.getDocumentById(doc.id);
if (!existingDoc) {
existingDoc = doc;
// --- Fix the insert position
if (index === undefined || index === null) {
index = this._documents.length;
} else if (index < 0) {
index = 0;
} else if (index > this._documents.length - 1) {
index = this._documents.length;
} else {
index = index + 1;
}
// --- Insert the document and activate it
this._documents.splice(index, 0, doc);
this._documents = this._documents.slice(0);
doc.index = index;
if (makeActive || !this._activeDocument) {
this.setActiveDocument(doc);
}
this._activationStack.push(doc);
this.fireChanges();
} else {
if (makeActive || !this._activeDocument) {
this.setActiveDocument(existingDoc);
}
}
return existingDoc;
}
/**
* Unregisters (and removes) the specified document
* @param doc
*/
unregisterDocument(doc: IDocumentPanel): void {
// --- Unregister existing document only
const position = this._documents.indexOf(doc);
if (position < 0) {
return;
}
// --- Remove the document
this._documents.splice(position, 1);
this._documents = this._documents.slice(0);
this._activationStack = this._activationStack.filter((d) => d !== doc);
// --- Activate a document
if (this._activationStack.length > 0) {
this.setActiveDocument(this._activationStack.pop());
} else if (this._documents.length === 0) {
this.setActiveDocument(null);
} else if (position >= this._documents.length - 1) {
this.setActiveDocument(this._documents[this._documents.length - 1]);
} else {
this.setActiveDocument(this._documents[position + 1]);
}
this.fireChanges();
}
/**
* Sets the specified document to be the active one
* @param doc Document to activate
*/
setActiveDocument(doc: IDocumentPanel | null): void {
// --- Save the state of the active panel
if (this._activeDocument) {
const fullState = Object.assign({}, getState().documentFrame ?? {}, {
[this._activeDocument.id]: this._activeDocument.getPanelState(),
});
dispatch(setDocumentFrameStateAction(fullState));
}
if (!doc) {
// --- There is no active document
const oldDocument = this._activeDocument;
this._activeDocument = null;
if (!oldDocument) {
this.fireChanges();
return;
}
}
// --- You can activate only an existing document
const position = this._documents.indexOf(doc);
if (position < 0) {
return;
}
// --- Activate the document
this._activeDocument = doc;
this._activationStack.push(doc);
this._documents.forEach((d) => (d.active = false));
doc.active = true;
// --- Load the state of the active document
const documentsState = getState().documentFrame ?? {};
const documentState = documentsState?.[this._activeDocument.id];
if (documentState) {
this._activeDocument.setPanelState(documentState);
}
// --- Invoke custom action
this.fireChanges();
}
/**
* Gets the active document
*/
getActiveDocument(): IDocumentPanel | null {
return this._activeDocument;
}
/**
* Gets the document with the specified identifier
* @param id Document ID to search for
*/
getDocumentById(id: string): IDocumentPanel | null {
return this._documents.find((d) => d.id === id) ?? null;
}
/**
* Gets the temporary document
*/
getTemporaryDocument(): IDocumentPanel | null {
return this._documents.find((d) => d.temporary) ?? null;
}
/**
* Moves the document to the left
* @param doc Document to move
*/
moveLeft(doc: IDocumentPanel): void {
const index = this._documents.indexOf(doc);
if (index > 0) {
const tmp = this._documents[index];
this._documents[index] = this._documents[index - 1];
this._documents[index - 1] = tmp;
this._documents = this._documents.slice(0);
this.fireChanges();
}
}
/**
* Moves the document to the right
* @param doc Document to move
*/
moveRight(doc: IDocumentPanel): void {
const index = this._documents.indexOf(doc);
if (index >= 0 && index < this._documents.length - 1) {
const tmp = this._documents[index];
this._documents[index] = this._documents[index + 1];
this._documents[index + 1] = tmp;
this._documents = this._documents.slice(0);
this.fireChanges();
}
}
/**
* Closes all documents
*/
closeAll(): void {
const docs = this._documents.slice(0);
docs.forEach((d) => this.unregisterDocument(d));
}
/**
* Closes all documents except the specified one
* @param doc Document to keep open
*/
closeOthers(doc: IDocumentPanel): void {
const otherDocs = this._documents.filter((d) => d !== doc);
otherDocs.forEach((d) => this.unregisterDocument(d));
}
/**
* Closes all documents to the right of the specified one
* @param doc Document to keep open
*/
closeToTheRight(doc: IDocumentPanel): void {
const index = this._documents.indexOf(doc);
if (index >= 0 && index < this._documents.length - 1) {
const rightDocs = this._documents.slice(index + 1);
rightDocs.forEach((d) => this.unregisterDocument(d));
}
}
/**
* Fires when any documents changes occurres
*/
get documentsChanged(): ILiteEvent<DocumentsInfo> {
return this._documentsChanged;
}
/**
* Fires the documents changed event
*/
fireChanges(): void {
this._documentsChanged.fire({
docs: this._documents.slice(0),
active: this._activeDocument,
});
}
} | the_stack |
import FlowMapLayer, { Flow, Location } from '@flowmap.gl/core';
import FlowMap, { DiffColorsLegend, getViewStateForFeatures, LegendBox, LocationTotalsLegend } from '@flowmap.gl/react';
import { storiesOf } from '@storybook/react';
import * as d3scaleChromatic from 'd3-scale-chromatic';
import React from 'react';
import { mapboxAccessToken } from '../index';
import pipe from '../utils/pipe';
import { withFetchJson } from '../utils/withFetch';
import withStats from '../utils/withStats';
import ClusteringExample from '../components/ClusteringExample';
import withSheetsFetch from '../utils/withSheetsFetch';
import Example from '../components/Example';
import { DeckGL } from '@deck.gl/react';
import { StaticMap } from 'react-map-gl';
const getLocationId = (loc: Location) => loc.properties.abbr;
const DARK_COLORS = {
darkMode: true,
flows: {
scheme: [
'rgb(0, 22, 61)',
'rgb(0, 27, 62)',
'rgb(0, 36, 68)',
'rgb(0, 48, 77)',
'rgb(3, 65, 91)',
'rgb(48, 87, 109)',
'rgb(85, 115, 133)',
'rgb(129, 149, 162)',
'rgb(179, 191, 197)',
'rgb(240, 240, 240)',
],
},
locationAreas: {
normal: '#334',
},
outlineColor: '#000',
};
storiesOf('Basic', module)
.add(
'basic as layer',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const flowMapLayer = new FlowMapLayer({
id: 'flow-map-layer',
locations,
flows,
getLocationId: (loc: Location) => loc.properties.abbr,
getFlowMagnitude: (f: Flow) => f.count,
});
return (
<DeckGL
style={{ mixBlendMode: 'multiply' }}
controller={true}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
layers={[flowMapLayer]}
>
<StaticMap mapboxApiAccessToken={mapboxAccessToken} width="100%" height="100%" />
</DeckGL>
);
}),
)
.add(
'basic as interactive component',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
</>
)),
)
.add(
'custom flow color scheme',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const colors = {
flows: {
scheme: d3scaleChromatic.schemeGnBu[d3scaleChromatic.schemeGnBu.length - 1] as string[],
},
};
return (
<>
<FlowMap
pickable={true}
colors={colors}
getLocationId={getLocationId}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend colors={colors} />
</LegendBox>
</>
);
}),
)
.add(
'two layers',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
return (
<DeckGL
style={{ mixBlendMode: 'multiply' }}
controller={true}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
layers={[
new FlowMapLayer({
id: 'flow-map-layer-1',
colors: {
flows: {
scheme: d3scaleChromatic.schemeReds[d3scaleChromatic.schemeReds.length - 1] as string[],
},
},
showLocationAreas: false,
locations,
flows: flows.filter((f: Flow) => f.origin === 'GE'),
getLocationId,
}),
new FlowMapLayer({
id: 'flow-map-layer-2',
colors: {
flows: {
scheme: d3scaleChromatic.schemeBlues[d3scaleChromatic.schemeBlues.length - 1] as string[],
},
},
locations,
showLocationAreas: false,
flows: flows.filter((f: Flow) => f.origin === 'ZH'),
getLocationId,
}),
]}
>
<StaticMap mapboxApiAccessToken={mapboxAccessToken} width="100%" height="100%" />
</DeckGL>
);
}),
)
.add(
'bearing pitch',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const viewport = getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight]);
return (
<>
<FlowMap
pickable={true}
mixBlendMode="multiply"
getLocationId={getLocationId}
flows={flows}
locations={locations}
showLocationAreas={false}
initialViewState={{
...viewport,
altitude: 1.5,
bearing: 40,
pitch: 50,
zoom: viewport.zoom * 1.1,
}}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend colors={DARK_COLORS} />
</LegendBox>
</>
);
}),
)
.add(
'dark mode',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
return (
<>
<FlowMap
pickable={true}
colors={DARK_COLORS}
mapStyle="mapbox://styles/mapbox/dark-v10"
mixBlendMode="screen"
getLocationId={getLocationId}
flows={flows}
locations={locations}
showLocationAreas={false}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10} style={{ backgroundColor: '#000', color: '#fff' }}>
<LocationTotalsLegend colors={DARK_COLORS} />
</LegendBox>
</>
);
}),
)
.add(
'custom dark mode color scheme',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const scheme = (d3scaleChromatic.schemeGnBu[d3scaleChromatic.schemeGnBu.length - 1] as string[])
.slice()
.reverse();
const colors = {
darkMode: true,
flows: {
scheme,
},
locationAreas: {
normal: '#334',
},
outlineColor: '#000',
};
return (
<>
<FlowMap
pickable={true}
colors={colors}
mapStyle="mapbox://styles/mapbox/dark-v10"
mixBlendMode="screen"
getLocationId={getLocationId}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10} style={{ backgroundColor: '#000', color: '#fff' }}>
<LocationTotalsLegend colors={colors} />
</LegendBox>
</>
);
}),
)
.add(
'animated',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<FlowMap
pickable={true}
animate={true}
getLocationId={getLocationId}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
)),
)
.add(
'animationTailLength',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const [animationTailLength, setAnimationTailLength] = React.useState(0.7);
return (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
flows={flows}
animate={true}
animationTailLength={animationTailLength}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
<LegendBox top={10} right={10}>
<label>Tail length:</label>
<input
type="range"
value={animationTailLength}
min={0.0}
max={1}
step={0.01}
onChange={evt => setAnimationTailLength(+evt.currentTarget.value)}
/>
</LegendBox>
</>
);
}),
)
.add(
'zoom > 12',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<FlowMap
pickable={true}
getLocationId={getLocationId}
showTotals={true}
showLocationAreas={true}
flows={flows}
locations={locations}
initialViewState={{
...getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight]),
zoom: 13,
longitude: 8.645888,
latitude: 47.411184,
}}
mapboxAccessToken={mapboxAccessToken}
/>
)),
)
.add(
'only top 100 flows',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<FlowMap
pickable={true}
getLocationId={getLocationId}
showTotals={true}
showOnlyTopFlows={100}
showLocationAreas={true}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
)),
)
.add(
'no location areas',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<FlowMap
pickable={true}
colors={{ outlineColor: '#fff' }}
getLocationId={getLocationId}
showTotals={true}
showLocationAreas={false}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
)),
)
.add(
'no location totals',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<FlowMap
pickable={true}
getLocationId={getLocationId}
showTotals={false}
showLocationAreas={true}
flows={flows}
locations={locations}
maxLocationCircleSize={3}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
)),
)
.add(
'custom zone totals',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const locationIds = locations.features.map(getLocationId).reverse();
const getTotal = (location: Location) => Math.pow(locationIds.indexOf(getLocationId(location)), 10);
return (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
flows={flows}
locations={locations}
getLocationTotalIn={getTotal}
getLocationTotalOut={getTotal}
getLocationTotalWithin={getTotal}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
</>
);
}),
)
.add(
'flow color override',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<FlowMap
pickable={true}
getLocationId={getLocationId}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
getFlowColor={(f: Flow) => {
if (f.origin === 'ZH' && f.dest === 'AG') {
return 'orange';
}
return undefined;
}}
/>
)),
)
.add(
'custom outlines',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<FlowMap
pickable={true}
colors={{
outlineColor: '#64e9f9',
}}
getLocationId={getLocationId}
showTotals={true}
showLocationAreas={true}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
outlineThickness={5}
mapboxAccessToken={mapboxAccessToken}
/>
)),
)
.add(
'maxLocationCircleSize',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<FlowMap
pickable={true}
getLocationId={getLocationId}
showTotals={true}
showLocationAreas={true}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
maxLocationCircleSize={30}
mapboxAccessToken={mapboxAccessToken}
/>
)),
)
.add(
'multiselect',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<FlowMap
pickable={true}
getLocationId={getLocationId}
flows={flows}
locations={locations}
multiselect={true}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
)),
)
.add(
'non-pickable',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<>
<FlowMap
pickable={false}
getLocationId={getLocationId}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
</>
)),
)
.add(
'basic',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
</>
)),
)
.add(
'difference mode',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-diff-2015-2016.json'),
)(({ locations, flows }: any) => (
<>
<FlowMap
pickable={true}
diffMode={true}
getLocationId={getLocationId}
showTotals={true}
showLocationAreas={true}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<DiffColorsLegend />
<hr />
<LocationTotalsLegend diff={true} />
</LegendBox>
</>
)),
)
.add('custom legend', () => (
<>
<LegendBox bottom={35} left={10}>
<DiffColorsLegend positiveText="+ diff" negativeText="- diff" />
<hr />
<LocationTotalsLegend
diff={true}
aboutEqualText="equal"
moreOutgoingText="> outgoing"
moreIncomingText="> incoming"
/>
</LegendBox>
</>
))
.add(
'opacity',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const [opacity, setOpacity] = React.useState(0.5);
return (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
opacity={opacity}
flows={flows}
animate={false}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
<LegendBox top={10} right={10}>
<label>Opacity:</label>
<input
type="range"
value={opacity}
min={0}
max={1}
step={0.05}
onChange={evt => setOpacity(+evt.currentTarget.value)}
/>
</LegendBox>
</>
);
}),
)
.add(
'maxFlowThickness',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const [thickness, setThickness] = React.useState(15);
return (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
maxFlowThickness={thickness}
flows={flows}
animate={false}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
<LegendBox top={10} right={10}>
<label>Thickness:</label>
<input
type="range"
value={thickness}
min={0}
max={30}
onChange={evt => setThickness(+evt.currentTarget.value)}
/>
</LegendBox>
</>
);
}),
)
.add(
'flowMagnitudeExtent, locationTotalsExtent',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const [maxFlowMagnitude, setMaxFlowMagnitude] = React.useState(10000);
const flowMagnitudeExtent: [number, number] = [0, maxFlowMagnitude];
const [maxLocationTotal, setMaxLocationTotal] = React.useState(500000);
const locationTotalsExtent: [number, number] = [0, maxLocationTotal];
return (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
flowMagnitudeExtent={flowMagnitudeExtent}
locationTotalsExtent={locationTotalsExtent}
flows={flows}
animate={false}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
<LegendBox top={10} right={10} style={{ maxWidth: 320 }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
<label>flowMagnitudeExtent[1]:</label>
<input
type="range"
value={maxFlowMagnitude}
min={2000}
max={20000}
onChange={evt => setMaxFlowMagnitude(+evt.currentTarget.value)}
/>
<label>locationTotalExtent[1]:</label>
<input
type="range"
value={maxLocationTotal}
min={10000}
max={1000000}
step={100}
onChange={evt => setMaxLocationTotal(+evt.currentTarget.value)}
/>
</div>
<div style={{ fontSize: 'small', color: '#999' }}>
Use it to fix the scales of a changing dataset (e.g. over time)
</div>
</LegendBox>
</>
);
}),
)
.add(
'flowMagnitudeExtent, locationTotalsExtent in diff mode',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-diff-2015-2016.json'),
)(({ locations, flows }: any) => {
const [maxFlowMagnitude, setMaxFlowMagnitude] = React.useState(500);
const flowMagnitudeExtent: [number, number] = [0, maxFlowMagnitude];
const [maxLocationTotal, setMaxLocationTotal] = React.useState(50000);
const locationTotalsExtent: [number, number] = [0, maxLocationTotal];
return (
<>
<FlowMap
pickable={true}
diffMode={true}
getLocationId={getLocationId}
showTotals={true}
showLocationAreas={true}
flows={flows}
flowMagnitudeExtent={flowMagnitudeExtent}
locationTotalsExtent={locationTotalsExtent}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<DiffColorsLegend />
<hr />
<LocationTotalsLegend diff={true} />
</LegendBox>
<LegendBox top={10} right={10}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
<label>flowMagnitudeExtent[1]:</label>
<input
type="range"
value={maxFlowMagnitude}
min={2000}
max={20000}
onChange={evt => setMaxFlowMagnitude(+evt.currentTarget.value)}
/>
<label>locationTotalExtent[1]:</label>
<input
type="range"
value={maxLocationTotal}
min={1000}
max={100000}
step={10}
onChange={evt => setMaxLocationTotal(+evt.currentTarget.value)}
/>
</div>
<div style={{ fontSize: 'small', color: '#999' }}>
Use it to fix the scales of a changing dataset (e.g. over time)
</div>
</LegendBox>
</>
);
}),
)
.add(
'maxFlowThickness animated',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
const [thickness, setThickness] = React.useState(15);
return (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
maxFlowThickness={thickness}
flows={flows}
animate={true}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
<LegendBox top={10} right={10}>
<label>Thickness:</label>
<input
type="range"
value={thickness}
min={0}
max={30}
onChange={evt => setThickness(+evt.currentTarget.value)}
/>
</LegendBox>
</>
);
}),
)
.add(
'minPickableFlowThickness',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
return (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
minPickableFlowThickness={1}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
</>
);
}),
)
.add(
'minPickableFlowThickness animated',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => {
return (
<>
<FlowMap
pickable={true}
getLocationId={getLocationId}
minPickableFlowThickness={1}
animate={true}
flows={flows}
locations={locations}
initialViewState={getViewStateForFeatures(locations, [window.innerWidth, window.innerHeight])}
mapboxAccessToken={mapboxAccessToken}
/>
<LegendBox bottom={35} left={10}>
<LocationTotalsLegend />
</LegendBox>
</>
);
}),
);
storiesOf('Cluster on zoom', module)
.add(
'basic',
pipe(
withStats,
withFetchJson('locations', './data/locations.json'),
withFetchJson('flows', './data/flows-2016.json'),
)(({ locations, flows }: any) => (
<ClusteringExample
locations={locations}
flows={flows}
getLocationId={(loc: Location) => loc.properties.abbr}
getLocationCentroid={(loc: Location) => loc.properties.centroid}
getFlowOriginId={(flow: Flow) => flow.origin}
getFlowDestId={(flow: Flow) => flow.dest}
getFlowMagnitude={(flow: Flow) => +flow.count}
/>
)),
)
.add(
'NL commuters',
pipe(
withStats,
withSheetsFetch('1Oe3zM219uSfJ3sjdRT90SAK2kU3xIvzdcCW6cwTsAuc'),
)(({ locations, flows }: any) => (
<ClusteringExample
locations={locations}
flows={flows}
getLocationId={(loc: Location) => loc.id}
getLocationCentroid={(loc: Location): [number, number] => [+loc.lon, +loc.lat]}
getFlowOriginId={(flow: Flow) => flow.origin}
getFlowDestId={(flow: Flow) => flow.dest}
getFlowMagnitude={(flow: Flow) => +flow.count}
/>
)),
);
storiesOf('Other datasets', module)
.add(
'London bicycle hire',
pipe(
withStats,
withSheetsFetch('1Z6dVVFFrdooHIs8xnJ_O7eM5bhS5KscCi7G_k0jUNDI'),
)(({ locations, flows }: any) => (
<Example
flows={flows}
locations={locations}
getLocationId={(loc: Location) => loc.id}
getLocationCentroid={(location: Location): [number, number] => [+location.lon, +location.lat]}
getFlowOriginId={(flow: Flow) => flow.origin}
getFlowDestId={(flow: Flow) => flow.dest}
getFlowMagnitude={(flow: Flow) => +flow.count}
/>
)),
)
.add(
'NYC citibike',
pipe(
withStats,
withSheetsFetch('1Aum0anWxPx6bHyfcFXWCCTE8u0xtfenIls_kPAJEDIA'),
)(({ locations, flows }: any) => (
<Example
flows={flows}
locations={locations}
getLocationId={(loc: Location) => loc.id}
getLocationCentroid={(location: Location): [number, number] => [+location.lon, +location.lat]}
getFlowOriginId={(flow: Flow) => flow.origin}
getFlowDestId={(flow: Flow) => flow.dest}
getFlowMagnitude={(flow: Flow) => +flow.count}
/>
)),
)
.add(
'Chicago taxis',
pipe(
withStats,
withSheetsFetch('1fhX98NFv5gAkkjB2YFCm50-fplFpmWVAZby3dmm9cgQ'),
)(({ locations, flows }: any) => (
<Example
flows={flows}
locations={locations}
getLocationId={(loc: Location) => loc.id}
getLocationCentroid={(location: Location): [number, number] => [+location.lon, +location.lat]}
getFlowOriginId={(flow: Flow) => flow.origin}
getFlowDestId={(flow: Flow) => flow.dest}
getFlowMagnitude={(flow: Flow) => +flow.count}
/>
)),
)
.add(
'NL commuters',
pipe(
withStats,
withSheetsFetch('1Oe3zM219uSfJ3sjdRT90SAK2kU3xIvzdcCW6cwTsAuc'),
)(({ locations, flows }: any) => (
<Example
flows={flows}
locations={locations}
getLocationId={(loc: Location) => loc.id}
getLocationCentroid={(location: Location): [number, number] => [+location.lon, +location.lat]}
getFlowOriginId={(flow: Flow) => flow.origin}
getFlowDestId={(flow: Flow) => flow.dest}
getFlowMagnitude={(flow: Flow) => +flow.count}
/>
)),
); | the_stack |
import {
generateProperty,
generateColor,
generateBorderRadius,
generateMargin,
} from './utils'
import { dslPxtoRem } from './dslPxtoRem'
import { dslPxtoRpx } from './dslPxtoRpx'
import cssOrder from './cssOrder'
// 驼峰改连接符
const toKebabCase = (str: any) => str.replace(/([A-Z])/g, '-$1').toLowerCase()
const addPx = (val: any) => {
if (typeof val == 'number') return `${val}px`
return val
}
// 转rem
export const formateDslRemStyle = (formateDsl: any, remScale:any) => {
// 标注稿以rem形式展示
if (!remScale || isNaN(Number(remScale))) return formateDsl
for (let item of formateDsl) {
let remStyle: any = {} // 样式集合
remStyle = dslPxtoRem(item.style, remScale);
item.style = remStyle;
if (item.children && item.children.length) {
formateDslRemStyle(item.children, remScale)
}
}
return formateDsl
}
//转rpx
export const formatDslRpxStyle = (formateDsl: any, size: number) => {
for (let item of formateDsl) {
let rpxStyle: any = {} // 样式集合
rpxStyle = dslPxtoRpx(item.style, size);
item.style = rpxStyle;
if (item.children && item.children.length) {
formatDslRpxStyle(item.children, size)
}
}
return formateDsl
}
/**
* DSL=> webStyle 转换方法
* @param data
*/
export const formateDslStyle = (data: any) => {
//let formateDsl = JSON.parse(JSON.stringify(data))
for (let i = 0; i < data.length; i++) {
let style: any = {} // 样式集合
const item = data[i];
// 处理 structure
if (item.structure && Object.keys(item.structure).length) {
for (var key in item.structure) {
let currValue = item.structure[key]
// sketch 设计稿解析过来的没有 margin 和 padding
switch (key) {
case 'border':
style = {
...style,
...generateProperty(currValue),
}
break
case 'width':
style[key] = `${Math.round(currValue * 100) / 100}px`
break
case 'height':
style[key] = `${Math.round(currValue * 100) / 100}px`
break
case 'x':
case 'y':
if (style.position) {
style[key] = `${Math.round(currValue * 100) / 100}px`
}
break
case 'zIndex':
if (style.position) {
style[toKebabCase(key)] = currValue;
}
break
default:
style[toKebabCase(key)] = generateMargin(currValue)
break
}
}
}
// 处理 style
if (item.style && Object.keys(item.style).length) {
for (var key in item.style) {
if (
item.style.hasOwnProperty(key) &&
item.style[key] != undefined
) {
let currValue = item.style[key]
switch (key) {
case 'textStyle': // text样式直接放在style里
for (let textKey of Object.keys(currValue)) {
let textVal = currValue[textKey]
// 颜色处理
if (textKey == 'color') {
textVal = generateColor(textVal)
}
// px处理
if (textKey == 'lineHeight' || textKey == 'fontSize' || textKey == 'textIndent'|| textKey == 'letterSpacing') {
textVal = `${Math.round(currValue[textKey] * 100) / 100}px`
}
// 其他不处理
style[toKebabCase(textKey)] = textVal
}
break
case 'background': // background样式放到background里
let propertyVal
for (let backgroundKey of Object.keys(currValue)) {
let backgroundVal = currValue[backgroundKey]
if (backgroundKey == 'linearGradient') {
let { gAngle, gList } = backgroundVal;
let list = gList.map((ref: any) => {
return `${generateColor(ref.color)} ${ref.position*100}%`
});
list = [...new Set(list)];
style['background'] = `linear-gradient(${
Math.round(gAngle * 100) / 100
}deg, ${list.join(',')})`
} else if (backgroundKey == 'radialGradient') {
let {
backgroundVal: any,
smallRadius,
largeRadius,
position,
gList,
} = backgroundVal
let list = gList.map((ref: any) => {
return `${generateColor(ref.color)} ${ref.position*100}%`
})
style['background'] = `radial-gradient(${
Math.round(smallRadius * 100) / 100
}px ${
Math.round(largeRadius * 100) / 100
}px at ${
Math.round(position.left * 100) / 100
}px ${
Math.round(-position.top * 100) / 100
}px, ${list.join(',')})`
} else if (typeof backgroundVal == 'object') {
if (backgroundKey == 'color') {
propertyVal = generateColor(
backgroundVal
)
} else if (backgroundKey == 'image' && item.type !== 'Image') {
propertyVal =`url(../images/${backgroundVal.url})`;
} else { // position、size
let valList = []
for (let ref of Object.keys(backgroundVal)) {
valList.push(
addPx(backgroundVal[ref])
)
}
propertyVal = valList.join(' ')
}
style[`background-${backgroundKey}`] = propertyVal
// 如果为图片,则背景色无效
if (item.type==='Image') {
delete style['background-color']
}
} else if (backgroundKey == 'repeat') {
// style[`background-${backgroundKey}`] = backgroundVal
}
}
break
case 'textShadow':
case 'boxShadow':
let shodowList = []
for (let item of currValue) {
let {
offsetX,
offsetY,
spread,
blurRadius,
color,
type,
} = item
shodowList.push(
type
? `${offsetX}px ${offsetY}px ${blurRadius}px ${spread}px ${generateColor(color)} ${type}`
: `${offsetX}px ${offsetY}px ${blurRadius}px ${spread}px ${generateColor(color)}`
)
}
if (shodowList.length) {
style[toKebabCase(key)] = shodowList.join(', ')
}
break
case 'transform':
let { scale = {}, rotate } = currValue
let transform = []
if (
scale.horizontal != undefined &&
scale.vertical != undefined
) {
transform.push(`scale(${scale.horizontal},${scale.vertical})`)
}
if (rotate != undefined) {
transform.push(`rotate(${rotate}deg)`)
}
if (transform && transform.length) {
style['transform'] = transform.join(' ')
}
break
case 'borderRadius':
let borderRadius = generateBorderRadius(currValue)
if (borderRadius) {
style['border-radius'] = borderRadius
}
break
case 'zIndex':
case 'fontWeight':
style[key] = currValue
break
case 'lineHeight':
style[toKebabCase(key)] = currValue
break
case 'width':
case 'height':
case 'marginTop':
case 'marginRight':
case 'marginLeft':
case 'marginBottom':
case 'paddingTop':
case 'paddingRight':
case 'paddingLeft':
case 'paddingBottom':
typeof currValue == 'string'
? (style[toKebabCase(key)] = currValue)
: (style[toKebabCase(key)] = `${currValue}px`)
break
default:
typeof currValue == 'string'
? (style[toKebabCase(key)] = currValue)
: (style[toKebabCase(key)] = `${currValue}px`)
}
}
}
}
// css 排序
data[i].style = cssOrder(style);
if (data[i].children && data[i].children.length) {
data[i].children = formateDslStyle(data[i].children);
}
}
return data
} | the_stack |
import { RawHttpHeaders } from "@azure/core-rest-pipeline";
import { HttpResponse } from "@azure-rest/core-client";
import { ErrorModelOutput } from "./outputModels";
/** Send a post request with header value "User-Agent": "overwrite" */
export interface ParamExistingKey200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header value "User-Agent": "overwrite" */
export interface ParamExistingKeydefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseExistingKey200Headers {
/** response with header value "User-Agent": "overwrite" */
"user-agent"?: string;
}
/** Get a response with header value "User-Agent": "overwrite" */
export interface ResponseExistingKey200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseExistingKey200Headers;
}
/** Get a response with header value "User-Agent": "overwrite" */
export interface ResponseExistingKeydefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header value "Content-Type": "text/html" */
export interface ParamProtectedKey200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header value "Content-Type": "text/html" */
export interface ParamProtectedKeydefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseProtectedKey200Headers {
/** response with header value "Content-Type": "text/html" */
"content-type"?: string;
}
/** Get a response with header value "Content-Type": "text/html" */
export interface ResponseProtectedKey200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseProtectedKey200Headers;
}
/** Get a response with header value "Content-Type": "text/html" */
export interface ResponseProtectedKeydefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "positive", "value": 1 or "scenario": "negative", "value": -2 */
export interface ParamInteger200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "positive", "value": 1 or "scenario": "negative", "value": -2 */
export interface ParamIntegerdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseInteger200Headers {
/** response with header value "value": 1 or -2 */
value?: number;
}
/** Get a response with header value "value": 1 or -2 */
export interface ResponseInteger200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseInteger200Headers;
}
/** Get a response with header value "value": 1 or -2 */
export interface ResponseIntegerdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "positive", "value": 105 or "scenario": "negative", "value": -2 */
export interface ParamLong200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "positive", "value": 105 or "scenario": "negative", "value": -2 */
export interface ParamLongdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseLong200Headers {
/** response with header value "value": 105 or -2 */
value?: number;
}
/** Get a response with header value "value": 105 or -2 */
export interface ResponseLong200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseLong200Headers;
}
/** Get a response with header value "value": 105 or -2 */
export interface ResponseLongdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "positive", "value": 0.07 or "scenario": "negative", "value": -3.0 */
export interface ParamFloat200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "positive", "value": 0.07 or "scenario": "negative", "value": -3.0 */
export interface ParamFloatdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseFloat200Headers {
/** response with header value "value": 0.07 or -3.0 */
value?: number;
}
/** Get a response with header value "value": 0.07 or -3.0 */
export interface ResponseFloat200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseFloat200Headers;
}
/** Get a response with header value "value": 0.07 or -3.0 */
export interface ResponseFloatdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "positive", "value": 7e120 or "scenario": "negative", "value": -3.0 */
export interface ParamDouble200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "positive", "value": 7e120 or "scenario": "negative", "value": -3.0 */
export interface ParamDoubledefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseDouble200Headers {
/** response with header value "value": 7e120 or -3.0 */
value?: number;
}
/** Get a response with header value "value": 7e120 or -3.0 */
export interface ResponseDouble200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseDouble200Headers;
}
/** Get a response with header value "value": 7e120 or -3.0 */
export interface ResponseDoubledefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "true", "value": true or "scenario": "false", "value": false */
export interface ParamBool200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "true", "value": true or "scenario": "false", "value": false */
export interface ParamBooldefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseBool200Headers {
/** response with header value "value": true or false */
value?: boolean;
}
/** Get a response with header value "value": true or false */
export interface ResponseBool200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseBool200Headers;
}
/** Get a response with header value "value": true or false */
export interface ResponseBooldefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "valid", "value": "The quick brown fox jumps over the lazy dog" or "scenario": "null", "value": null or "scenario": "empty", "value": "" */
export interface ParamString200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "valid", "value": "The quick brown fox jumps over the lazy dog" or "scenario": "null", "value": null or "scenario": "empty", "value": "" */
export interface ParamStringdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseString200Headers {
/** response with header values "The quick brown fox jumps over the lazy dog" or null or "" */
value?: string;
}
/** Get a response with header values "The quick brown fox jumps over the lazy dog" or null or "" */
export interface ResponseString200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseString200Headers;
}
/** Get a response with header values "The quick brown fox jumps over the lazy dog" or null or "" */
export interface ResponseStringdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "valid", "value": "2010-01-01" or "scenario": "min", "value": "0001-01-01" */
export interface ParamDate200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "valid", "value": "2010-01-01" or "scenario": "min", "value": "0001-01-01" */
export interface ParamDatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseDate200Headers {
/** response with header values "2010-01-01" or "0001-01-01" */
value?: string;
}
/** Get a response with header values "2010-01-01" or "0001-01-01" */
export interface ResponseDate200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseDate200Headers;
}
/** Get a response with header values "2010-01-01" or "0001-01-01" */
export interface ResponseDatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "valid", "value": "2010-01-01T12:34:56Z" or "scenario": "min", "value": "0001-01-01T00:00:00Z" */
export interface ParamDatetime200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "valid", "value": "2010-01-01T12:34:56Z" or "scenario": "min", "value": "0001-01-01T00:00:00Z" */
export interface ParamDatetimedefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseDatetime200Headers {
/** response with header values "2010-01-01T12:34:56Z" or "0001-01-01T00:00:00Z" */
value?: string;
}
/** Get a response with header values "2010-01-01T12:34:56Z" or "0001-01-01T00:00:00Z" */
export interface ResponseDatetime200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseDatetime200Headers;
}
/** Get a response with header values "2010-01-01T12:34:56Z" or "0001-01-01T00:00:00Z" */
export interface ResponseDatetimedefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "valid", "value": "Wed, 01 Jan 2010 12:34:56 GMT" or "scenario": "min", "value": "Mon, 01 Jan 0001 00:00:00 GMT" */
export interface ParamDatetimeRfc1123200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "valid", "value": "Wed, 01 Jan 2010 12:34:56 GMT" or "scenario": "min", "value": "Mon, 01 Jan 0001 00:00:00 GMT" */
export interface ParamDatetimeRfc1123defaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseDatetimeRfc1123200Headers {
/** response with header values "Wed, 01 Jan 2010 12:34:56 GMT" or "Mon, 01 Jan 0001 00:00:00 GMT" */
value?: string;
}
/** Get a response with header values "Wed, 01 Jan 2010 12:34:56 GMT" or "Mon, 01 Jan 0001 00:00:00 GMT" */
export interface ResponseDatetimeRfc1123200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseDatetimeRfc1123200Headers;
}
/** Get a response with header values "Wed, 01 Jan 2010 12:34:56 GMT" or "Mon, 01 Jan 0001 00:00:00 GMT" */
export interface ResponseDatetimeRfc1123defaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "valid", "value": "P123DT22H14M12.011S" */
export interface ParamDuration200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "valid", "value": "P123DT22H14M12.011S" */
export interface ParamDurationdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseDuration200Headers {
/** response with header values "P123DT22H14M12.011S" */
value?: string;
}
/** Get a response with header values "P123DT22H14M12.011S" */
export interface ResponseDuration200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseDuration200Headers;
}
/** Get a response with header values "P123DT22H14M12.011S" */
export interface ResponseDurationdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "valid", "value": "啊齄丂狛狜隣郎隣兀﨩" */
export interface ParamByte200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "valid", "value": "啊齄丂狛狜隣郎隣兀﨩" */
export interface ParamBytedefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseByte200Headers {
/** response with header values "啊齄丂狛狜隣郎隣兀﨩" */
value?: string;
}
/** Get a response with header values "啊齄丂狛狜隣郎隣兀﨩" */
export interface ResponseByte200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseByte200Headers;
}
/** Get a response with header values "啊齄丂狛狜隣郎隣兀﨩" */
export interface ResponseBytedefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send a post request with header values "scenario": "valid", "value": "GREY" or "scenario": "null", "value": null */
export interface ParamEnum200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send a post request with header values "scenario": "valid", "value": "GREY" or "scenario": "null", "value": null */
export interface ParamEnumdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
export interface ResponseEnum200Headers {
/** response with header values "GREY" or null */
value?: "White" | "black" | "GREY";
}
/** Get a response with header values "GREY" or null */
export interface ResponseEnum200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
headers: RawHttpHeaders & ResponseEnum200Headers;
}
/** Get a response with header values "GREY" or null */
export interface ResponseEnumdefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
}
/** Send x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request */
export interface CustomRequestId200Response extends HttpResponse {
status: "200";
body: Record<string, unknown>;
}
/** Send x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request */
export interface CustomRequestIddefaultResponse extends HttpResponse {
status: "500";
body: ErrorModelOutput;
} | the_stack |
import './setup';
import { TaskQueue } from 'aurelia-task-queue';
import { Compose, ActivationStrategy } from '../src/compose';
import * as LogManager from 'aurelia-logging';
import { View } from 'aurelia-framework';
describe('Compose', () => {
let elementMock;
let containerMock;
let compositionEngineMock;
let viewSlotMock;
let viewResourcesMock;
let taskQueue: TaskQueue;
let sut: Compose;
function updateBindable(name, value) {
const oldValue = sut[name];
sut[name] = value;
if (typeof sut[`${name}Changed`] === 'function') {
sut[`${name}Changed`](value, oldValue);
}
}
function createMock() {
return { [Math.random()]: Math.random() };
}
beforeEach(() => {
sut = new Compose(
elementMock = createMock(),
containerMock = createMock(),
compositionEngineMock = jasmine.createSpyObj('compositionEnine', ['compose']),
viewSlotMock = jasmine.createSpyObj('viewSlot', ['removeAll']),
viewResourcesMock = createMock(),
taskQueue = new TaskQueue()
);
compositionEngineMock.compose.and.callFake(() => Promise.resolve());
});
describe('when created', () => {
it('caches the owning view', () => {
const owningView = {} as any as View;
sut.created(owningView);
expect(sut.owningView).toBe(owningView);
});
});
describe('when bound', () => {
it('caches the binding and override contexts', () => {
const bindingContext = {};
const overrideContext = {};
sut.bind(bindingContext, overrideContext);
expect(sut.bindingContext).toBe(bindingContext);
expect(sut.overrideContext).toBe(overrideContext);
});
// commented out waiting for future work
// it('sets "inheritBindingContext"', () => {
// const bindingContext = {};
// const overrideContext = {};
// sut.bind(bindingContext, overrideContext);
// expect(sut.inheritBindingContext).toBe(undefined);
// Compose.traverseParentScope = false;
// sut.bind(bindingContext, overrideContext);
// expect(sut.inheritBindingContext).toBe(false);
// sut.inheritBindingContext = undefined;
// Compose.traverseParentScope = true;
// sut.bind(bindingContext, overrideContext);
// expect(sut.inheritBindingContext).toBe(undefined);
// });
it('awaits ongoing update from previous lifecycle', done => {
compositionEngineMock.compose.and.stub();
// makes updates longer
compositionEngineMock.compose.and.callFake(() => new Promise(resolve => setTimeout(resolve, 600)));
// make first bind
sut.viewModel = 'some-vm';
sut.bind({}, {});
expect(sut.pendingTask).toBeDefined();
const taskFromFirstBind = sut.pendingTask;
// await some time and unbind
setTimeout(() => {
sut.unbind();
// the work from the initial bind should still be ongoing
expect(sut.pendingTask).toBe(taskFromFirstBind);
}, 100);
// do a second bind after unbinding
setTimeout(() => {
// the work from the initial bind should still be ongoing
expect(sut.pendingTask).toBe(taskFromFirstBind);
sut.viewModel = 'new-vm';
sut.model = {};
sut.bind({}, {});
// the new bind should not modify ongoing work
expect(sut.pendingTask).toBe(taskFromFirstBind);
taskFromFirstBind.then(() => {
// the initial work is done
// the scheduled changes should be processed
// there should be new ongoing work - from the processed changes
expect(sut.pendingTask).toBeDefined();
expect(sut.pendingTask).not.toBe(taskFromFirstBind);
done();
});
}, 300);
});
});
describe('when unbound', () => {
it('clears the cached binding and override contexts', () => {
const bindingContext = sut.bindingContext = {};
const overrideContext = sut.overrideContext = {};
sut.unbind();
expect(sut.bindingContext).not.toBe(bindingContext);
expect(sut.overrideContext).not.toBe(overrideContext);
});
it('clears the view', () => {
sut.unbind();
expect(viewSlotMock.removeAll).toHaveBeenCalledTimes(1);
});
it('clears any scheduled changes', () => {
const expectedChanges = Object.create(null);
sut.changes = expectedChanges;
sut.unbind();
expect(sut.changes).toBeDefined();
expect(sut.changes).not.toBe(expectedChanges);
});
});
describe('triggers composition', () => {
it('when bound', () => {
(sut as any).bind();
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
});
it('when "viewModel" changes', done => {
const viewModel = './some-view-model';
updateBindable('viewModel', viewModel);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining({ viewModel }));
done();
});
});
it('when "view" changes', done => {
const view = './some-view.html';
updateBindable('view', view);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining({ view }));
done();
});
});
it('when "model" changes and the activation-strategy is set to "replace"', done => {
const model = {};
sut.activationStrategy = ActivationStrategy.Replace;
updateBindable('model', model);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining({ model }));
done();
});
});
it('when "model" changes and the "determineActivationStrategy" hook in view-model returns "replace"', done => {
const model = {};
sut.currentViewModel = {
determineActivationStrategy() { return ActivationStrategy.Replace; }
};
updateBindable('model', model);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining({ model }));
done();
});
});
});
describe('does not trigger composition', () => {
it('when only "model" or "swapOrder" change', done => {
updateBindable('model', {});
updateBindable('swapOrder', 'after');
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).not.toHaveBeenCalled();
done();
});
});
it('when "model" changes and the "determineActivationStrategy" hook in view-model returns "invoke-lifecycle"', done => {
const model = {};
sut.currentViewModel = {
determineActivationStrategy() { return ActivationStrategy.InvokeLifecycle; }
};
updateBindable('model', model);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).not.toHaveBeenCalled();
done();
});
});
it('when "model" changes and the "determineActivationStrategy" hook is not implemented in view-model', done => {
const model = {};
sut.currentViewModel = {};
updateBindable('model', model);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).not.toHaveBeenCalled();
done();
});
});
it('when "model" changes and the activation-strategy is set to unknown value', done => {
const model = {};
sut.activationStrategy = Math.random().toString() as ActivationStrategy;
updateBindable('model', model);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).not.toHaveBeenCalled();
done();
});
});
});
it('aggregates changes from single drain of the micro task queue', done => {
const viewModel = createMock();
const view = './some-view.html';
const model = 42;
updateBindable('viewModel', viewModel);
updateBindable('model', model);
updateBindable('view', view);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining({
viewModel,
view,
model
}));
done();
});
});
describe('"model" changed handler', () => {
it('lets all other change handlers run before deciding whether there is a change requiring composition', done => { // TODO: name and position
const model = 42;
updateBindable('model', model);
updateBindable('viewModel', './some-vm');
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining({ model }));
done();
});
});
it('activates the "currentViewModel" if there is no change requiring composition', done => {
const model = 42;
sut.activationStrategy = Math.random().toString() as ActivationStrategy;
sut.currentViewModel = jasmine.createSpyObj('currentViewModelSpy', ['activate']);
updateBindable('model', model);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).not.toHaveBeenCalled();
expect(sut.currentViewModel.activate).toHaveBeenCalledTimes(1);
expect(sut.currentViewModel.activate).toHaveBeenCalledWith(model);
done();
});
});
it('activates the "currentViewModel" if the activation strategy is unknown', done => {
const model = 42;
sut.currentViewModel = jasmine.createSpyObj('currentViewModelSpy', ['activate']);
updateBindable('model', model);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).not.toHaveBeenCalled();
expect(sut.currentViewModel.activate).toHaveBeenCalledTimes(1);
expect(sut.currentViewModel.activate).toHaveBeenCalledWith(model);
done();
});
});
});
describe('does not throw when trying to activate the "currentViewModel"', () => {
it('if there is no such', done => {
const task = jasmine.createSpyObj('notToThrowTaskSpy', ['onError']);
task.call = () => {
expect(task.onError).not.toHaveBeenCalled();
done();
};
updateBindable('model', 42);
taskQueue.queueMicroTask(task);
});
it('if it does not have an ".activate" hook', done => {
const task = jasmine.createSpyObj('notToThrowTask', ['onError']);
task.call = () => {
expect(task.onError).not.toHaveBeenCalled();
done();
};
sut.currentViewModel = {};
updateBindable('model', 42);
taskQueue.queueMicroTask(task);
});
});
describe('builds "CompositionContext"', () => {
it('from all available data', done => {
sut.bindingContext = createMock();
sut.overrideContext = createMock();
sut.owningView = createMock() as any as View;
sut.currentController = createMock();
const viewModel = './some-vm';
const view = './some-view.html';
const model = 42;
const swapOrder = sut.swapOrder = 'after';
updateBindable('viewModel', viewModel);
updateBindable('view', view);
updateBindable('model', model);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining({
viewModel,
view,
model,
swapOrder,
bindingContext: sut.bindingContext,
overrideContext: sut.overrideContext,
owningView: sut.owningView,
container: containerMock,
viewSlot: viewSlotMock,
viewResources: viewResourcesMock,
currentController: sut.currentController,
host: elementMock
}));
done();
});
});
describe('when "view" changes and "viewModel" not', () => {
it('by using the view model from the last composition, if such', done => {
const view = './some-view.html';
sut.currentViewModel = createMock();
updateBindable('view', view);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining({
view,
viewModel: sut.currentViewModel
}));
done();
});
});
it('by using the "viewModel", if there is no view model from previous composition', done => {
const view = './some-view.html';
sut.viewModel = './some-view-model';
updateBindable('view', view);
taskQueue.queueMicroTask(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining({
view,
viewModel: sut.viewModel
}));
done();
});
});
});
});
it('awaits the current composition/activation before applying next set of changes', done => {
compositionEngineMock.compose.and.stub();
compositionEngineMock.compose.and.callFake(() => new Promise(resolve => setTimeout(resolve, 600)));
updateBindable('viewModel', './some-vm');
taskQueue.queueMicroTask(() => setTimeout(() => {
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
const setOne = {
model: 2,
view: './view.html'
};
const setTwo = {
model: 42,
viewModel: './truth'
};
const endSet = Object.assign({}, setOne, setTwo);
sut.pendingTask.then(() => {
expect(Object.keys(sut.changes).length).toBe(0);
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(2);
expect(compositionEngineMock.compose).toHaveBeenCalledWith(jasmine.objectContaining(endSet));
done();
});
updateBindable('model', setOne.model);
updateBindable('view', setOne.view);
setTimeout(() => {
expect(sut.changes).toEqual(jasmine.objectContaining(setOne));
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
updateBindable('model', setTwo.model);
updateBindable('viewModel', setTwo.viewModel);
}, 100);
setTimeout(() => {
expect(sut.changes).toEqual(jasmine.objectContaining(endSet));
expect(compositionEngineMock.compose).toHaveBeenCalledTimes(1);
}, 300);
}, 0));
});
describe('after successul composition', () => {
const controller = {
viewModel: createMock()
};
beforeEach(done => {
// tslint:disable-next-line:no-unused-expression
compositionEngineMock.compose.and.stub;
compositionEngineMock.compose.and.callFake(() => new Promise(resolve => setTimeout(() => resolve(controller), 20)));
updateBindable('viewModel', './some-vm');
taskQueue.queueMicroTask(done);
});
it('sets the current controller', done => {
sut.pendingTask.then(() => {
expect(sut.currentController).toBe(controller);
done();
}, done.fail);
});
it('sets the current active view model', done => {
sut.pendingTask.then(() => {
expect(sut.currentViewModel).toBe(controller.viewModel);
done();
}, done.fail);
});
it('processes pending changes', done => {
expect(sut.pendingTask).toBeTruthy();
expect(sut.changes['viewModel']).not.toBeDefined();
setTimeout(() => {
const vm = './some-other-vm';
updateBindable('viewModel', vm);
expect(sut.changes['viewModel']).toBeDefined();
sut.pendingTask.then(() => {
expect(sut.changes['viewModel']).not.toBeDefined();
return sut.pendingTask;
}).then(done).catch(done.fail);
}, 0);
});
it('clears pending composition', done => {
sut.pendingTask.then(() => {
expect(sut.pendingTask).not.toBeTruthy();
done();
}).catch(done.fail);
});
});
describe('after failing a composition', () => {
let error;
beforeEach(done => {
// tslint:disable-next-line:no-unused-expression
compositionEngineMock.compose.and.stub;
compositionEngineMock.compose.and.callFake(() => Promise.reject(error = new Error('".compose" test error')));
updateBindable('viewModel', './some-vm');
taskQueue.queueMicroTask(done);
});
it('re-throws errors', done => {
sut.pendingTask.then(() => done.fail('"pendingTask" should be rejected'), reason => {
expect(reason).toBe(error);
done();
});
});
it('completes pending composition', done => {
sut.pendingTask.then(() => done.fail('"pendingTask" should be rejected'), () => {
expect(sut.pendingTask).not.toBeTruthy();
done();
});
});
});
}); | the_stack |
import { flow, identity, pipe, Predicate, Refinement } from 'fp-ts/function'
import { bind as bind_, chainFirst as chainFirst_, Chain4 } from 'fp-ts/Chain'
import { Task } from 'fp-ts/Task'
import * as TE from 'fp-ts/TaskEither'
import * as H from '.'
import * as M from './Middleware'
import { IO } from 'fp-ts/IO'
import { IOEither } from 'fp-ts/IOEither'
import * as E from 'fp-ts/Either'
import { Monad4 } from 'fp-ts/Monad'
import { Alt4 } from 'fp-ts/Alt'
import { Bifunctor4 } from 'fp-ts/Bifunctor'
import { MonadThrow4 } from 'fp-ts/MonadThrow'
import { Functor4, bindTo as bindTo_ } from 'fp-ts/Functor'
import { Apply4, apS as apS_, apFirst as apFirst_, apSecond as apSecond_ } from 'fp-ts/Apply'
import { Applicative4 } from 'fp-ts/Applicative'
import * as RTE from 'fp-ts/ReaderTaskEither'
import { Reader } from 'fp-ts/Reader'
import {
chainEitherK as chainEitherK_,
FromEither4,
fromPredicate as fromPredicate_,
filterOrElse as filterOrElse_,
} from 'fp-ts/FromEither'
import { FromIO4, fromIOK as fromIOK_, chainIOK as chainIOK_, chainFirstIOK as chainFirstIOK_ } from 'fp-ts/FromIO'
import {
FromTask4,
fromTaskK as fromTaskK_,
chainTaskK as chainTaskK_,
chainFirstTaskK as chainFirstTaskK_,
} from 'fp-ts/FromTask'
/**
* @category instances
* @since 0.6.3
*/
export const URI = 'ReaderMiddleware'
/**
* @category instances
* @since 0.6.3
*/
export type URI = typeof URI
declare module 'fp-ts/HKT' {
interface URItoKind4<S, R, E, A> {
readonly [URI]: ReaderMiddleware<S, R, R, E, A>
}
}
/**
* @category model
* @since 0.6.3
*/
export interface ReaderMiddleware<R, I, O, E, A> {
(r: R): M.Middleware<I, O, E, A>
}
/**
* @category constructors
* @since 0.6.3
*/
export function fromTaskEither<R, I = H.StatusOpen, E = never, A = never>(
fa: TE.TaskEither<E, A>
): ReaderMiddleware<R, I, I, E, A> {
return () => M.fromTaskEither(fa)
}
/**
* @category constructors
* @since 0.6.3
*/
export function fromReaderTaskEither<R, I = H.StatusOpen, E = never, A = never>(
fa: RTE.ReaderTaskEither<R, E, A>
): ReaderMiddleware<R, I, I, E, A> {
return (r) => M.fromTaskEither(fa(r))
}
/**
* @category constructors
* @since 0.6.3
*/
export const fromMiddleware =
<R, I = H.StatusOpen, O = I, E = never, A = never>(fa: M.Middleware<I, O, E, A>): ReaderMiddleware<R, I, O, E, A> =>
() =>
fa
/**
* @category constructor
* @since 0.7.0
*/
export function gets<R, I = H.StatusOpen, E = never, A = never>(
f: (c: H.Connection<I>) => A
): ReaderMiddleware<R, I, I, E, A> {
return fromMiddleware(M.gets(f))
}
/**
* @category constructor
* @since 0.7.0
*/
export function fromConnection<R, I = H.StatusOpen, E = never, A = never>(
f: (c: H.Connection<I>) => E.Either<E, A>
): ReaderMiddleware<R, I, I, E, A> {
return fromMiddleware(M.fromConnection(f))
}
/**
* @category constructor
* @since 0.7.0
*/
export function modifyConnection<R, I, O, E>(
f: (c: H.Connection<I>) => H.Connection<O>
): ReaderMiddleware<R, I, O, E, void> {
return fromMiddleware(M.modifyConnection(f))
}
/**
* @category constructors
* @since 0.6.3
*/
export function right<R, I = H.StatusOpen, E = never, A = never>(a: A): ReaderMiddleware<R, I, I, E, A> {
return fromMiddleware(M.right(a))
}
/**
* @category constructors
* @since 0.6.3
*/
export function left<R, I = H.StatusOpen, E = never, A = never>(e: E): ReaderMiddleware<R, I, I, E, A> {
return fromMiddleware(M.left(e))
}
/**
* @category constructors
* @since 0.6.3
*/
export function rightTask<R, I = H.StatusOpen, E = never, A = never>(fa: Task<A>): ReaderMiddleware<R, I, I, E, A> {
return fromMiddleware(M.rightTask(fa))
}
/**
* @category constructors
* @since 0.6.3
*/
export function leftTask<R, I = H.StatusOpen, E = never, A = never>(te: Task<E>): ReaderMiddleware<R, I, I, E, A> {
return fromMiddleware(M.leftTask(te))
}
/**
* @category constructors
* @since 0.6.3
*/
export function rightIO<R, I = H.StatusOpen, E = never, A = never>(fa: IO<A>): ReaderMiddleware<R, I, I, E, A> {
return fromMiddleware(M.rightIO(fa))
}
/**
* @category constructors
* @since 0.6.3
*/
export function leftIO<R, I = H.StatusOpen, E = never, A = never>(fe: IO<E>): ReaderMiddleware<R, I, I, E, A> {
return fromMiddleware(M.leftIO(fe))
}
/**
* @category constructors
* @since 0.7.0
*/
export const fromEither = <R, I = H.StatusOpen, E = never, A = never>(
e: E.Either<E, A>
): ReaderMiddleware<R, I, I, E, A> => fromMiddleware(M.fromEither(e))
/**
* @category constructors
* @since 0.6.3
*/
export function fromIOEither<R, I = H.StatusOpen, E = never, A = never>(
fa: IOEither<E, A>
): ReaderMiddleware<R, I, I, E, A> {
return fromMiddleware(M.fromIOEither(fa))
}
/**
* @category constructors
* @since 0.6.3
*/
export const rightReader =
<R, I = H.StatusOpen, E = never, A = never>(ma: Reader<R, A>): ReaderMiddleware<R, I, I, E, A> =>
(r) =>
M.right(ma(r))
/**
* @category constructors
* @since 0.6.3
*/
export function leftReader<R, I = H.StatusOpen, E = never, A = never>(
me: Reader<R, E>
): ReaderMiddleware<R, I, I, E, A> {
return (r) => M.left(me(r))
}
/**
* @category constructors
* @since 0.6.3
*/
export const ask = <R, I = H.StatusOpen, E = never>(): ReaderMiddleware<R, I, I, E, R> => M.right
/**
* @category constructors
* @since 0.6.3
*/
export const asks = <R, E = never, A = never>(f: (r: R) => A): ReaderMiddleware<R, H.StatusOpen, H.StatusOpen, E, A> =>
flow(f, M.right)
/**
* @category combinators
* @since 0.6.3
*/
export function orElse<R, E, I, O, M, A>(
f: (e: E) => ReaderMiddleware<R, I, O, M, A>
): (ma: ReaderMiddleware<R, I, O, E, A>) => ReaderMiddleware<R, I, O, M, A> {
return (ma) => (r) => (c) =>
pipe(
ma(r)(c),
TE.orElse((e) => f(e)(r)(c))
)
}
/**
* @category combinators
* @since 0.6.4
*/
export const orElseW =
<R2, E, I, O, M, A>(f: (e: E) => ReaderMiddleware<R2, I, O, M, A>) =>
<R1, B>(ma: ReaderMiddleware<R1, I, O, E, B>): ReaderMiddleware<R2 & R1, I, O, M, A | B> =>
pipe(ma, orElse<R1 & R2, E, I, O, M, A | B>(f))
/**
* @category constructors
* @since 0.6.3
*/
export function status<R, E = never>(status: H.Status): ReaderMiddleware<R, H.StatusOpen, H.HeadersOpen, E, void> {
return () => M.status(status)
}
/**
* @category constructors
* @since 0.6.3
*/
export function header<R, E = never>(
name: string,
value: string
): ReaderMiddleware<R, H.HeadersOpen, H.HeadersOpen, E, void> {
return () => M.header(name, value)
}
/**
* @category constructors
* @since 0.6.3
*/
export function contentType<R, E = never>(
mediaType: H.MediaType
): ReaderMiddleware<R, H.HeadersOpen, H.HeadersOpen, E, void> {
return header('Content-Type', mediaType)
}
/**
* @category constructors
* @since 0.6.3
*/
export function cookie<R, E = never>(
name: string,
value: string,
options: H.CookieOptions
): ReaderMiddleware<R, H.HeadersOpen, H.HeadersOpen, E, void> {
return () => M.cookie(name, value, options)
}
/**
* @category constructors
* @since 0.6.3
*/
export function clearCookie<R, E = never>(
name: string,
options: H.CookieOptions
): ReaderMiddleware<R, H.HeadersOpen, H.HeadersOpen, E, void> {
return () => M.clearCookie(name, options)
}
const closedHeaders: ReaderMiddleware<any, H.HeadersOpen, H.BodyOpen, never, void> = iof(undefined)
/**
* @category constructors
* @since 0.6.3
*/
export function closeHeaders<R, E = never>(): ReaderMiddleware<R, H.HeadersOpen, H.BodyOpen, E, void> {
return closedHeaders
}
/**
* @category constructors
* @since 0.6.3
*/
export function send<R, E = never>(body: string): ReaderMiddleware<R, H.BodyOpen, H.ResponseEnded, E, void> {
return () => M.send(body)
}
/**
* @category constructors
* @since 0.6.3
*/
export function end<R, E = never>(): ReaderMiddleware<R, H.BodyOpen, H.ResponseEnded, E, void> {
return M.end
}
/**
* @category constructors
* @since 0.6.3
*/
export function json<R, E>(
body: unknown,
onError: (reason: unknown) => E
): ReaderMiddleware<R, H.HeadersOpen, H.ResponseEnded, E, void> {
return () => M.json(body, onError)
}
/**
* @category constructors
* @since 0.6.3
*/
export function redirect<R, E = never>(uri: string): ReaderMiddleware<R, H.StatusOpen, H.HeadersOpen, E, void> {
return () => M.redirect(uri)
}
/**
* @category constructors
* @since 0.6.3
*/
export function decodeParam<R, E, A>(
name: string,
f: (input: unknown) => E.Either<E, A>
): ReaderMiddleware<R, H.StatusOpen, H.StatusOpen, E, A> {
return () => M.decodeParam(name, f)
}
/**
* @category constructors
* @since 0.6.3
*/
export function decodeParams<R, E, A>(
f: (input: unknown) => E.Either<E, A>
): ReaderMiddleware<R, H.StatusOpen, H.StatusOpen, E, A> {
return () => M.decodeParams(f)
}
/**
* @category constructors
* @since 0.6.3
*/
export function decodeQuery<R, E, A>(
f: (input: unknown) => E.Either<E, A>
): ReaderMiddleware<R, H.StatusOpen, H.StatusOpen, E, A> {
return () => M.decodeQuery(f)
}
/**
* @category constructors
* @since 0.6.3
*/
export function decodeBody<R, E, A>(
f: (input: unknown) => E.Either<E, A>
): ReaderMiddleware<R, H.StatusOpen, H.StatusOpen, E, A> {
return () => M.decodeBody(f)
}
/**
* @category constructors
* @since 0.6.3
*/
export function decodeMethod<R, E, A>(
f: (method: string) => E.Either<E, A>
): ReaderMiddleware<R, H.StatusOpen, H.StatusOpen, E, A> {
return () => M.decodeMethod(f)
}
/**
* @category constructors
* @since 0.6.3
*/
export function decodeHeader<R, E, A>(
name: string,
f: (input: unknown) => E.Either<E, A>
): ReaderMiddleware<R, H.StatusOpen, H.StatusOpen, E, A> {
return () => M.decodeHeader(name, f)
}
const _map: Functor4<URI>['map'] = (fa, f) => (r) => pipe(fa(r), M.map(f))
const _apPar: Monad4<URI>['ap'] = (fab, fa) => pipe(fab, ap(fa))
const _apSeq: Apply4<URI>['ap'] = (fab, fa) => _chain(fab, (f) => _map(fa, (a) => f(a)))
const _chain: Monad4<URI>['chain'] = (ma, f) => (r) =>
pipe(
ma(r),
M.chain((a) => f(a)(r))
)
const _alt: Alt4<URI>['alt'] = (fx, f) => (r) => (c) =>
pipe(
fx(r)(c),
TE.alt(() => f()(r)(c))
)
const _bimap: Bifunctor4<URI>['bimap'] = (fea, f, g) => (r) => (c) =>
pipe(
fea(r)(c),
TE.bimap(f, ([a, c]) => [g(a), c])
)
const _mapLeft: Bifunctor4<URI>['mapLeft'] = (fea, f) => (r) => (c) => pipe(fea(r)(c), TE.mapLeft(f))
/**
* `map` can be used to turn functions `(a: A) => B` into functions `(fa: F<A>) => F<B>` whose argument and return types
* use the type constructor `F` to represent some computational context.
*
* @category Functor
* @since 0.6.3
*/
export const map =
<A, B>(f: (a: A) => B) =>
<R, I, E>(fa: ReaderMiddleware<R, I, I, E, A>): ReaderMiddleware<R, I, I, E, B> =>
_map(fa, f)
/**
* Indexed version of [`map`](#map).
*
* @category IxFunctor
* @since 0.7.0
*/
export const imap =
<A, B>(f: (a: A) => B) =>
<R, I, O, E>(fa: ReaderMiddleware<R, I, O, E, A>): ReaderMiddleware<R, I, O, E, B> =>
(r) =>
pipe(fa(r), M.imap(f))
/**
* Map a pair of functions over the two last type arguments of the bifunctor.
*
* @category Bifunctor
* @since 0.6.3
*/
export const bimap =
<E, G, A, B>(f: (e: E) => G, g: (a: A) => B) =>
<R, I>(fa: ReaderMiddleware<R, I, I, E, A>): ReaderMiddleware<R, I, I, G, B> =>
_bimap(fa, f, g)
/**
* Map a function over the second type argument of a bifunctor.
*
* @category Bifunctor
* @since 0.6.3
*/
export const mapLeft =
<E, G>(f: (e: E) => G) =>
<R, I, A>(fa: ReaderMiddleware<R, I, I, E, A>): ReaderMiddleware<R, I, I, G, A> =>
_mapLeft(fa, f)
/**
* Apply a function to an argument under a type constructor.
*
* @category Apply
* @since 0.6.3
*/
export const ap =
<R, I, E, A>(fa: ReaderMiddleware<R, I, I, E, A>) =>
<B>(fab: ReaderMiddleware<R, I, I, E, (a: A) => B>): ReaderMiddleware<R, I, I, E, B> =>
(r) =>
pipe(fab(r), M.ap(fa(r)))
/**
* Less strict version of [`ap`](#ap).
*
* @category Apply
* @since 0.6.3
*/
export const apW: <R2, I, E2, A>(
fa: ReaderMiddleware<R2, I, I, E2, A>
) => <R1, E1, B>(fab: ReaderMiddleware<R1, I, I, E1, (a: A) => B>) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, B> =
ap as any
/**
* @category Pointed
* @since 0.6.3
*/
export const of: <R, I = H.StatusOpen, E = never, A = never>(a: A) => ReaderMiddleware<R, I, I, E, A> = right
/**
* @category Pointed
* @since 0.6.3
*/
export function iof<R, I = H.StatusOpen, O = H.StatusOpen, E = never, A = never>(
a: A
): ReaderMiddleware<R, I, O, E, A> {
return () => M.iof(a)
}
/**
* Composes computations in sequence, using the return value of one computation to determine the next computation.
*
* @category Monad
* @since 0.6.3
*/
export const chain =
<R, I, E, A, B>(f: (a: A) => ReaderMiddleware<R, I, I, E, B>) =>
(ma: ReaderMiddleware<R, I, I, E, A>): ReaderMiddleware<R, I, I, E, B> =>
_chain(ma, f)
/**
* Less strict version of [`chain`](#chain).
*
* @category Monad
* @since 0.6.3
*/
export const chainW: <R2, I, E2, A, B>(
f: (a: A) => ReaderMiddleware<R2, I, I, E2, B>
) => <R1, E1>(ma: ReaderMiddleware<R1, I, I, E1, A>) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, B> = chain as any
/**
* Less strict version of [`flatten`](#flatten).
*
* @category combinators
* @since 0.7.2
*/
export const flattenW: <R1, I, E1, R2, E2, A>(
mma: ReaderMiddleware<R1, I, I, E1, ReaderMiddleware<R2, I, I, E2, A>>
) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, A> = chainW(identity)
/**
* Derivable from `Chain`.
*
* @category combinators
* @since 0.7.2
*/
export const flatten: <R, I, E, A>(
mma: ReaderMiddleware<R, I, I, E, ReaderMiddleware<R, I, I, E, A>>
) => ReaderMiddleware<R, I, I, E, A> = flattenW
/**
* Indexed version of [`chain`](#chain).
*
* @category IxMonad
* @since 0.6.3
*/
export const ichain: <R, A, O, Z, E, B>(
f: (a: A) => ReaderMiddleware<R, O, Z, E, B>
) => <I>(ma: ReaderMiddleware<R, I, O, E, A>) => ReaderMiddleware<R, I, Z, E, B> = ichainW
/**
* Less strict version of [`ichain`](#ichain).
*
* @category IxMonad
* @since 0.6.3
*/
export function ichainW<R2, A, O, Z, E2, B>(
f: (a: A) => ReaderMiddleware<R2, O, Z, E2, B>
): <R1, I, E1>(ma: ReaderMiddleware<R1, I, O, E1, A>) => ReaderMiddleware<R1 & R2, I, Z, E1 | E2, B> {
return (ma) => (r) => (ci) =>
pipe(
ma(r)(ci),
TE.chainW(([a, co]) => f(a)(r)(co))
)
}
/**
* Less strict version of [`iflatten`](#iflatten).
*
* @category combinators
* @since 0.7.2
*/
export const iflattenW: <R1, I, O, Z, E1, R2, E2, A>(
mma: ReaderMiddleware<R1, I, O, E1, ReaderMiddleware<R2, O, Z, E2, A>>
) => ReaderMiddleware<R1 & R2, I, Z, E1 | E2, A> = ichainW(identity)
/**
* Derivable from indexed version of `Chain`.
*
* @category combinators
* @since 0.7.2
*/
export const iflatten: <R, I, O, Z, E, A>(
mma: ReaderMiddleware<R, I, O, E, ReaderMiddleware<R, O, Z, E, A>>
) => ReaderMiddleware<R, I, Z, E, A> = iflattenW
/**
* @category combinators
* @since 0.6.3
*/
export const chainMiddlewareK =
<R, I, E, A, B>(f: (a: A) => M.Middleware<I, I, E, B>) =>
(ma: ReaderMiddleware<R, I, I, E, A>): ReaderMiddleware<R, I, I, E, B> =>
pipe(
ma,
chain((a) => fromMiddleware(f(a)))
)
/**
* @category combinators
* @since 0.6.3
*/
export const ichainMiddlewareK: <R, A, O, Z, E, B>(
f: (a: A) => M.Middleware<O, Z, E, B>
) => <I>(ma: ReaderMiddleware<R, I, O, E, A>) => ReaderMiddleware<R, I, Z, E, B> = chainMiddlewareK as any
/**
* @category combinators
* @since 0.6.5
*/
export const ichainMiddlewareKW: <R, A, O, Z, E, B>(
f: (a: A) => M.Middleware<O, Z, E, B>
) => <I, D>(ma: ReaderMiddleware<R, I, O, D, A>) => ReaderMiddleware<R, I, Z, D | E, B> = chainMiddlewareK as any
/**
* @category combinators
* @since 0.6.3
*/
export const chainTaskEitherK: <E, A, B>(
f: (a: A) => TE.TaskEither<E, B>
) => <R, I>(ma: ReaderMiddleware<R, I, I, E, A>) => ReaderMiddleware<R, I, I, E, B> = (f) => (ma) => (r) =>
pipe(
ma(r),
M.chain((a) => M.fromTaskEither(f(a)))
)
/**
* @category combinators
* @since 0.6.3
*/
export const chainTaskEitherKW: <E2, A, B>(
f: (a: A) => TE.TaskEither<E2, B>
) => <R, I, E1>(ma: ReaderMiddleware<R, I, I, E1, A>) => ReaderMiddleware<R, I, I, E1 | E2, B> = chainTaskEitherK as any
/**
* @category combinators
* @since 0.6.3
*/
export const chainReaderTaskEitherK: <R, E, A, B>(
f: (a: A) => RTE.ReaderTaskEither<R, E, B>
) => <I>(ma: ReaderMiddleware<R, I, I, E, A>) => ReaderMiddleware<R, I, I, E, B> = (f) => (ma) => (r) =>
pipe(
ma(r),
M.chain((a) => M.fromTaskEither(f(a)(r)))
)
/**
* @category combinators
* @since 0.6.3
*/
export const chainReaderTaskEitherKW: <R2, E2, A, B>(
f: (a: A) => RTE.ReaderTaskEither<R2, E2, B>
) => <R1, I, E1>(ma: ReaderMiddleware<R1, I, I, E1, A>) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, B> =
chainReaderTaskEitherK as any
/**
* Less strict version of [`chainFirstReaderTaskEitherK`](#chainfirstreadertaskeitherk).
*
* @category combinators
* @since 0.7.0
*/
export const chainFirstReaderTaskEitherKW: <R2, E2, A, B>(
f: (a: A) => RTE.ReaderTaskEither<R2, E2, B>
) => <R1, I, E1>(ma: ReaderMiddleware<R1, I, I, E1, A>) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, A> = (f) =>
chainFirstW((a) => fromReaderTaskEither(f(a)))
/**
* @category combinators
* @since 0.7.0
*/
export const chainFirstReaderTaskEitherK: <R, E, A, B>(
f: (a: A) => RTE.ReaderTaskEither<R, E, B>
) => <I>(ma: ReaderMiddleware<R, I, I, E, A>) => ReaderMiddleware<R, I, I, E, A> = chainFirstReaderTaskEitherKW
/**
* @category instances
* @since 0.6.3
*/
export const Functor: Functor4<URI> = {
URI,
map: _map,
}
/**
* @category instances
* @since 0.7.0
*/
export const ApplyPar: Apply4<URI> = {
...Functor,
ap: _apPar,
}
/**
* @category instances
* @since 0.7.0
*/
export const ApplySeq: Apply4<URI> = {
...Functor,
ap: _apSeq,
}
/**
* Use [`ApplySeq`](./ReaderMiddleware.ts.html#ApplySeq) instead.
*
* @category instances
* @since 0.6.3
* @deprecated
*/
export const Apply: Apply4<URI> = ApplySeq
/**
* @category instances
* @since 0.7.0
*/
export const ApplicativePar: Applicative4<URI> = {
...ApplyPar,
of,
}
/**
* @category instances
* @since 0.7.0
*/
export const ApplicativeSeq: Applicative4<URI> = {
...ApplySeq,
of,
}
/**
* Use [`ApplicativeSeq`](./ReaderMiddleware.ts.html#ApplicativeSeq) instead.
*
* @category instances
* @since 0.6.3
* @deprecated
*/
export const Applicative: Applicative4<URI> = ApplicativeSeq
/**
* @category instances
* @since 0.7.0
*/
export const Chain: Chain4<URI> = {
...ApplyPar,
chain: _chain,
}
/**
* @category instances
* @since 0.6.3
*/
export const Monad: Monad4<URI> = {
...ApplicativeSeq,
chain: _chain,
}
/**
* @category instances
* @since 0.6.3
*/
export const MonadThrow: MonadThrow4<URI> = {
...Monad,
throwError: left,
}
/**
* @category instances
* @since 0.6.3
*/
export const Alt: Alt4<URI> = {
...Functor,
alt: _alt,
}
/**
* @category instances
* @since 0.6.3
*/
export const Bifunctor: Bifunctor4<URI> = {
URI,
bimap: _bimap,
mapLeft: _mapLeft,
}
/**
* @category instances
* @since 0.7.0
*/
export const FromEither: FromEither4<URI> = {
URI,
fromEither,
}
/**
* @category combinators
* @since 0.7.0
*/
export const apFirst = apFirst_(ApplyPar)
/**
* Less strict version of [`apFirst`](#apfirst).
*
* @category combinators
* @since 0.7.1
*/
export const apFirstW: <R2, I, E2, B>(
second: ReaderMiddleware<R2, I, I, E2, B>
) => <R1, E1, A>(first: ReaderMiddleware<R1, I, I, E1, A>) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, A> =
apFirst as any
/**
* @category combinators
* @since 0.7.0
*/
export const apSecond = apSecond_(ApplyPar)
/**
* Less strict version of [`apSecond`](#apsecond).
*
* @category combinators
* @since 0.7.1
*/
export const apSecondW: <R2, I, E2, B>(
second: ReaderMiddleware<R2, I, I, E2, B>
) => <R1, E1, A>(first: ReaderMiddleware<R1, I, I, E1, A>) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, B> =
apSecond as any
/**
* Composes computations in sequence, using the return value of one computation to determine
* the next computation and keeping only the result of the first.
*
* Derivable from `Chain`.
*
* @category combinators
* @since 0.7.0
*/
export const chainFirst: <R, I, E, A, B>(
f: (a: A) => ReaderMiddleware<R, I, I, E, B>
) => (ma: ReaderMiddleware<R, I, I, E, A>) => ReaderMiddleware<R, I, I, E, A> = chainFirst_(Chain)
/**
* Less strict version of [`chainFirst`](#chainfirst).
*
* Derivable from `Chain`.
*
* @category combinators
* @since 0.7.0
*/
export const chainFirstW: <R2, I, E2, A, B>(
f: (a: A) => ReaderMiddleware<R2, I, I, E2, B>
) => <R1, E1>(ma: ReaderMiddleware<R1, I, I, E1, A>) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, A> = chainFirst as any
/**
* @category constructors
* @since 0.7.0
*/
export const fromPredicate: {
<E, A, B extends A>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <R, I>(
a: A
) => ReaderMiddleware<R, I, I, E, B>
<E, A>(predicate: Predicate<A>, onFalse: (a: A) => E): <R, I>(a: A) => ReaderMiddleware<R, I, I, E, A>
} = fromPredicate_(FromEither)
/**
* @category combinators
* @since 0.7.0
*/
export const filterOrElse: {
<E, A, B extends A>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <R, I>(
ma: ReaderMiddleware<R, I, I, E, A>
) => ReaderMiddleware<R, I, I, E, B>
<E, A>(predicate: Predicate<A>, onFalse: (a: A) => E): <R, I>(
ma: ReaderMiddleware<R, I, I, E, A>
) => ReaderMiddleware<R, I, I, E, A>
} = filterOrElse_(FromEither, Chain)
/**
* Less strict version of [`filterOrElse`](#filterorelse).
*
* @category combinators
* @since 0.7.0
*/
export const filterOrElseW: {
<A, B extends A, E2>(refinement: Refinement<A, B>, onFalse: (a: A) => E2): <R, I, E1>(
ma: ReaderMiddleware<R, I, I, E1, A>
) => ReaderMiddleware<R, I, I, E1 | E2, B>
<A, E2>(predicate: Predicate<A>, onFalse: (a: A) => E2): <R, I, E1>(
ma: ReaderMiddleware<R, I, I, E1, A>
) => ReaderMiddleware<R, I, I, E1 | E2, A>
} = filterOrElse
/**
* @category combinators
* @since 0.7.0
*/
export const chainEitherK: <E, A, B>(
f: (a: A) => E.Either<E, B>
) => <R, I>(ma: ReaderMiddleware<R, I, I, E, A>) => ReaderMiddleware<R, I, I, E, B> = chainEitherK_(FromEither, Chain)
/**
* Less strict version of [`chainEitherK`](#chaineitherk).
*
* @category combinators
* @since 0.7.0
*/
export const chainEitherKW: <E2, A, B>(
f: (a: A) => E.Either<E2, B>
) => <R, I, E1>(ma: ReaderMiddleware<R, I, I, E1, A>) => ReaderMiddleware<R, I, I, E1 | E2, B> = chainEitherK as any
/**
* @category constructors
* @since 0.7.0
*/
export const fromIO: FromIO4<URI>['fromIO'] = rightIO
/**
* @category instances
* @since 0.7.0
*/
export const FromIO: FromIO4<URI> = {
URI,
fromIO,
}
/**
* @category combinators
* @since 0.7.0
*/
export const fromIOK = fromIOK_(FromIO)
/**
* @category combinators
* @since 0.7.0
*/
export const chainIOK = chainIOK_(FromIO, Chain)
/**
* @category combinators
* @since 0.7.0
*/
export const chainFirstIOK = chainFirstIOK_(FromIO, Chain)
/**
* @category constructors
* @since 0.7.0
*/
export const fromTask: FromTask4<URI>['fromTask'] = rightTask
/**
* @category instances
* @since 0.7.0
*/
export const FromTask: FromTask4<URI> = {
...FromIO,
fromTask,
}
/**
* @category combinators
* @since 0.7.0
*/
export const fromTaskK = fromTaskK_(FromTask)
/**
* @category combinators
* @since 0.7.0
*/
export const chainTaskK = chainTaskK_(FromTask, Chain)
/**
* @category combinators
* @since 0.7.0
*/
export const chainFirstTaskK = chainFirstTaskK_(FromTask, Chain)
/**
* Less strict version of [`chainFirstTaskEitherK`](#chainfirsttaskeitherk).
*
* @category combinators
* @since 0.7.0
*/
export const chainFirstTaskEitherKW: <E2, A, B>(
f: (a: A) => TE.TaskEither<E2, B>
) => <R, I, E1>(ma: ReaderMiddleware<R, I, I, E1, A>) => ReaderMiddleware<R, I, I, E1 | E2, A> = (f) =>
chainFirstW((a) => fromTaskEither(f(a)))
/**
* @category combinators
* @since 0.7.0
*/
export const chainFirstTaskEitherK: <E, A, B>(
f: (a: A) => TE.TaskEither<E, B>
) => <R, I>(ma: ReaderMiddleware<R, I, I, E, A>) => ReaderMiddleware<R, I, I, E, A> = chainFirstTaskEitherKW
/**
* Phantom type can't be infered properly, use [`bindTo`](#bindto) instead.
*
* @since 0.6.3
* @deprecated
*/
export const Do = iof<unknown, unknown, unknown, never, {}>({})
/**
* @since 0.6.3
*/
export const bindTo = bindTo_(Functor)
/**
* Indexed version of [`bindTo`](#bindto).
*
* @since 0.7.0
*/
export const ibindTo: <N extends string>(
name: N
) => <R, I, O, E, A>(fa: ReaderMiddleware<R, I, O, E, A>) => ReaderMiddleware<R, I, O, E, { readonly [K in N]: A }> =
bindTo as any
/**
* @since 0.6.3
*/
export const bind = bind_(Chain)
/**
* @since 0.6.3
*/
export const bindW: <N extends string, R2, I, A, E2, B>(
name: Exclude<N, keyof A>,
f: (a: A) => ReaderMiddleware<R2, I, I, E2, B>
) => <R1, E1>(
fa: ReaderMiddleware<R1, I, I, E1, A>
) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, { [K in keyof A | N]: K extends keyof A ? A[K] : B }> = bind as any
/**
* Less strict version of [`ibind`](#ibind).
*
* @since 0.7.0
*/
export const ibindW: <N extends string, A, R2, O, Z, E2, B>(
name: Exclude<N, keyof A>,
f: (a: A) => ReaderMiddleware<R2, O, Z, E2, B>
) => <R1, I, E1>(
ma: ReaderMiddleware<R1, I, O, E1, A>
) => ReaderMiddleware<R1 & R2, I, Z, E1 | E2, { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> =
bindW as any
/**
* @since 0.7.0
*/
export const ibind: <N extends string, A, R, O, Z, E, B>(
name: Exclude<N, keyof A>,
f: (a: A) => ReaderMiddleware<R, O, Z, E, B>
) => <I>(
ma: ReaderMiddleware<R, I, O, E, A>
) => ReaderMiddleware<R, I, Z, E, { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> = ibindW
/**
* @since 0.7.0
*/
export const apS = apS_(ApplyPar)
/**
* Less strict version of [`apS`](#aps).
*
* @since 0.7.0
*/
export const apSW: <N extends string, A, I, R2, E2, B>(
name: Exclude<N, keyof A>,
fb: ReaderMiddleware<R2, I, I, E2, B>
) => <R1, E1>(
fa: ReaderMiddleware<R1, I, I, E1, A>
) => ReaderMiddleware<R1 & R2, I, I, E1 | E2, { readonly [K in keyof A | N]: K extends keyof A ? A[K] : B }> =
apS as any
/**
* Less strict version of [`iapS`](#iaps).
*
* @since 0.7.0
*/
export const iapSW: <N extends string, A, R2, I, O, E2, B>(
name: Exclude<N, keyof A>,
fb: ReaderMiddleware<R2, I, O, E2, B>
) => <R1, E1>(
fa: ReaderMiddleware<R1, I, O, E1, A>
) => ReaderMiddleware<R1 & R2, I, O, E1 | E2, { readonly [K in keyof A | N]: K extends keyof A ? A[K] : B }> =
apS as any
/**
* @since 0.7.0
*/
export const iapS: <N extends string, A, R, I, O, E, B>(
name: Exclude<N, keyof A>,
fb: ReaderMiddleware<R, I, O, E, B>
) => (
fa: ReaderMiddleware<R, I, O, E, A>
) => ReaderMiddleware<R, I, O, E, { readonly [K in N | keyof A]: K extends keyof A ? A[K] : B }> = iapSW | the_stack |
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
jest.mock('fbjs/lib/warning', () => {
const f: any = jest.fn();
f.default = jest.fn();
return f;
});
const unsubscribe = jest.fn();
jest.doMock('relay-runtime', () => {
const originalRuntime = jest.requireActual('relay-runtime');
const originalInternal = originalRuntime.__internal;
return {
...originalRuntime,
__internal: {
...originalInternal,
fetchQuery: (...args) => {
const observable = originalInternal.fetchQuery(...args);
return {
subscribe: (observer) => {
return observable.subscribe({
...observer,
start: (originalSubscription) => {
const observerStart = observer?.start;
observerStart &&
observerStart({
...originalSubscription,
unsubscribe: () => {
originalSubscription.unsubscribe();
unsubscribe();
},
});
},
});
},
};
},
},
};
});
import * as invariant from 'fbjs/lib/invariant';
import * as React from 'react';
import { useMemo, useState } from 'react';
import * as TestRenderer from 'react-test-renderer';
import { OperationDescriptor, Variables } from 'relay-runtime';
import {
ConnectionHandler,
FRAGMENT_OWNER_KEY,
FRAGMENTS_KEY,
ID_KEY,
createOperationDescriptor,
} from 'relay-runtime';
import { ReactRelayContext, usePaginationFragment as usePaginationFragmentOriginal } from '../src';
const warning = require('fbjs/lib/warning');
type Direction = 'forward' | 'backward';
describe('usePaginationFragment', () => {
let environment;
let initialUser;
let gqlQuery;
let gqlQueryNestedFragment;
let gqlQueryWithoutID;
let gqlQueryWithLiteralArgs;
let gqlQueryWithStreaming;
let gqlPaginationQuery;
let gqlPaginationQueryWithStreaming;
let gqlFragment;
let gqlFragmentWithStreaming;
let query;
let queryNestedFragment;
let queryWithoutID;
let queryWithLiteralArgs;
let queryWithStreaming;
let paginationQuery;
let variables;
let variablesNestedFragment;
let variablesWithoutID;
let setEnvironment;
let setOwner;
let renderFragment;
let renderSpy;
let createMockEnvironment;
let generateAndCompile;
let loadNext;
let refetch;
let Renderer;
class ErrorBoundary extends React.Component<any, any> {
state = { error: null };
componentDidCatch(error) {
this.setState({ error });
}
render() {
const { children, fallback } = this.props;
const { error } = this.state;
if (error) {
return React.createElement(fallback, { error });
}
return children;
}
}
function usePaginationFragment(fragmentNode, fragmentRef) {
const { data, ...result } = usePaginationFragmentOriginal(fragmentNode, fragmentRef);
loadNext = result.loadNext;
refetch = result.refetch;
renderSpy(data, result);
return { data, ...result };
}
function assertCall(expected, idx) {
const actualData = renderSpy.mock.calls[idx][0];
const actualResult = renderSpy.mock.calls[idx][1];
const actualIsLoadingNext = actualResult.isLoadingNext;
const actualIsLoadingPrevious = actualResult.isLoadingPrevious;
const actualHasNext = actualResult.hasNext;
const actualHasPrevious = actualResult.hasPrevious;
const actualErrorNext = actualResult.errorNext;
expect(actualData).toEqual(expected.data);
expect(actualIsLoadingNext).toEqual(expected.isLoadingNext);
expect(actualIsLoadingPrevious).toEqual(expected.isLoadingPrevious);
expect(actualHasNext).toEqual(expected.hasNext);
expect(actualHasPrevious).toEqual(expected.hasPrevious);
expected.errorNext && expect(actualErrorNext).toEqual(expected.errorNext);
}
function expectFragmentResults(
expectedCalls: ReadonlyArray<{
data: any;
isLoadingNext: boolean;
isLoadingPrevious: boolean;
hasNext: boolean;
hasPrevious: boolean;
errorNext?: Error | null;
}>,
) {
// This ensures that useEffect runs
TestRenderer.act(() => jest.runAllImmediates());
expect(renderSpy).toBeCalledTimes(expectedCalls.length);
expectedCalls.forEach((expected, idx) => assertCall(expected, idx));
renderSpy.mockClear();
}
function createFragmentRef(id, owner) {
return {
[ID_KEY]: id,
[FRAGMENTS_KEY]: {
NestedUserFragment: {},
},
[FRAGMENT_OWNER_KEY]: owner.request,
};
}
beforeEach(() => {
// Set up mocks
jest.resetModules();
jest.spyOn(console, 'warn').mockImplementationOnce(() => {});
renderSpy = jest.fn();
({ generateAndCompile } = require('./TestCompiler'));
({ createMockEnvironment } = require('relay-test-utils-internal'));
// Set up environment and base data
environment = createMockEnvironment({
handlerProvider: () => ConnectionHandler,
});
const generated = generateAndCompile(
`
fragment NestedUserFragment on User {
username
}
fragment UserFragment on User
@refetchable(queryName: "UserFragmentPaginationQuery")
@argumentDefinitions(
isViewerFriendLocal: {type: "Boolean", defaultValue: false}
orderby: {type: "[String]"}
scale: {type: "Float"}
) {
id
name
friends(
after: $after,
first: $first,
before: $before,
last: $last,
orderby: $orderby,
isViewerFriend: $isViewerFriendLocal
scale: $scale
) @connection(key: "UserFragment_friends", filters: ["orderby", "isViewerFriend"]) {
edges {
node {
id
name
...NestedUserFragment
}
}
}
}
fragment UserFragmentWithStreaming on User
@refetchable(queryName: "UserFragmentStreamingPaginationQuery")
@argumentDefinitions(
isViewerFriendLocal: {type: "Boolean", defaultValue: false}
orderby: {type: "[String]"}
scale: {type: "Float"}
) {
id
name
friends(
after: $after,
first: $first,
before: $before,
last: $last,
orderby: $orderby,
isViewerFriend: $isViewerFriendLocal
scale: $scale
) @stream_connection(
initial_count: 1
key: "UserFragment_friends",
filters: ["orderby", "isViewerFriend"]
) {
edges {
node {
id
name
...NestedUserFragment
}
}
}
}
query UserQuery(
$id: ID!
$after: ID
$first: Int
$before: ID
$last: Int
$orderby: [String]
$isViewerFriend: Boolean
) {
node(id: $id) {
...UserFragment @arguments(isViewerFriendLocal: $isViewerFriend, orderby: $orderby)
}
}
query UserQueryNestedFragment(
$id: ID!
$after: ID
$first: Int
$before: ID
$last: Int
$orderby: [String]
$isViewerFriend: Boolean
) {
node(id: $id) {
actor {
...UserFragment @arguments(isViewerFriendLocal: $isViewerFriend, orderby: $orderby)
}
}
}
query UserQueryWithoutID(
$after: ID
$first: Int
$before: ID
$last: Int
$orderby: [String]
$isViewerFriend: Boolean
) {
viewer {
actor {
...UserFragment @arguments(isViewerFriendLocal: $isViewerFriend, orderby: $orderby)
}
}
}
query UserQueryWithLiteralArgs(
$id: ID!
$after: ID
$first: Int
$before: ID
$last: Int
) {
node(id: $id) {
...UserFragment @arguments(isViewerFriendLocal: true, orderby: ["name"])
}
}
query UserQueryWithStreaming(
$id: ID!
$after: ID
$first: Int
$before: ID
$last: Int
$orderby: [String]
$isViewerFriend: Boolean
) {
node(id: $id) {
...UserFragmentWithStreaming @arguments(isViewerFriendLocal: $isViewerFriend, orderby: $orderby)
}
}
`,
);
variablesWithoutID = {
after: null,
first: 1,
before: null,
last: null,
isViewerFriend: false,
orderby: ['name'],
};
variables = {
...variablesWithoutID,
id: '1',
};
variablesNestedFragment = {
...variablesWithoutID,
id: '<feedbackid>',
};
gqlQuery = generated.UserQuery;
gqlQueryNestedFragment = generated.UserQueryNestedFragment;
gqlQueryWithoutID = generated.UserQueryWithoutID;
gqlQueryWithLiteralArgs = generated.UserQueryWithLiteralArgs;
gqlQueryWithStreaming = generated.UserQueryWithStreaming;
gqlPaginationQuery = generated.UserFragmentPaginationQuery;
gqlPaginationQueryWithStreaming = generated.UserFragmentStreamingPaginationQuery;
gqlFragment = generated.UserFragment;
gqlFragmentWithStreaming = generated.UserFragmentWithStreaming;
invariant(
gqlFragment.metadata?.refetch?.operation ===
'@@MODULE_START@@UserFragmentPaginationQuery.graphql@@MODULE_END@@',
'useRefetchableFragment-test: Expected refetchable fragment metadata to contain operation.',
);
invariant(
gqlFragmentWithStreaming.metadata?.refetch?.operation ===
'@@MODULE_START@@UserFragmentStreamingPaginationQuery.graphql@@MODULE_END@@',
'useRefetchableFragment-test: Expected refetchable fragment metadata to contain operation.',
);
// Manually set the refetchable operation for the test.
gqlFragment.metadata.refetch.operation = gqlPaginationQuery;
// Manually set the refetchable operation for the test.
gqlFragmentWithStreaming.metadata.refetch.operation = gqlPaginationQueryWithStreaming;
query = createOperationDescriptor(gqlQuery, variables, { force: true });
queryNestedFragment = createOperationDescriptor(
gqlQueryNestedFragment,
variablesNestedFragment,
{ force: true },
);
queryWithoutID = createOperationDescriptor(gqlQueryWithoutID, variablesWithoutID, {
force: true,
});
queryWithLiteralArgs = createOperationDescriptor(gqlQueryWithLiteralArgs, variables, {
force: true,
});
queryWithStreaming = createOperationDescriptor(gqlQueryWithStreaming, variables, {
force: true,
});
paginationQuery = createOperationDescriptor(gqlPaginationQuery, variables, {
force: true,
});
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
environment.commitPayload(queryWithoutID, {
viewer: {
actor: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
},
});
environment.commitPayload(queryWithLiteralArgs, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
// Set up renderers
Renderer = (props) => null;
const Container = (props: { userRef?: any; owner: any; fragment?: any }) => {
// We need a render a component to run a Hook
const [owner, _setOwner] = useState(props.owner);
const [_, _setCount] = useState(0);
const fragment = props.fragment ?? gqlFragment;
const nodeUserRef = useMemo(() => environment.lookup(owner.fragment).data?.node, [
owner,
]);
const ownerOperationRef = useMemo(
() => ({
[ID_KEY]: owner.request.variables.id ?? owner.request.variables.nodeID,
[FRAGMENTS_KEY]: {
[fragment.name]: {},
},
[FRAGMENT_OWNER_KEY]: owner.request,
}),
[owner, fragment.name],
);
const userRef = props.hasOwnProperty('userRef')
? props.userRef
: nodeUserRef ?? ownerOperationRef;
setOwner = _setOwner;
const { data: userData } = usePaginationFragment(fragment, userRef as any);
return <Renderer user={userData} />;
};
const ContextProvider = ({ children }) => {
const [env, _setEnv] = useState(environment);
const relayContext = useMemo(() => ({ environment: env }), [env]);
setEnvironment = _setEnv;
return (
<ReactRelayContext.Provider value={relayContext}>
{children}
</ReactRelayContext.Provider>
);
};
renderFragment = (args?: {
isConcurrent?: boolean;
owner?: any;
userRef?: any;
fragment?: any;
}): any => {
const { isConcurrent = false, ...props } = args ?? {};
let renderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<ErrorBoundary fallback={({ error }) => `Error: ${error.message}`}>
<React.Suspense fallback="Fallback">
<ContextProvider>
<Container owner={query} {...props} />
</ContextProvider>
</React.Suspense>
</ErrorBoundary>,
// any[prop-missing] - error revealed when flow-typing ReactTestRenderer
{ unstable_isConcurrent: isConcurrent },
);
});
return renderer;
};
initialUser = {
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
});
afterEach(() => {
environment.mockClear();
renderSpy.mockClear();
warning.mockClear();
});
describe('initial render', () => {
// The bulk of initial render behavior is covered in useFragmentNode-test,
// so this suite covers the basic cases as a sanity check.
it('should throw error if fragment is plural', () => {
jest.spyOn(console, 'error').mockImplementationOnce(() => {});
const generated = generateAndCompile(`
fragment UserFragment on User @relay(plural: true) {
id
}
`);
const renderer = renderFragment({ fragment: generated.UserFragment });
expect(
renderer.toJSON().includes('Remove `@relay(plural: true)` from fragment'),
).toEqual(true);
});
it('should throw error if fragment is missing @refetchable directive', () => {
jest.spyOn(console, 'error').mockImplementationOnce(() => {});
const generated = generateAndCompile(`
fragment UserFragment on User {
id
}
`);
const renderer = renderFragment({ fragment: generated.UserFragment });
expect(
renderer
.toJSON()
.includes('Did you forget to add a @refetchable directive to the fragment?'),
).toEqual(true);
});
it('should throw error if fragment is missing @connection directive', () => {
jest.spyOn(console, 'error').mockImplementationOnce(() => {});
const generated = generateAndCompile(`
fragment UserFragment on User
@refetchable(queryName: "UserFragmentRefetchQuery") {
id
}
`);
generated.UserFragment.metadata.refetch.operation = generated.UserFragmentRefetchQuery;
const renderer = renderFragment({ fragment: generated.UserFragment });
expect(
renderer
.toJSON()
.includes(
'Did you forget to add a @connection directive to the connection field in the fragment?',
),
).toEqual(true);
});
it('should render fragment without error when data is available', () => {
renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
});
it('should render fragment without error when ref is null', () => {
renderFragment({ userRef: null });
expectFragmentResults([
{
data: null,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: false,
hasPrevious: false,
},
]);
});
it('should render fragment without error when ref is undefined', () => {
renderFragment({ userRef: undefined });
expectFragmentResults([
{
data: null,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: false,
hasPrevious: false,
},
]);
});
it('should update when fragment data changes', () => {
renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
// Update parent record
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
// Update name
name: 'Alice in Wonderland',
},
});
expectFragmentResults([
{
data: {
...initialUser,
// Assert that name is updated
name: 'Alice in Wonderland',
},
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
// Update edge
environment.commitPayload(query, {
node: {
__typename: 'User',
id: 'node:1',
// Update name
name: 'name:node:1-updated',
},
});
expectFragmentResults([
{
data: {
...initialUser,
name: 'Alice in Wonderland',
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
// Assert that name is updated
name: 'name:node:1-updated',
...createFragmentRef('node:1', query),
},
},
],
},
},
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
});
/*it('should throw a promise if data is missing for fragment and request is in flight', () => {
// This prevents console.error output in the test, which is expected
jest.spyOn(console, 'error').mockImplementationOnce(() => {});
jest.spyOn(
require('relay-runtime').__internal,
'getPromiseForActiveRequest',
).mockImplementationOnce(() => Promise.resolve());
const missingDataVariables = { ...variables, id: '4' };
const missingDataQuery = createOperationDescriptor(gqlQuery, missingDataVariables, {
force: true,
});
// Commit a payload with name and profile_picture are missing
environment.commitPayload(missingDataQuery, {
node: {
__typename: 'User',
id: '4',
},
});
const renderer = renderFragment({ owner: missingDataQuery });
expect(renderer.toJSON()).toEqual('Fallback');
});*/
});
describe('pagination', () => {
let release;
beforeEach(() => {
jest.resetModules();
release = jest.fn();
environment.retain.mockImplementation((...args) => {
return {
dispose: release,
};
});
});
function expectRequestIsInFlight(expected) {
expect(environment.execute).toBeCalledTimes(expected.requestCount);
expect(
environment.mock.isLoading(
expected.gqlPaginationQuery ?? gqlPaginationQuery,
expected.paginationVariables,
{ force: true },
),
).toEqual(expected.inFlight);
}
function expectFragmentIsLoadingMore(
renderer,
direction: Direction,
expected: {
data: any;
hasNext: boolean;
hasPrevious: boolean;
paginationVariables: Variables;
gqlPaginationQuery?: any;
},
) {
// Assert fragment sets isLoading to true
expect(renderSpy).toBeCalledTimes(1);
assertCall(
{
data: expected.data,
isLoadingNext: direction === 'forward',
isLoadingPrevious: direction === 'backward',
hasNext: expected.hasNext,
hasPrevious: expected.hasPrevious,
},
0,
);
renderSpy.mockClear();
// Assert refetch query was fetched
expectRequestIsInFlight({ ...expected, inFlight: true, requestCount: 1 });
}
// TODO
// - backward pagination
// - simultaneous pagination
// - TODO(T41131846): Fetch/Caching policies for loadMore / when network
// returns or errors synchronously
// - TODO(T41140071): Handle loadMore while refetch is in flight and vice-versa
describe('loadNext', () => {
const direction = 'forward';
beforeEach(() => {
unsubscribe.mockClear();
});
it('does not load more if component has unmounted', () => {
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
renderer.unmount();
});
TestRenderer.act(() => {
loadNext(1);
});
expect(warning).toHaveBeenCalledTimes(1);
expect(
(warning as any).mock.calls[0][1].includes(
'Relay: Unexpected fetch on unmounted component',
),
).toEqual(true);
expect(environment.execute).toHaveBeenCalledTimes(0);
});
it('does not load more if fragment ref passed to usePaginationFragment() was null', () => {
renderFragment({ userRef: null });
expectFragmentResults([
{
data: null,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: false,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1);
});
expect(warning).toHaveBeenCalledTimes(1);
expect(
(warning as any).mock.calls[0][1].includes(
'Relay: Unexpected fetch while using a null fragment ref',
),
).toEqual(true);
expect(environment.execute).toHaveBeenCalledTimes(0);
});
it('does not load more if request is already in flight', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
expect(callback).toBeCalledTimes(0);
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
expect(environment.execute).toBeCalledTimes(1);
expect(callback).toBeCalledTimes(1);
expect(renderSpy).toBeCalledTimes(0);
});
it('does not load more if parent query is already active (i.e. during streaming)', () => {
// This prevents console.error output in the test, which is expected
jest.spyOn(console, 'error').mockImplementationOnce(() => {});
const {
__internal: { fetchQuery },
} = require('relay-runtime');
fetchQuery(environment, query).subscribe({});
const callback = jest.fn();
environment.execute.mockClear();
renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
expect(environment.execute).toBeCalledTimes(0);
expect(callback).toBeCalledTimes(1);
expect(renderSpy).toBeCalledTimes(0);
});
it('cancels load more if component unmounts', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(unsubscribe).toHaveBeenCalledTimes(0);
TestRenderer.act(() => {
renderer.unmount();
});
expect(unsubscribe).toHaveBeenCalledTimes(1);
expect(environment.execute).toBeCalledTimes(1);
expect(callback).toBeCalledTimes(0);
expect(renderSpy).toBeCalledTimes(0);
});
it('cancels load more if refetch is called', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(unsubscribe).toHaveBeenCalledTimes(0);
TestRenderer.act(() => {
refetch({ id: '4' });
});
expect(unsubscribe).toHaveBeenCalledTimes(1);
expect(environment.execute).toBeCalledTimes(2);
expect(callback).toBeCalledTimes(0);
expect(renderSpy).toBeCalledTimes(0);
});
it('attempts to load more even if there are no more items to load', () => {
(environment.getStore().getSource() as any).clear();
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: false,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
const callback = jest.fn();
const renderer = renderFragment();
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
pageInfo: expect.objectContaining({ hasNextPage: false }),
},
};
expectFragmentResults([
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: false,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: expectedUser,
hasNext: false,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [],
pageInfo: {
startCursor: null,
endCursor: null,
hasNextPage: null,
hasPreviousPage: null,
},
},
},
},
});
expectFragmentResults([
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: false,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('loads and renders next items in connection', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', query),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('loads more correctly using fragment variables from literal @argument values', () => {
let expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryWithLiteralArgs),
},
},
],
},
};
const callback = jest.fn();
const renderer = renderFragment({ owner: queryWithLiteralArgs });
expectFragmentResults([
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: true,
orderby: ['name'],
scale: null,
};
expect(paginationVariables.isViewerFriendLocal).not.toBe(variables.isViewerFriend);
expectFragmentIsLoadingMore(renderer, direction, {
data: expectedUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
expectedUser = {
...expectedUser,
friends: {
...expectedUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryWithLiteralArgs),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', queryWithLiteralArgs),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('loads more correctly when original variables do not include an id', () => {
const callback = jest.fn();
const viewer = environment.lookup(queryWithoutID.fragment).data?.viewer;
const userRef = typeof viewer === 'object' && viewer != null ? viewer?.actor : null;
invariant(userRef != null, 'Expected to have cached test data');
let expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryWithoutID),
},
},
],
},
};
const renderer = renderFragment({ owner: queryWithoutID, userRef });
expectFragmentResults([
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: expectedUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryWithoutID),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', queryWithoutID),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('loads more with correct id from refetchable fragment when using a nested fragment', () => {
const callback = jest.fn();
// Populate store with data for query using nested fragment
environment.commitPayload(queryNestedFragment, {
node: {
__typename: 'Feedback',
id: '<feedbackid>',
actor: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
},
});
// Get fragment ref for user using nested fragment
const userRef = (environment.lookup(queryNestedFragment.fragment).data as any)?.node
?.actor;
initialUser = {
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryNestedFragment),
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
const renderer = renderFragment({ owner: queryNestedFragment, userRef });
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
// The id here should correspond to the user id, and not the
// feedback id from the query variables (i.e. `<feedbackid>`)
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryNestedFragment),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', queryNestedFragment),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('calls callback with error when error occurs during fetch', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
const error = new Error('Oops');
environment.mock.reject(gqlPaginationQuery, error);
// We pass the error in the callback, but do not throw during render
// since we want to continue rendering the existing items in the
// connection
expect(callback).toBeCalledTimes(1);
expect(callback).toBeCalledWith(error);
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
errorNext: error,
},
]);
});
it('preserves pagination request if re-rendered with same fragment ref', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
TestRenderer.act(() => {
setOwner({ ...query });
});
// Assert that request is still in flight after re-rendering
// with new fragment ref that points to the same data.
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', query),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
describe('extra variables', () => {
it('loads and renders the next items in the connection when passing extra variables', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, {
onComplete: callback,
// Pass extra variables that are different from original request
UNSTABLE_extraVariables: { scale: 2.0 },
});
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
// Assert that value from extra variables is used
scale: 2.0,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', query),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('loads the next items in the connection and ignores any pagination vars passed as extra vars', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, {
onComplete: callback,
// Pass pagination vars as extra variables
UNSTABLE_extraVariables: { first: 100, after: 'foo' },
});
});
const paginationVariables = {
id: '1',
// Assert that pagination vars from extra variables are ignored
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', query),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
});
describe('disposing', () => {
beforeEach(() => {
unsubscribe.mockClear();
});
it('disposes ongoing request if environment changes', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
// Assert request is started
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
// Set new environment
const newEnvironment = createMockEnvironment({
handlerProvider: () => ConnectionHandler,
});
newEnvironment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice in a different environment',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
TestRenderer.act(() => {
setEnvironment(newEnvironment);
});
// Assert request was canceled
expect(unsubscribe).toBeCalledTimes(1);
expectRequestIsInFlight({
inFlight: false,
requestCount: 1,
gqlPaginationQuery,
paginationVariables,
});
// Assert newly rendered data
expectFragmentResults([
/*{
data: {
...initialUser,
name: 'Alice in a different environment',
},
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},*/
{
data: {
...initialUser,
name: 'Alice in a different environment',
},
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
});
it('disposes ongoing request if fragment ref changes', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
// Assert request is started
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
// Pass new parent fragment ref with different variables
const newVariables = { ...variables, isViewerFriend: true };
const newQuery = createOperationDescriptor(gqlQuery, newVariables, {
force: true,
});
environment.commitPayload(newQuery, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
TestRenderer.act(() => {
setOwner(newQuery);
});
// Assert request was canceled
expect(unsubscribe).toBeCalledTimes(1);
expectRequestIsInFlight({
inFlight: false,
requestCount: 1,
gqlPaginationQuery,
paginationVariables,
});
// Assert newly rendered data
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
// Assert fragment ref points to owner with new variables
...createFragmentRef('node:1', newQuery),
},
},
],
},
};
expectFragmentResults([
/*{
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},*/
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
});
it('disposes ongoing request on unmount', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
// Assert request is started
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
TestRenderer.act(() => {
renderer.unmount();
});
// Assert request was canceled
expect(unsubscribe).toBeCalledTimes(1);
expectRequestIsInFlight({
inFlight: false,
requestCount: 1,
gqlPaginationQuery,
paginationVariables,
});
});
it('disposes ongoing request if it is manually disposed', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
let disposable;
TestRenderer.act(() => {
disposable = loadNext(1, { onComplete: callback });
});
// Assert request is started
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
// any[incompatible-use]
disposable.dispose();
// Assert request was canceled
expect(unsubscribe).toBeCalledTimes(1);
expectRequestIsInFlight({
inFlight: false,
requestCount: 1,
gqlPaginationQuery,
paginationVariables,
});
expect(renderSpy).toHaveBeenCalledTimes(0);
});
});
describe('when parent query is streaming', () => {
beforeEach(() => {
({ createMockEnvironment } = require('relay-test-utils-internal'));
environment = createMockEnvironment({
handlerProvider: () => ConnectionHandler,
});
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
},
});
});
/*
it('does not start pagination request even if query is no longer active but loadNext is bound to snapshot of data while query was active', () => {
const {
__internal: { fetchQuery },
} = require('relay-runtime');
// Start parent query and assert it is active
fetchQuery(environment, queryWithStreaming).subscribe({});
expect(
environment.isRequestActive(queryWithStreaming.request.identifier),
).toEqual(true);
// Render initial fragment
const instance = renderFragment({
fragment: gqlFragmentWithStreaming,
owner: queryWithStreaming,
});
expect(instance.toJSON()).toEqual(null);
renderSpy.mockClear();
// Resolve first payload
TestRenderer.act(() => {
environment.mock.nextValue(gqlQueryWithStreaming, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
},
},
},
extensions: {
is_final: false,
},
});
});
// Ensure request is still active
expect(
environment.isRequestActive(queryWithStreaming.request.identifier),
).toEqual(true);
// Assert fragment rendered with correct data
expectFragmentResults([
{
data: {
...initialUser,
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryWithStreaming),
},
},
],
// Assert pageInfo is currently null
pageInfo: {
endCursor: null,
hasNextPage: false,
hasPreviousPage: false,
startCursor: null,
},
},
},
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: false,
hasPrevious: false,
},
]);
// Capture the value of loadNext at this moment, which will
// would use the page info from the current fragment snapshot.
// At the moment of this snapshot the parent request is still active,
// so calling `capturedLoadNext` should be a no-op, otherwise it
// would attempt a pagination with the incorrect cursor as null.
const capturedLoadNext = loadNext;
// Resolve page info
TestRenderer.act(() => {
environment.mock.nextValue(gqlQueryWithStreaming, {
data: {
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
},
},
label: 'UserFragmentWithStreaming$defer$UserFragment_friends$pageInfo',
path: ['node', 'friends'],
extensions: {
is_final: true,
},
});
});
// Ensure request is no longer active since final payload has been
// received
expect(
environment.isRequestActive(queryWithStreaming.request.identifier),
).toEqual(false);
// Assert fragment rendered with correct data
expectFragmentResults([
{
data: {
...initialUser,
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryWithStreaming),
},
},
],
// Assert pageInfo is updated
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: null,
},
},
},
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
environment.execute.mockClear();
renderSpy.mockClear();
// Call `capturedLoadNext`, which should be a no-op since it's
// bound to the snapshot of the fragment taken while the query is
// still active and pointing to incomplete page info.
TestRenderer.act(() => {
capturedLoadNext(1);
});
// Assert that calling `capturedLoadNext` is a no-op
expect(environment.execute).toBeCalledTimes(0);
expect(renderSpy).toBeCalledTimes(0);
// Calling `loadNext`, should be fine since it's bound to the
// latest fragment snapshot with the latest page info and when
// the request is no longer active
TestRenderer.act(() => {
loadNext(1);
});
// Assert that calling `loadNext` starts the request
expect(environment.execute).toBeCalledTimes(1);
expect(renderSpy).toBeCalledTimes(1);
});*/
});
});
describe('hasNext', () => {
const direction = 'forward';
it('returns true if it has more items', () => {
(environment.getStore().getSource() as any).clear();
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
renderFragment();
expectFragmentResults([
{
data: {
...initialUser,
friends: {
...initialUser.friends,
pageInfo: expect.objectContaining({ hasNextPage: true }),
},
},
isLoadingNext: false,
isLoadingPrevious: false,
// Assert hasNext is true
hasNext: true,
hasPrevious: false,
},
]);
});
it('returns false if edges are null', () => {
(environment.getStore().getSource() as any).clear();
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: null,
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
renderFragment();
expectFragmentResults([
{
data: {
...initialUser,
friends: {
...initialUser.friends,
edges: null,
pageInfo: expect.objectContaining({ hasNextPage: true }),
},
},
isLoadingNext: false,
isLoadingPrevious: false,
// Assert hasNext is false
hasNext: false,
hasPrevious: false,
},
]);
});
it('returns false if edges are undefined', () => {
(environment.getStore().getSource() as any).clear();
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: undefined,
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
renderFragment();
expectFragmentResults([
{
data: {
...initialUser,
friends: {
...initialUser.friends,
edges: undefined,
pageInfo: expect.objectContaining({ hasNextPage: true }),
},
},
isLoadingNext: false,
isLoadingPrevious: false,
// Assert hasNext is false
hasNext: false,
hasPrevious: false,
},
]);
});
it('returns false if end cursor is null', () => {
(environment.getStore().getSource() as any).clear();
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
// endCursor is null
endCursor: null,
// but hasNextPage is still true
hasNextPage: true,
hasPreviousPage: false,
startCursor: null,
},
},
},
});
renderFragment();
expectFragmentResults([
{
data: {
...initialUser,
friends: {
...initialUser.friends,
pageInfo: expect.objectContaining({
endCursor: null,
hasNextPage: true,
}),
},
},
isLoadingNext: false,
isLoadingPrevious: false,
// Assert hasNext is false
hasNext: false,
hasPrevious: false,
},
]);
});
it('returns false if end cursor is undefined', () => {
(environment.getStore().getSource() as any).clear();
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
// endCursor is undefined
endCursor: undefined,
// but hasNextPage is still true
hasNextPage: true,
hasPreviousPage: false,
startCursor: undefined,
},
},
},
});
renderFragment();
expectFragmentResults([
{
data: {
...initialUser,
friends: {
...initialUser.friends,
pageInfo: expect.objectContaining({
endCursor: null,
hasNextPage: true,
}),
},
},
isLoadingNext: false,
isLoadingPrevious: false,
// Assert hasNext is false
hasNext: false,
hasPrevious: false,
},
]);
});
it('returns false if pageInfo.hasNextPage is false-ish', () => {
(environment.getStore().getSource() as any).clear();
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: null,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
renderFragment();
expectFragmentResults([
{
data: {
...initialUser,
friends: {
...initialUser.friends,
pageInfo: expect.objectContaining({
hasNextPage: null,
}),
},
},
isLoadingNext: false,
isLoadingPrevious: false,
// Assert hasNext is false
hasNext: false,
hasPrevious: false,
},
]);
});
it('returns false if pageInfo.hasNextPage is false', () => {
(environment.getStore().getSource() as any).clear();
environment.commitPayload(query, {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: false,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
});
renderFragment();
expectFragmentResults([
{
data: {
...initialUser,
friends: {
...initialUser.friends,
pageInfo: expect.objectContaining({
hasNextPage: false,
}),
},
},
isLoadingNext: false,
isLoadingPrevious: false,
// Assert hasNext is false
hasNext: false,
hasPrevious: false,
},
]);
});
it('updates after pagination if more results are available', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', query),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
// Assert hasNext reflects server response
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
// Assert hasNext reflects server response
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('updates after pagination if no more results are available', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: false,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', query),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: false,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedUser,
isLoadingNext: true,
isLoadingPrevious: false,
// Assert hasNext reflects server response
hasNext: false,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
// Assert hasNext reflects server response
hasNext: false,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
});
describe('refetch', () => {
// The bulk of refetch behavior is covered in useRefetchableFragmentNode-test,
// so this suite covers the pagination-related test cases.
function expectRefetchRequestIsInFlight(expected) {
expect(environment.execute).toBeCalledTimes(expected.requestCount);
expect(
environment.mock.isLoading(
expected.gqlRefetchQuery ?? gqlPaginationQuery,
expected.refetchVariables,
{ force: true },
),
).toEqual(expected.inFlight);
}
function expectFragmentIsRefetching(
renderer,
expected: {
data: any;
hasNext: boolean;
hasPrevious: boolean;
refetchVariables: Variables;
refetchQuery?: OperationDescriptor;
gqlRefetchQuery?: any;
},
) {
expect(renderSpy).toBeCalledTimes(0);
renderSpy.mockClear();
// Assert refetch query was fetched
expectRefetchRequestIsInFlight({
...expected,
inFlight: true,
requestCount: 1,
});
// Assert component suspended
expect(renderSpy).toBeCalledTimes(0);
expect(renderer.toJSON()).toEqual('Fallback');
// Assert query is tentatively retained while component is suspended
expect(environment.retain).toBeCalledTimes(1);
expect(environment.retain.mock.calls[0][0]).toEqual(
expected.refetchQuery ?? paginationQuery,
);
}
it('refetches new variables correctly when refetching new id', () => {
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
refetch({ id: '4' });
});
// Assert that fragment is refetching with the right variables and
// suspends upon refetch
const refetchVariables = {
after: null,
first: 1,
before: null,
last: null,
id: '4',
isViewerFriendLocal: false,
orderby: ['name'],
scale: null,
};
paginationQuery = createOperationDescriptor(gqlPaginationQuery, refetchVariables, {
force: true,
});
expectFragmentIsRefetching(renderer, {
data: initialUser,
hasNext: true,
hasPrevious: false,
refetchVariables,
refetchQuery: paginationQuery,
});
// Mock network response
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '4',
name: 'Mark',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
username: 'username:node:100',
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
},
},
});
// Assert fragment is rendered with new data
const expectedUser = {
id: '4',
name: 'Mark',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
...createFragmentRef('node:100', paginationQuery),
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
};
expectFragmentResults([
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
// Assert refetch query was retained
expect(release).not.toBeCalled();
expect(environment.retain).toBeCalledTimes(1);
expect(environment.retain.mock.calls[0][0]).toEqual(paginationQuery);
});
it('refetches new variables correctly when refetching same id', () => {
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
refetch({ isViewerFriendLocal: true, orderby: ['lastname'] });
});
// Assert that fragment is refetching with the right variables and
// suspends upon refetch
const refetchVariables = {
after: null,
first: 1,
before: null,
last: null,
id: '1',
isViewerFriendLocal: true,
orderby: ['lastname'],
scale: null,
};
paginationQuery = createOperationDescriptor(gqlPaginationQuery, refetchVariables, {
force: true,
});
expectFragmentIsRefetching(renderer, {
data: initialUser,
hasNext: true,
hasPrevious: false,
refetchVariables,
refetchQuery: paginationQuery,
});
// Mock network response
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
username: 'username:node:100',
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
},
},
});
// Assert fragment is rendered with new data
const expectedUser = {
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
...createFragmentRef('node:100', paginationQuery),
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
};
expectFragmentResults([
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
// Assert refetch query was retained
expect(release).not.toBeCalled();
expect(environment.retain).toBeCalledTimes(1);
expect(environment.retain.mock.calls[0][0]).toEqual(paginationQuery);
});
it('refetches with correct id from refetchable fragment when using nested fragment', () => {
// Populate store with data for query using nested fragment
environment.commitPayload(queryNestedFragment, {
node: {
__typename: 'Feedback',
id: '<feedbackid>',
actor: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
},
});
// Get fragment ref for user using nested fragment
const userRef = (environment.lookup(queryNestedFragment.fragment).data as any)?.node
?.actor;
initialUser = {
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryNestedFragment),
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
const renderer = renderFragment({ owner: queryNestedFragment, userRef });
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
refetch({ isViewerFriendLocal: true, orderby: ['lastname'] });
});
// Assert that fragment is refetching with the right variables and
// suspends upon refetch
const refetchVariables = {
after: null,
first: 1,
before: null,
last: null,
// The id here should correspond to the user id, and not the
// feedback id from the query variables (i.e. `<feedbackid>`)
id: '1',
isViewerFriendLocal: true,
orderby: ['lastname'],
scale: null,
};
paginationQuery = createOperationDescriptor(gqlPaginationQuery, refetchVariables, {
force: true,
});
expectFragmentIsRefetching(renderer, {
data: initialUser,
hasNext: true,
hasPrevious: false,
refetchVariables,
refetchQuery: paginationQuery,
});
// Mock network response
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
username: 'username:node:100',
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
},
},
});
// Assert fragment is rendered with new data
const expectedUser = {
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
...createFragmentRef('node:100', paginationQuery),
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
};
expectFragmentResults([
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
// Assert refetch query was retained
expect(release).not.toBeCalled();
expect(environment.retain).toBeCalledTimes(1);
expect(environment.retain.mock.calls[0][0]).toEqual(paginationQuery);
});
it('loads more items correctly after refetching', () => {
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
refetch({ isViewerFriendLocal: true, orderby: ['lastname'] });
});
// Assert that fragment is refetching with the right variables and
// suspends upon refetch
const refetchVariables = {
after: null,
first: 1,
before: null,
last: null,
id: '1',
isViewerFriendLocal: true,
orderby: ['lastname'],
scale: null,
};
paginationQuery = createOperationDescriptor(gqlPaginationQuery, refetchVariables, {
force: true,
});
expectFragmentIsRefetching(renderer, {
data: initialUser,
hasNext: true,
hasPrevious: false,
refetchVariables,
refetchQuery: paginationQuery,
});
// Mock network response
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
username: 'username:node:100',
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
},
},
});
// Assert fragment is rendered with new data
const expectedUser = {
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
...createFragmentRef('node:100', paginationQuery),
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
};
expectFragmentResults([
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
data: expectedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
// Assert refetch query was retained
expect(release).not.toBeCalled();
expect(environment.retain).toBeCalledTimes(1);
expect(environment.retain.mock.calls[0][0]).toEqual(paginationQuery);
// Paginate after refetching
environment.execute.mockClear();
TestRenderer.act(() => {
loadNext(1);
});
const paginationVariables = {
id: '1',
after: 'cursor:100',
first: 1,
before: null,
last: null,
isViewerFriendLocal: true,
orderby: ['lastname'],
scale: null,
};
expectFragmentIsLoadingMore(renderer, 'forward', {
data: expectedUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:200',
node: {
__typename: 'User',
id: 'node:200',
name: 'name:node:200',
username: 'username:node:200',
},
},
],
pageInfo: {
startCursor: 'cursor:200',
endCursor: 'cursor:200',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const paginatedUser = {
...expectedUser,
friends: {
...expectedUser.friends,
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
...createFragmentRef('node:100', paginationQuery),
},
},
{
cursor: 'cursor:200',
node: {
__typename: 'User',
id: 'node:200',
name: 'name:node:200',
...createFragmentRef('node:200', paginationQuery),
},
},
],
pageInfo: {
endCursor: 'cursor:200',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: paginatedUser,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: paginatedUser,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
});
});
describe('paginating @fetchable types', () => {
let gqlRefetchQuery;
beforeEach(() => {
const generated = generateAndCompile(
`
fragment StoryFragment on NonNodeStory
@argumentDefinitions(
count: {type: "Int", defaultValue: 10},
cursor: {type: "ID"}
)
@refetchable(queryName: "StoryFragmentRefetchQuery") {
comments(first: $count, after: $cursor) @connection(key: "StoryFragment_comments") {
edges {
node {
id
}
}
}
}
query StoryQuery($id: ID!) {
nonNodeStory(id: $id) {
...StoryFragment
}
}
`,
);
const fetchVariables = { id: 'a' };
gqlQuery = generated.StoryQuery;
gqlRefetchQuery = generated.StoryFragmentRefetchQuery;
gqlPaginationQuery = generated.StoryFragmentRefetchQuery;
gqlFragment = generated.StoryFragment;
invariant(
gqlFragment.metadata?.refetch?.operation ===
'@@MODULE_START@@StoryFragmentRefetchQuery.graphql@@MODULE_END@@',
'useRefetchableFragment-test: Expected refetchable fragment metadata to contain operation.',
);
// Manually set the refetchable operation for the test.
gqlFragment.metadata.refetch.operation = gqlRefetchQuery;
query = createOperationDescriptor(gqlQuery, fetchVariables, {
force: true,
});
environment.commitPayload(query, {
nonNodeStory: {
__typename: 'NonNodeStory',
id: 'a',
fetch_id: 'fetch:a',
comments: {
edges: [
{
cursor: 'edge:0',
node: {
__typename: 'Comment',
id: 'comment:0',
},
},
],
pageInfo: {
endCursor: 'edge:0',
hasNextPage: true,
},
},
},
});
});
it('loads and renders next items in connection', () => {
const callback = jest.fn();
const renderer = renderFragment();
const initialData = {
fetch_id: 'fetch:a',
comments: {
edges: [
{
cursor: 'edge:0',
node: {
__typename: 'Comment',
id: 'comment:0',
},
},
],
pageInfo: {
endCursor: 'edge:0',
hasNextPage: true,
},
},
};
expectFragmentResults([
{
data: initialData,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
TestRenderer.act(() => {
loadNext(1, { onComplete: callback });
});
const paginationVariables = {
id: 'fetch:a',
cursor: 'edge:0',
count: 1,
};
expectFragmentIsLoadingMore(renderer, 'forward', {
data: initialData,
hasNext: true,
hasPrevious: false,
paginationVariables,
gqlPaginationQuery,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
fetch__NonNodeStory: {
id: 'a',
fetch_id: 'fetch:a',
comments: {
edges: [
{
cursor: 'edge:1',
node: {
__typename: 'Comment',
id: 'comment:1',
},
},
],
pageInfo: {
endCursor: 'edge:1',
hasNextPage: true,
},
},
},
},
});
const expectedData = {
...initialData,
comments: {
edges: [
...initialData.comments.edges,
{
cursor: 'edge:1',
node: {
__typename: 'Comment',
id: 'comment:1',
},
},
],
pageInfo: {
endCursor: 'edge:1',
hasNextPage: true,
},
},
};
expectFragmentResults([
{
// First update has updated connection
data: expectedData,
isLoadingNext: true,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
{
// Second update sets isLoading flag back to false
data: expectedData,
isLoadingNext: false,
isLoadingPrevious: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
});
});
}); | the_stack |
import Application = require("application");
import FileSystem = require("file-system");
import HTTP = require("http");
import Image = require("image-source");
import TypeUtils = require("utils/types");
import Xml = require("xml");
/**
* A basic logger.
*/
export abstract class LoggerBase implements ILogger {
/** @inheritdoc */
public alert(msg : any, tag?: string, priority?: LogPriority) : LoggerBase {
return this.log(msg, tag,
LogCategory.Alert, priority);
}
/**
* Creates a ILogMessage object.
*
* @param any msg The message value.
* @param {String} tag The tag value.
* @param LogCategory category The log category.
* @param {LogPriority} priority The log priority.
*/
protected abstract createLogMessage(msg : any, tag: string,
category: LogCategory, priority: LogPriority) : ILogMessage;
/** @inheritdoc */
public crit(msg : any, tag?: string, priority?: LogPriority) : LoggerBase {
return this.log(msg, tag,
LogCategory.Critical, priority);
}
/** @inheritdoc */
public dbg(msg : any, tag?: string, priority?: LogPriority) : LoggerBase {
return this.log(msg, tag,
LogCategory.Debug, priority);
}
/** @inheritdoc */
public emerg(msg : any, tag?: string, priority?: LogPriority) : LoggerBase {
return this.log(msg, tag,
LogCategory.Emergency, priority);
}
/** @inheritdoc */
public err(msg : any, tag?: string, priority?: LogPriority) : LoggerBase {
return this.log(msg, tag,
LogCategory.Error, priority);
}
/** @inheritdoc */
public info(msg : any, tag?: string, priority?: LogPriority) : LoggerBase {
return this.log(msg, tag,
LogCategory.Info, priority);
}
/** @inheritdoc */
public log(msg : any, tag?: string,
category?: LogCategory, priority?: LogPriority) : LoggerBase {
if (isEmptyString(tag)) {
tag = null;
}
else {
tag = tag.toUpperCase().trim();
}
if (TypeUtils.isNullOrUndefined(category)) {
category = LogCategory.Debug;
}
this.onLog(this.createLogMessage(msg, tag,
category, priority));
return this;
}
/** @inheritdoc */
public note(msg : any, tag?: string, priority?: LogPriority) : LoggerBase {
return this.log(msg, tag,
LogCategory.Notice, priority);
}
/**
* The logic for the 'log' method.
*/
protected abstract onLog(msg : ILogMessage);
/** @inheritdoc */
public trace(msg : any, tag?: string, priority?: LogPriority) : LoggerBase {
return this.log(msg, tag,
LogCategory.Trace, priority);
}
/** @inheritdoc */
public warn(msg : any, tag?: string, priority?: LogPriority) : LoggerBase {
return this.log(msg, tag,
LogCategory.Warning, priority);
}
}
/**
* An authorizer that uses an internal list of
* authorizers to execute.
*/
export class AggregateAuthorizer implements IAuthorizer {
private _authorizers : IAuthorizer[] = [];
/**
* Adds one or more authorizers.
*
* @param {IAuthorizer} ...authorizers One or more authorizers to add.
*/
public addAuthorizers(...authorizers : IAuthorizer[]) {
for (var i = 0; i < authorizers.length; i++) {
this._authorizers
.push(authorizers[i]);
}
}
/** @inheritdoc */
public prepare(reqOpts : HTTP.HttpRequestOptions) {
for (var i = 0; i < this._authorizers.length; i++) {
this._authorizers[i]
.prepare(reqOpts);
}
}
}
class ApiClient extends LoggerBase implements IApiClient {
constructor(cfg : IApiClientConfig) {
super();
this.baseUrl = cfg.baseUrl;
this.headers = cfg.headers;
this.route = cfg.route;
this.routeParams = cfg.routeParams;
this.params = cfg.params;
this.authorizer = cfg.authorizer;
// beforeSend()
if (!TypeUtils.isNullOrUndefined(cfg.beforeSend)) {
this.beforeSend(cfg.beforeSend);
}
// success action
if (!TypeUtils.isNullOrUndefined(cfg.success)) {
this.successAction = cfg.success;
}
// error action
if (!TypeUtils.isNullOrUndefined(cfg.error)) {
this.errorAction = cfg.error;
}
// complete action
if (!TypeUtils.isNullOrUndefined(cfg.complete)) {
this.completeAction = cfg.complete;
}
// notFound()
if (!TypeUtils.isNullOrUndefined(cfg.notFound)) {
this.notFound(cfg.notFound);
}
// unauthorized()
if (!TypeUtils.isNullOrUndefined(cfg.unauthorized)) {
this.unauthorized(cfg.unauthorized);
}
// forbidden()
if (!TypeUtils.isNullOrUndefined(cfg.forbidden)) {
this.forbidden(cfg.forbidden);
}
// succeededRequest()
if (!TypeUtils.isNullOrUndefined(cfg.succeededRequest)) {
this.succeededRequest(cfg.succeededRequest);
}
// redirection()
if (!TypeUtils.isNullOrUndefined(cfg.redirection)) {
this.redirection(cfg.redirection);
}
// clientError()
if (!TypeUtils.isNullOrUndefined(cfg.clientError)) {
this.clientError(cfg.clientError);
}
// serverError()
if (!TypeUtils.isNullOrUndefined(cfg.serverError)) {
this.serverError(cfg.serverError);
}
// ok()
if (!TypeUtils.isNullOrUndefined(cfg.ok)) {
this.ok(cfg.ok);
}
// status code
for (var p in cfg) {
var statusCode = parseInt(p);
if (!isNaN(statusCode)) {
if (statusCode >= 200 && statusCode <= 599) {
this.status(statusCode, cfg[p]);
}
}
}
// ifStatus()
if (!TypeUtils.isNullOrUndefined(cfg.ifStatus)) {
for (var i = 0; i < cfg.ifStatus.length; i++) {
var ise = <IIfStatus>cfg.ifStatus[i];
if (!TypeUtils.isNullOrUndefined(ise)) {
this.ifStatus(ise.predicate,
ise.action);
}
}
}
// if()
if (!TypeUtils.isNullOrUndefined(cfg.if)) {
for (var i = 0; i < cfg.if.length; i++) {
var ie = <IIfResponse>cfg.if[i];
if (!TypeUtils.isNullOrUndefined(ie)) {
this.if(ie.predicate,
ie.action);
}
}
}
}
public addFormatProvider(provider: (ctx: IFormatProviderContext) => any) : ApiClient {
if (!TypeUtils.isNullOrUndefined(provider)) {
this.formatProviders.push(provider);
}
return this;
}
public addLogger(logAction : (ctx : ILogMessage) => void) : ApiClient {
if (!TypeUtils.isNullOrUndefined(logAction)) {
this.logActions.push(logAction);
}
return this;
}
public authorizer: IAuthorizer;
public badGateway(badGatewayAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(502, badGatewayAction);
}
public badRequest(badRequestAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(400, badRequestAction);
}
public baseUrl : string;
public beforeSend(beforeAction : (opts : HTTP.HttpRequestOptions, tag: any) => void) : ApiClient {
this.beforeSendActions.push(beforeAction);
return this;
}
public beforeSendActions = [];
public clientError(clientErrAction : (result : IApiClientResult) => void) : ApiClient {
return this.ifStatus((code) => code >= 400 && code <= 499,
clientErrAction);
}
public clientOrServerError(clientSrvErrAction : (result : IApiClientResult) => void): IApiClient {
this.clientError(clientSrvErrAction);
this.serverError(clientSrvErrAction);
return this;
}
public complete(completeAction : (ctx : IApiClientCompleteContext) => void) : ApiClient {
this.completeAction = completeAction;
return this;
}
public completeAction : (ctx : IApiClientCompleteContext) => void;
public conflict(conflictAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(409, conflictAction);
}
protected createLogMessage(msg: any, tag: string,
category : LogCategory, priority : LogPriority) : ILogMessage {
return new LogMessage(LogSource.Client,
new Date(),
msg, tag,
category, priority);
}
public delete(opts? : IRequestOptions) {
this.request("DELETE", opts);
}
public error(errAction : (ctx : IApiClientError) => void) : ApiClient {
this.errorAction = errAction;
return this;
}
public errorAction : (ctx : IApiClientError) => void;
public formatProviders = [];
public forbidden(forbiddenAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(403, forbiddenAction);
}
public gatewayTimeout(timeoutAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(504, timeoutAction);
}
public get(opts? : IRequestOptions) {
return this.request("GET", opts);
}
public gone(goneAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(410, goneAction);
}
public headers: any;
public if(predicate: (ctx : IApiClientResult) => boolean,
statusAction : (result : IApiClientResult) => void) : ApiClient {
this.ifEntries.push({
action: statusAction,
predicate: predicate,
});
return this;
}
public ifEntries : IIfResponse[] = [];
public ifStatus(predicate: (code : number) => boolean,
statusAction : (result : IApiClientResult) => void) : ApiClient {
var ifPredicate : (ctx : IApiClientResult) => boolean;
if (!TypeUtils.isNullOrUndefined(predicate)) {
ifPredicate = function(ctx) : boolean {
return predicate(ctx.code);
};
}
else {
ifPredicate = () => true;
}
return this.if(ifPredicate, statusAction);
}
public informational(infoAction: (result : IApiClientResult) => void) : ApiClient {
return this.ifStatus((code) => code >= 100 && code <= 199,
infoAction);
}
public insufficientStorage(insufficientAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(507, insufficientAction);
}
public internalServerError(errAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(500, errAction);
}
public locked(lockedAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(423, lockedAction);
}
public logActions = [];
public methodNotAllowed(notAllowedAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(405, notAllowedAction);
}
public notFound(notFoundAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(404, notFoundAction);
}
public notImplemented(notImplementedAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(501, notImplementedAction);
}
public ok(okAction : (result : IApiClientResult) => void) : ApiClient {
this.status(200, okAction);
this.status(204, okAction);
this.status(205, okAction);
return this;
}
protected onLog(msg : ILogMessage) {
invokeLogActions(this, msg);
}
public params: any;
public partialContent(partialAction: (result : IApiClientResult) => void) : IApiClient {
return this.status(206, partialAction);
}
public patch(opts? : IRequestOptions) {
return this.request("PATCH", opts);
}
public payloadTooLarge(tooLargeAction: (result : IApiClientResult) => void) : ApiClient {
return this.status(413, tooLargeAction);
}
public post(opts? : IRequestOptions) {
return this.request("POST", opts);
}
public put(opts? : IRequestOptions) {
return this.request("PUT", opts);
}
public redirection(redirectAction : (result : IApiClientResult) => void) : ApiClient {
return this.ifStatus((code) => code >= 300 && code <= 399,
redirectAction);
}
public request(method : any, opts? : IRequestOptions) {
var me = this;
var convertToString = function(val: any) : string {
if (TypeUtils.isNullOrUndefined(val)) {
return null;
}
if (typeof val !== "string") {
val = JSON.stringify(getOwnProperties(val));
}
return val;
};
var url = this.baseUrl;
var route = me.route;
if (!isEmptyString(route)) {
if ("/" !== url.substring(url.length - 1)) {
url += "/";
}
// collect route parameters
var routeParams = {};
if (!TypeUtils.isNullOrUndefined(opts)) {
var allRouteParams = [getOwnProperties(me.routeParams), getOwnProperties(opts.routeParams)];
for (var i = 0; i < allRouteParams.length; i++) {
var routeParamsTemp = allRouteParams[i];
if (TypeUtils.isNullOrUndefined(routeParamsTemp)) {
continue;
}
var alreadyHandledParamNames = {};
for (var rpt in routeParamsTemp) {
var routeParamName = rpt.toLowerCase().trim();
if (alreadyHandledParamNames[routeParamName] === true) {
throw "Route parameter '" + routeParamName + "' is ALREADY defined!";
}
routeParams[routeParamName] = routeParamsTemp[rpt];
alreadyHandledParamNames[routeParamName] = true;
}
}
}
// parse route parameters
route = route.replace(/{(([^\:]+))(\:)?([^}]*)}/g, function(match, paramName, formatSeparator, formatExpr) : string {
paramName = paramName.toLowerCase().trim();
var paramValue = routeParams[paramName];
var funcDepth = -1;
while (typeof paramValue === "function") {
paramValue = paramValue(paramName, routeParams, match, formatExpr, ++funcDepth);
}
if (formatSeparator === ':') {
// use format providers
for (var i = 0; i < me.formatProviders.length; i++) {
var fp = me.formatProviders[i];
var fpCtx = new FormatProviderContext(formatExpr, paramValue);
var fpResult = fp(fpCtx);
if (fpCtx.handled) {
// handled: first wins
paramValue = fpResult;
break;
}
}
}
if (paramValue === undefined) {
throw "Route parameter '" + paramName + "' is NOT defined!";
}
return convertToString(paramValue);
});
url += route;
}
var httpRequestOpts : any = {};
// request headers
httpRequestOpts.headers = {};
{
var allRequestHeaders = [getOwnProperties(me.headers)];
if (!TypeUtils.isNullOrUndefined(opts)) {
allRequestHeaders.push(getOwnProperties(opts.headers));
}
for (var i = 0; i < allRequestHeaders.length; i++) {
var requestHeaders = allRequestHeaders[i];
if (TypeUtils.isNullOrUndefined(requestHeaders)) {
continue;
}
for (var rqh in requestHeaders) {
httpRequestOpts.headers[rqh] = requestHeaders[rqh];
}
}
}
// URL parameters
{
var allUrlParams = [getOwnProperties(me.params)];
if (!TypeUtils.isNullOrUndefined(opts)) {
allUrlParams.push(getOwnProperties(opts.params));
}
var urlParamCount = 0;
var urlParamSuffix = "?";
for (var i = 0; i < allUrlParams.length; i++) {
var urlParams = allUrlParams[i];
if (TypeUtils.isNullOrUndefined(urlParams)) {
continue;
}
for (var up in urlParams) {
if (urlParamCount > 0) {
urlParamSuffix += "&";
}
var urlParamName = up;
var funcDepth = 0;
var urlParamValue = urlParams[up];
while (typeof urlParamValue === "function") {
urlParamValue = urlParamValue(urlParamName, urlParamCount, funcDepth++);
}
urlParamSuffix += urlParamName + "=" + urlParamValue;
++urlParamCount;
}
}
if (urlParamCount > 0) {
url += urlParamSuffix;
}
}
if (!TypeUtils.isNullOrUndefined(opts)) {
// timeout
if (!TypeUtils.isNullOrUndefined(opts.timeout)) {
httpRequestOpts.timeout = opts.timeout;
}
}
var authorizer = me.authorizer;
var content;
var encoding = "utf-8";
var tag;
var contentConverter = (c) => c;
if (!TypeUtils.isNullOrUndefined(opts)) {
content = opts.content;
tag = opts.tag;
// encoding
if (!isEmptyString(opts.encoding)) {
encoding = opts.encoding.toLowerCase().trim();
}
// request type
if (!TypeUtils.isNullOrUndefined(opts.type)) {
switch (opts.type) {
case HttpRequestType.Binary:
httpRequestOpts.headers["Content-type"] = "application/octet-stream";
break;
case HttpRequestType.JSON:
httpRequestOpts.headers["Content-type"] = "application/json; charset=" + encoding;
contentConverter = function(c) {
if (null !== c) {
c = JSON.stringify(c);
}
return c;
};
break;
case HttpRequestType.Text:
httpRequestOpts.headers["Content-type"] = "text/plain; charset=" + encoding;
contentConverter = function(c) {
return convertToString(c);
};
break;
case HttpRequestType.Xml:
httpRequestOpts.headers["Content-type"] = "text/xml; charset=" + encoding;
contentConverter = function(c) {
c = convertToString(c);
if (null !== c) {
var isValidXml = true;
var xmlParser = new Xml.XmlParser(() => {}, function(error: Error) {
isValidXml = false;
});
xmlParser.parse(c);
if (!isValidXml) {
throw "XML parse error.";
}
}
return c;
};
break;
}
}
authorizer = opts.authorizer || authorizer;
}
// authorization
if (!TypeUtils.isNullOrUndefined(authorizer)) {
authorizer.prepare(httpRequestOpts);
}
if (TypeUtils.isNullOrUndefined(content)) {
content = null;
}
httpRequestOpts.url = encodeURI(url);
httpRequestOpts.method = methodToString(method);
httpRequestOpts.content = contentConverter(content);
// before send actions
for (var i = 0; i < me.beforeSendActions.length; i++) {
var bsa = me.beforeSendActions[i];
bsa(httpRequestOpts, tag);
}
var httpReq = new HttpRequest(me, httpRequestOpts);
me.dbg("URL: " + httpRequestOpts.url, "HttpRequestOptions");
me.dbg("Method: " + httpRequestOpts.method, "HttpRequestOptions");
for (var rp in routeParams) {
me.dbg("RouteParameter[" + rp + "]: " + routeParams[rp], "HttpRequestOptions");
}
if (!TypeUtils.isNullOrUndefined(urlParams)) {
for (var up in urlParams) {
me.dbg("UrlParameter[" + up + "]: " + urlParams[up], "HttpRequestOptions");
}
}
var getLogTag = function() : string {
return "HttpRequest::" + httpRequestOpts.url;
};
var invokeComplete = function(result: ApiClientResult, err: ApiClientError) {
if (!TypeUtils.isNullOrUndefined(result)) {
result.setContext(ApiClientResultContext.Complete);
}
if (!TypeUtils.isNullOrUndefined(me.completeAction)) {
me.completeAction(new ApiClientCompleteContext(me, httpReq,
result, err,
tag));
}
};
try {
HTTP.request(httpRequestOpts)
.then(function (response) {
var result = new ApiClientResult(me, httpReq, response,
tag);
result.setContext(ApiClientResultContext.Success);
me.dbg("Status code: " + result.code, getLogTag());
for (var h in getOwnProperties(result.headers)) {
me.trace("ResponseHeader['" + h + "']: " + result.headers[h], getLogTag());
}
// collect "conditional" actions that should be
// invoked instead of "success" action
var ifActions = [];
for (var i = 0; i < me.ifEntries.length; i++) {
var ie = me.ifEntries[i];
if (!TypeUtils.isNullOrUndefined(ie.action)) {
var statusPredicate = ie.predicate;
if (TypeUtils.isNullOrUndefined(statusPredicate)) {
statusPredicate = () => true;
}
if (statusPredicate(result)) {
ifActions.push(ie.action);
}
}
}
// process "conditional" actions
for (var i = 0; i < ifActions.length; i++) {
var ia = ifActions[i];
ia(result);
}
if (ifActions.length < 1 &&
!TypeUtils.isNullOrUndefined(me.successAction)) {
me.successAction(result);
}
invokeComplete(result, undefined);
},
function (err) {
me.err("[ERROR]: " + err, getLogTag());
var errCtx = new ApiClientError(me, httpReq,
err, ApiClientErrorContext.ClientError,
tag);
if (!TypeUtils.isNullOrUndefined(me.errorAction)) {
errCtx.handled = true;
me.errorAction(errCtx);
}
if (!errCtx.handled) {
throw err;
}
invokeComplete(undefined, errCtx);
});
}
catch (e) {
me.crit("[FATAL ERROR]: " + e, getLogTag());
var errCtx = new ApiClientError(me, httpReq,
e, ApiClientErrorContext.Exception,
tag);
if (!TypeUtils.isNullOrUndefined(me.errorAction)) {
errCtx.handled = true;
me.errorAction(errCtx);
}
if (!errCtx.handled) {
throw e;
}
invokeComplete(undefined, errCtx);
}
}
public route: string;
public routeParams: any;
public setAuthorizer(newAuthorizer: IAuthorizer) : ApiClient {
this.authorizer = newAuthorizer;
return this;
}
public serverError(serverErrAction : (result : IApiClientResult) => void): ApiClient {
return this.ifStatus((code) => code >= 500 && code <= 599,
serverErrAction);
}
public serviceUnavailable(unavailableAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(503, unavailableAction);
}
public setBaseUrl(newValue: string) : ApiClient {
this.baseUrl = newValue;
return this;
}
public setRoute(newValue : string) : ApiClient {
this.route = newValue;
return this;
}
public status(code: number, statusAction : (result : IApiClientResult) => void) : ApiClient {
this.ifStatus((sc) => code == sc,
statusAction);
return this;
}
public succeededRequest(succeededAction : (result : IApiClientResult) => void): ApiClient {
return this.ifStatus((code) => code >= 200 && code <= 299,
succeededAction);
}
public success(successAction: (result : IApiClientResult) => void) : ApiClient {
this.successAction = successAction;
return this;
}
public successAction: (ctx : IApiClientResult) => void;
public tooManyRequests(tooManyAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(429, tooManyAction);
}
public unauthorized(unauthorizedAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(401, unauthorizedAction);
}
public unsupportedMediaType(unsupportedAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(415, unsupportedAction);
}
public uriTooLong(tooLongAction : (result : IApiClientResult) => void) : ApiClient {
return this.status(414, tooLongAction);
}
}
class ApiClientCompleteContext extends LoggerBase implements IApiClientCompleteContext {
private _client: ApiClient;
private _error: ApiClientError;
private _request: HttpRequest;
private _result: ApiClientResult;
private _tag: any;
constructor(client: ApiClient, request: HttpRequest, result: ApiClientResult, err: ApiClientError,
tag: any) {
super();
this._client = client;
this._request = request;
this._result = result;
this._error = err;
this._tag = tag;
}
public get client() : ApiClient {
return this._client;
}
protected createLogMessage(msg: any, tag: string,
category : LogCategory, priority : LogPriority) : ILogMessage {
return new LogMessage(LogSource.Complete,
new Date(),
msg, tag,
category, priority);
}
public get error(): ApiClientError {
return this._error;
}
protected onLog(msg: ILogMessage) {
invokeLogActions(this._client, msg);
}
public get request(): HttpRequest {
return this._request;
}
public get result(): ApiClientResult {
return this._result;
}
public get tag(): any {
return this._tag;
}
}
class ApiClientError extends LoggerBase implements IApiClientError {
private _client: ApiClient;
private _context: ApiClientErrorContext;
private _error: any;
private _request: HttpRequest;
private _tag: any;
constructor(client : ApiClient, request: HttpRequest, error: any, ctx: ApiClientErrorContext,
tag: any) {
super();
this._client = client;
this._request = request;
this._error = error;
this._context = ctx;
this._tag = tag;
}
public get client(): IApiClient {
return this._client;
}
public get context() : ApiClientErrorContext {
return this._context;
}
protected createLogMessage(msg: any, tag: string,
category : LogCategory, priority : LogPriority) : ILogMessage {
return new LogMessage(LogSource.Error,
new Date(),
msg, tag,
category, priority);
}
public get error() : any {
return this._error;
}
public handled: boolean = false;
protected onLog(msg : ILogMessage) {
invokeLogActions(this._client, msg);
}
public get request() : HttpRequest {
return this._request;
}
public get tag() : any {
return this._tag;
}
}
/**
* List of API client result contextes.
*/
export enum ApiClientResultContext {
/**
* "success" action.
*/
Success,
/**
* "completed" action.
*/
Complete
}
/**
* List of API client error contextes.
*/
export enum ApiClientErrorContext {
/**
* Error in HTTP client.
*/
ClientError,
/**
* "Unhandled" exception.
*/
Exception
}
class ApiClientResult extends LoggerBase implements IApiClientResult {
private _client: ApiClient;
private _context: ApiClientResultContext;
private _reponse: HTTP.HttpResponse;
private _request: HttpRequest;
private _tag: any;
constructor(client : ApiClient, request: HttpRequest, response: HTTP.HttpResponse,
tag: any) {
super();
this._client = client;
this._request = request;
this._reponse = response;
this._tag = tag;
}
public get client() : ApiClient {
return this._client;
}
public get code(): number {
return this._reponse.statusCode;
}
public get content() : any {
if (TypeUtils.isNullOrUndefined(this._reponse.content.raw)) {
return null;
}
return this._reponse.content.raw;
}
public get context() : ApiClientResultContext {
return this._context;
}
protected createLogMessage(msg: any, tag: string,
category : LogCategory, priority : LogPriority) : ILogMessage {
return new LogMessage(LogSource.Result,
new Date(),
msg, tag,
category, priority);
}
public getAjaxResult<TData>() : IAjaxResult<TData> {
return this.getJSON<IAjaxResult<TData>>();
}
public getFile(destFile?: string) : FileSystem.File {
if (arguments.length < 1) {
return this._reponse.content.toFile();
}
this._reponse.headers
return this._reponse.content.toFile(destFile);
}
public getImage(): Promise<Image.ImageSource> {
return this._reponse.content.toImage();
}
public getJSON<T>() : T {
var json = this._reponse.content.toString();
if (isEmptyString(json)) {
return null;
}
return JSON.parse(json);
}
public getString() : string {
var str = this._reponse.content.toString();
if (TypeUtils.isNullOrUndefined(str)) {
return null;
}
return str;
}
public get headers(): HTTP.Headers {
return this._reponse.headers;
}
protected onLog(msg : ILogMessage) {
invokeLogActions(this._client, msg);
}
public get request() : HttpRequest {
return this._request;
}
public get response() : HTTP.HttpResponse {
return this._reponse;
}
public setContext(newValue : ApiClientResultContext) {
this._context = newValue;
}
public get tag() : any {
return this._tag;
}
}
/**
* An authorizer for basic authentication.
*/
export class BasicAuth implements IAuthorizer {
private _password : string;
private _username : string;
/**
* Initializes a new instance of that class.
*
* @param {String} username The username.
* @param {String} pwd The password.
*/
constructor(username : string, pwd : string) {
this._username = username;
this._password = pwd;
}
/**
* Gets the password.
*
* @property
*/
public get password() : string {
return this._password;
}
/** @inheritdoc */
public prepare(reqOpts : HTTP.HttpRequestOptions) {
reqOpts.headers["Authorization"] = "Basic " + encodeBase64(this._username + ":" + this._password);
}
/**
* Gets the username.
*
* @property
*/
public get username() : string {
return this._username;
}
}
/**
* An authorizer for bearer authentication.
*/
export class BearerAuth implements IAuthorizer {
private _token : string;
/**
* Initializes a new instance of that class.
*
* @param {String} token The token.
*/
constructor(token : string) {
this._token = token;
}
/** @inheritdoc */
public prepare(reqOpts : HTTP.HttpRequestOptions) {
reqOpts.headers["Authorization"] = "Bearer " + this._token;
}
/**
* Gets the token.
*
* @property
*/
public get token() : string {
return this._token;
}
}
class FormatProviderContext implements IFormatProviderContext {
private _expression: string;
private _value: any;
constructor(expr: string, val: any) {
this._expression = expr;
this._value = val;
}
public get expression(): string {
return this._expression;
}
public handled: boolean = false;
public get value(): any {
return this._value;
}
}
/**
* List of known HTTP request methods.
*/
export enum HttpMethod {
GET,
POST,
PUT,
PATCH,
DELETE,
HEAD,
TRACE,
OPTIONS,
CONNECT
}
class HttpRequest implements IHttpRequest {
private _client: ApiClient;
private _opts: HTTP.HttpRequestOptions;
constructor(client: ApiClient, reqOpts : HTTP.HttpRequestOptions) {
this._client = client;
this._opts = reqOpts;
}
public get body() : any {
return this._opts.content;
}
public get client() : ApiClient {
return this._client;
}
public get headers(): any {
return this._opts.headers;
}
public get method(): string {
return this._opts.method;
}
public get url(): string {
return this._opts.url;
}
}
/**
* List of known HTTP request / content types.
*/
export enum HttpRequestType {
/**
* Raw / binary
*/
Binary,
/**
* JSON
*/
JSON,
/**
* Xml
*/
Xml,
/**
* Text / string
*/
Text
}
/**
* List of known HTTP status codes.
*/
export enum HttpStatusCode {
Accepted = 202,
BadGateway = 502,
BadRequest = 400,
Conflict = 409,
Continue = 100,
Created = 201,
ExpectationFailed = 417,
Forbidden = 403,
GatewayTimeout = 504,
Gone = 410,
HttpVersionNotSupported = 505,
InternalServerError = 500,
LengthRequired = 411,
MethodNotAllowed = 405,
MovedPermanently = 301,
MultipleChoices = 300,
NoContent = 204,
NonAuthoritativeInformation = 203,
NotAcceptable = 406,
NotFound = 404,
NotImplemented = 501,
NotModified = 304,
OK = 200,
PartialContent = 206,
PaymentRequired = 402,
PreconditionFailed = 412,
ProxyAuthenticationRequired = 407,
Redirect = 302,
RequestedRangeNotSatisfiable = 416,
RequestEntityTooLarge = 413,
RequestTimeout = 408,
RequestUriTooLong = 414,
ResetContent = 205,
SeeOther = 303,
ServiceUnavailable = 503,
SwitchingProtocols = 101,
TemporaryRedirect = 307,
Unauthorized = 401,
UnsupportedMediaType = 415,
Unused = 306,
UpgradeRequired = 426,
UseProxy = 305,
}
/**
* A helper object for wrapping API results.
*/
export interface IAjaxResult<TData> {
/**
* Gets the code (if defined).
*
* @property
*/
code? : number;
/**
* Gets the message (if defined).
*
* @property
*/
msg?: string;
/**
* The result data (if defined).
*
* @property
*/
data?: TData;
}
/**
* Describes an API client.
*/
export interface IApiClient {
/**
* Adds a callback that can be used to format values of route parameters, e.g.
*
* @chainable
*
* @param {Function} provider The callback that formats values.
*/
addFormatProvider(provider: (ctx: IFormatProviderContext) => any) : IApiClient;
/**
* Adds a log action.
*
* @chainable
*
* @param {Function} logAction The log action.
*/
addLogger(logAction : (ctx : ILogMessage) => void) : IApiClient;
/**
* Gets or sets the deault authorizer.
*/
authorizer: IAuthorizer;
/**
* Short hand method to define an action that is invoked
* for a status code 502 (bad gateway).
*
* @chainable
*
* @param {Function} badGatewayAction The action to invoke.
*/
badGateway(badGatewayAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 400 (bad request).
*
* @chainable
*
* @param {Function} notFoundAction The action to invoke.
*/
badRequest(badRequestAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Gets or sets the base URL.
*/
baseUrl : string;
/**
* Defines an action that is invoked BEFORE a request starts.
*
* @chainable
*
* @param {Function} beforeAction The action to invoke.
*/
beforeSend(beforeAction : (opts : HTTP.HttpRequestOptions, tag: any) => void) : IApiClient;
/**
* Defines an action that is invoked on a status code between 400 and 499.
*
* @chainable
*
* @param {Function} clientErrAction The action to invoke.
*/
clientError(clientErrAction : (result : IApiClientResult) => void): IApiClient;
/**
* Defines an action that is invoked on a status code between 400 and 599.
*
* @chainable
*
* @param {Function} clientSrvErrAction The action to invoke.
*/
clientOrServerError(clientSrvErrAction : (result : IApiClientResult) => void): IApiClient;
/**
* Defines the "complete" action.
*
* @chainable
*
* @param {Function} completeAction The action to invoke.
*/
complete(completeAction : (ctx : IApiClientCompleteContext) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 409 (conflict).
*
* @chainable
*
* @param {Function} conflictAction The action to invoke.
*/
conflict(conflictAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Starts a DELETE request.
*
* @param {IRequestOptions} [opts] The (additional) options.
*/
delete(opts? : IRequestOptions);
/**
* Defines the "error" action.
*
* @chainable
*
* @param {Function} errAction The action to invoke.
*/
error(errAction : (ctx : IApiClientError) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 403 (forbidden).
*
* @chainable
*
* @param {Function} forbiddenAction The action to invoke.
*/
forbidden(forbiddenAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 504 (gateway timeout).
*
* @chainable
*
* @param {Function} timeoutAction The action to invoke.
*/
gatewayTimeout(timeoutAction: (result : IApiClientResult) => void) : IApiClient;
/**
* Starts a GET request.
*
* @param {IRequestOptions} [opts] The (additional) options.
*/
get(opts? : IRequestOptions);
/**
* Short hand method to define an action that is invoked
* for a status code 410 (gone).
*
* @chainable
*
* @param {Function} goneAction The action to invoke.
*/
gone(goneAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Gets or sets the global request headers.
*
* @property
*/
headers: any;
/**
* Invokes an action if a predicate matches.
*
* @chainable
*
* @param {Function} predicate The predicate to use.
* @param {Function} statusAction The action to invoke.
*/
if(predicate: (ctx : IApiClientResult) => boolean,
statusAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Invokes an action if a status matches.
*
* @chainable
*
* @param {Function} predicate The predicate to use.
* @param {Function} statusAction The action to invoke.
*/
ifStatus(predicate: (code : number) => boolean,
statusAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Defines an action that is invoked on a status code between 100 and 199.
*
* @chainable
*
* @param {Function} infoAction The action to invoke.
*/
informational(infoAction: (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 507 (insufficient storage).
*
* @chainable
*
* @param {Function} insufficientAction The action to invoke.
*/
insufficientStorage(insufficientAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 500 (internal server error).
*
* @chainable
*
* @param {Function} errAction The action to invoke.
*/
internalServerError(errAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 423 (document not found).
*
* @chainable
*
* @param {Function} lockedAction The action to invoke.
*/
locked(lockedAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 405 (method not allowed).
*
* @chainable
*
* @param {Function} notAllowedAction The action to invoke.
*/
methodNotAllowed(notAllowedAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 404 (document not found).
*
* @chainable
*
* @param {Function} notFoundAction The action to invoke.
*/
notFound(notFoundAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 501 (not implemented).
*
* @chainable
*
* @param {Function} notImplementedAction The action to invoke.
*/
notImplemented(notImplementedAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 200, 204 or 205 (OK; no content; reset content).
*
* @chainable
*
* @param {Function} okAction The action to invoke.
*/
ok(okAction: (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 413 (payload too large).
*
* @chainable
*
* @param {Function} tooLargeAction The action to invoke.
*/
payloadTooLarge(tooLargeAction: (result : IApiClientResult) => void) : IApiClient;
/**
* Gets or sets the global list of URL parameters.
*
* @property
*/
params: any;
/**
* Short hand method to define an action that is invoked
* for a status code 206 (partial content).
*
* @chainable
*
* @param {Function} partialAction The action to invoke.
*/
partialContent(partialAction: (result : IApiClientResult) => void) : IApiClient;
/**
* Starts a PATCH request.
*
* @param {IRequestOptions} [opts] The (additional) options.
*/
patch(opts? : IRequestOptions);
/**
* Starts a POST request.
*
* @param {IRequestOptions} [opts] The (additional) options.
*/
post(opts? : IRequestOptions);
/**
* Starts a PUT request.
*
* @param {IRequestOptions} [opts] The (additional) options.
*/
put(opts? : IRequestOptions);
/**
* Defines an action that is invoked on a status code between 300 and 399.
*
* @chainable
*
* @param {Function} redirectAction The action to invoke.
*/
redirection(redirectAction : (result : IApiClientResult) => void): IApiClient;
/**
* Starts a request.
*
* @param any method The HTTP method.
* @param {IRequestOptions} [opts] The (additional) options.
*/
request(method : any, opts? : IRequestOptions);
/**
* Gets or sets the route.
*/
route: string;
/**
* Gets or sets the global list of route parameters.
*
* @property
*/
routeParams: any;
/**
* Defines an action that is invoked on a status code between 500 and 599.
*
* @chainable
*
* @param {Function} serverErrAction The action to invoke.
*/
serverError(serverErrAction : (result : IApiClientResult) => void): IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 503 (service unavailable).
*
* @chainable
*
* @param {Function} unavailableAction The action to invoke.
*/
serviceUnavailable(unavailableAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Sets the default authorizer.
*
* @chainable
*
* @param {IAuthorizer} authorizer The default authorizer.
*/
setAuthorizer(authorizer: IAuthorizer) : IApiClient;
/**
* Sets the base URL.
*
* @chainable
*
* @param {String} newValue The new URL.
*/
setBaseUrl(newValue : string) : IApiClient;
/**
* Sets the route.
*
* @chainable
*
* @param {String} newValue The new route.
*/
setRoute(newValue : string) : IApiClient;
/**
* Defines an action that is invoked for a specific status code.
*
* @chainable
*
* @param {Number} code The status code.
* @param {Function} statusAction The action to invoke.
*/
status(code: number,
statusAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Defines an action that is invoked on a status code between 200 and 299.
*
* @chainable
*
* @param {Function} succeededAction The action to invoke.
*/
succeededRequest(succeededAction : (result : IApiClientResult) => void): IApiClient;
/**
* Defines the "success" action.
*
* @chainable
*
* @param {Function} successAction The action to invoke.
*/
success(successAction : (result: IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 429 (too many requests).
*
* @chainable
*
* @param {Function} tooManyAction The action to invoke.
*/
tooManyRequests(tooManyAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 401 (unauthorized).
*
* @chainable
*
* @param {Function} unauthorizedAction The action to invoke.
*/
unauthorized(unauthorizedAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 415 (unsupported media type).
*
* @chainable
*
* @param {Function} unsupportedAction The action to invoke.
*/
unsupportedMediaType(unsupportedAction : (result : IApiClientResult) => void) : IApiClient;
/**
* Short hand method to define an action that is invoked
* for a status code 414 (URI too long).
*
* @chainable
*
* @param {Function} tooLongAction The action to invoke.
*/
uriTooLong(tooLongAction : (result : IApiClientResult) => void) : IApiClient;
}
/**
* Describes a context of a "complete" action.
*/
export interface IApiClientCompleteContext extends ILogger, ITagProvider {
/**
* Gets the underlying API client.
*
* @property
*/
client: IApiClient;
/**
* Gets the error context (if defined).
*
* @property
*/
error?: IApiClientError;
/**
* Gets the underlying HTTP request.
*
* @property
*/
request: IHttpRequest;
/**
* Gets the API result (if defined).
*
* @property
*/
result?: IApiClientResult;
}
/**
* Describes an object that stores configuration data for an API client.
*/
export interface IApiClientConfig {
/**
* Gets the default authorizer.
*
* @property
*/
authorizer?: IAuthorizer;
/**
* Gets the base URL to use.
*
* @property
*/
baseUrl: string;
/**
* Defines an action that is invoked BEFORE a request starts.
*
* @property
*/
beforeSend? : (opts : HTTP.HttpRequestOptions) => void;
/**
* Defines the action to handle a status code between 400 and 499.
*
* @property
*/
clientError?: (ctx : IApiClientResult) => void;
/**
* Defines the "complete" action.
*
* @property
*/
complete?: (ctx : IApiClientCompleteContext) => void;
/**
* Defines the "error" action.
*
* @property
*/
error?: (ctx : IApiClientError) => void;
/**
* Defines the action to handle a 403 status code.
*
* @property
*/
forbidden?: (ctx : IApiClientResult) => void;
/**
* Gets the global request headers to use.
*
* @property
*/
headers?: any;
/**
* Defines that actions to invoke if a reponse matches.
*/
if? : IIfResponse[];
/**
* Defines that actions to invoke if a status code matches.
*/
ifStatus? : IIfStatus[];
/**
* Defines the action to handle a status code between 300 and 399.
*
* @property
*/
redirection?: (ctx : IApiClientResult) => void;
/**
* Defines the action to handle a 404 status code.
*
* @property
*/
notFound?: (ctx : IApiClientResult) => void;
/**
* Defines the action to handle a 200, 204 or 205 status code.
*
* @property
*/
ok?: (ctx : IApiClientResult) => void;
/**
* Gets the global URL parameters to use.
*
* @property
*/
params?: any;
/**
* Gets the optional route.
*
* @property
*/
route?: string;
/**
* Gets the global route parameters to use.
*
* @property
*/
routeParams?: any;
/**
* Defines the action to handle a status code between 500 and 599.
*
* @property
*/
serverError?: (ctx : IApiClientResult) => void;
/**
* Defines the action to handle a status code between 200 and 299.
*
* @property
*/
succeededRequest?: (ctx : IApiClientResult) => void;
/**
* Defines the "success" action.
*
* @property
*/
success?: (ctx : IApiClientResult) => void;
/**
* Defines the action to handle a 401 status code.
*
* @property
*/
unauthorized?: (ctx : IApiClientResult) => void;
}
/**
* Describes an error context of an API call.
*/
export interface IApiClientError extends ILogger, ITagProvider {
/**
* Gets the underlying client.
*
* @property
*/
client: IApiClient;
/**
* Gets the context.
*
* @property
*/
context: ApiClientErrorContext;
/**
* Gets the error data.
*
* @property
*/
error: any;
/**
* Gets or sets if error has been handled or not.
*
* @property
*/
handled: boolean;
/**
* Gets the underlying HTTP request.
*
* @property
*/
request: IHttpRequest;
}
/**
* Describes an API result.
*/
export interface IApiClientResult extends ILogger, ITagProvider {
/**
* Gets the underlying API client.
*
* @property
*/
client: IApiClient;
/**
* Gets the HTTP response code.
*
* @property
*/
code: number;
/**
* Gets the raw content.
*
* @property
*/
content: any;
/**
* Gets the underlying (execution) context.
*
* @property
*/
context: ApiClientResultContext;
/**
* Gets the response headers.
*
* @property
*/
headers: HTTP.Headers;
/**
* Returns the content as wrapped AJAX result object.
*
* @return {IAjaxResult<TData>} The ajax result object.
*/
getAjaxResult<TData>() : IAjaxResult<TData>;
/**
* Returns the content as file.
*
* @param {String} [destFile] The custom path of the destination file.
*
* @return {FileSystem.File} The file.
*/
getFile(destFile?: string) : FileSystem.File;
/**
* Tries result the content as image source.
*
* @return {Promise<Image.ImageSource>} The result.
*/
getImage(): Promise<Image.ImageSource>;
/**
* Returns the content as JSON object.
*
* @return {T} The JSON object.
*/
getJSON<T>() : T;
/**
* Returns the content as string.
*
* @return {String} The string.
*/
getString() : string;
/**
* Gets the information about the request.
*
* @property
*/
request: IHttpRequest;
/**
* Gets the raw response.
*
* @property
*/
response: HTTP.HttpResponse;
}
/**
* Describes an object that prepares a HTTP for authorization.
*/
export interface IAuthorizer {
/**
* Prepares a HTTP request for authorization.
*
* @param {HTTP.HttpRequestOptions} reqOpts The request options.
*/
prepare(reqOpts: HTTP.HttpRequestOptions);
}
/**
* Describes a format provider context.
*/
export interface IFormatProviderContext {
/**
* Gets the format expression.
*
* @property
*/
expression: string;
/**
* Gets if the expression has been handled or not.
*
* @property
*/
handled: boolean;
/**
* Gets the underlying (unhandled) value.
*
* @property
*/
value: any;
}
/**
* Describes an object that stores information about a HTTP request.
*/
export interface IHttpRequest {
/**
* Gets the raw content that is send to the API.
*/
body: any;
/**
* Gets the underlying client.
*
* @property
*/
client: IApiClient;
/**
* Gets the list of request headers.
*/
headers: any;
/**
* Gets the HTTP method.
*/
method: string;
/**
* Gets the URL.
*/
url: string;
}
/**
* Describes an entry that stores data for
* invoke a response action if a predicate matches.
*/
export interface IIfResponse {
/**
* The action to invoke.
*
* @property
*/
action : (result : IApiClientResult) => void,
/**
* The predicate.
*
* @property
*/
predicate?: (ctx : IApiClientResult) => boolean
}
/**
* Describes an entry that stores data for
* invoke a response action if a status code matches.
*/
export interface IIfStatus {
/**
* The action to invoke.
*
* @property
*/
action : (result : IApiClientResult) => void,
/**
* The predicate.
*
* @property
*/
predicate?: (code : number) => boolean
}
/**
* Describes an object that stores log information.
*/
export interface ILogMessage {
/**
* Gets the category.
*
* @property
*/
category: LogCategory;
/**
* Gets the message value.
*
* @property
*/
message: any;
/**
* Gets the priority.
*
* @property
*/
priority: LogPriority;
/**
* Gets the source.
*/
source: LogSource;
/**
* Gets the tag.
*
* @property
*/
tag: string;
/**
* Gets the timestamp.
*/
time: Date;
}
/**
* Describes a logger.
*/
export interface ILogger {
/**
* Logs an alert message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogPriority} [priority] The optional log priority.
*/
alert(msg : any, tag?: string,
priority?: LogPriority) : ILogger;
/**
* Logs a critical message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogPriority} [priority] The optional log priority.
*/
crit(msg : any, tag?: string,
priority?: LogPriority) : ILogger;
/**
* Logs a debug message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogPriority} [priority] The optional log priority.
*/
dbg(msg : any, tag?: string,
priority?: LogPriority) : ILogger;
/**
* Logs an emergency message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogPriority} [priority] The optional log priority.
*/
emerg(msg : any, tag?: string,
priority?: LogPriority) : ILogger;
/**
* Logs an error message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogPriority} [priority] The optional log priority.
*/
err(msg : any, tag?: string,
priority?: LogPriority) : ILogger;
/**
* Logs an info message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogPriority} [priority] The optional log priority.
*/
info(msg : any, tag?: string,
priority?: LogPriority) : ILogger;
/**
* Logs a message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogCategory} [category] The optional log category. Default: LogCategory.Debug
* @param {LogPriority} [priority] The optional log priority.
*/
log(msg : any, tag?: string,
category?: LogCategory, priority?: LogPriority) : ILogger;
/**
* Logs a notice message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogPriority} [priority] The optional log priority.
*/
note(msg : any, tag?: string,
priority?: LogPriority) : ILogger;
/**
* Logs a trace message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogPriority} [priority] The optional log priority.
*/
trace(msg : any, tag?: string,
priority?: LogPriority) : ILogger;
/**
* Logs a warning message.
*
* @chainable
*
* @param any msg The message value.
* @param {String} [tag] The optional tag value.
* @param {LogPriority} [priority] The optional log priority.
*/
warn(msg : any, tag?: string,
priority?: LogPriority) : ILogger;
}
/**
* Describes an object that stores (additional) options for a request.
*/
export interface IRequestOptions {
/**
* Gets the authorizer.
*
* @property
*/
authorizer? : IAuthorizer;
/**
* Gets the content.
*
* @property
*/
content?: any;
/**
* Gets the name of the encoding.
*
* @property
*/
encoding?: string;
/**
* Gets the list of request headers.
*
* @property
*/
headers? : any;
/**
* Gets the URL params to set.
*
* @property
*/
params?: any;
/**
* Gets the params for the route to set.
*
* @property
*/
routeParams?: any;
/**
* Gets the global object that should be used in any callback.
*
* @property
*/
tag?: any;
/**
* Gets the timeout in millisecons.
*
* @property
*/
timeout?: number;
/**
* Gets request type.
*
* @property
*/
type?: HttpRequestType;
}
/**
* Describes an object that stores a global value.
*/
export interface ITagProvider {
/**
* Gets the value that should be linked with that instance.
*
* @property
*/
tag: any;
}
/**
* List of log categories.
*/
export enum LogCategory {
Emergency = 1,
Alert = 2,
Critical = 3,
Error = 4,
Warning = 5,
Notice = 6,
Info = 7,
Debug = 8,
Trace = 9
}
class LogMessage implements ILogMessage {
private _category : LogCategory;
private _message : any;
private _priority : LogPriority;
private _source : LogSource;
private _tag : string;
private _time : Date;
constructor(source : LogSource,
time: Date,
msg: any, tag: string,
category: LogCategory, priority : LogPriority) {
this._source = source;
this._time = time;
this._message = msg;
this._tag = tag;
this._category = category;
this._priority = priority;
}
public get category(): LogCategory {
return this._category;
}
public get message(): any {
return this._message;
}
public get priority(): LogPriority {
return this._priority;
}
public get source(): LogSource {
return this._source;
}
public get tag(): string {
return this._tag;
}
public get time(): Date {
return this._time;
}
}
/**
* List of log priorities.
*/
export enum LogPriority {
VeryHigh = 1,
High = 2,
Medium = 3,
Low = 4,
VeryLow = 5
}
/**
* List of log (message) source.
*/
export enum LogSource {
/**
* From API client.
*/
Client,
/**
* From "completed" action
*/
Complete,
/**
* From IApiClientError object
*/
Error,
/**
* From IApiClientResult object
*/
Result
}
/**
* OAuth authorizer
*/
export class OAuth implements IAuthorizer {
private _fields = {};
/** @inheritdoc */
public prepare(reqOpts : HTTP.HttpRequestOptions) {
var i = 0;
var fieldList = '';
for (var f in this._fields) {
var v = this._fields[f];
if (i > 0) {
fieldList += ', ';
}
fieldList += f + '=' + '"' + encodeURIComponent(v) + '"';
++i;
}
reqOpts.headers["Authorization"] = 'OAuth ' + fieldList;
}
/**
* Sets a field.
*
* @chainable
*
* @param {String} name The name of the field.
* @param {String} value The value of the field.
*/
public setField(name: string, value: any): OAuth {
this._fields[name] = value;
return this;
}
/**
* Sets a list of fields.
*
* @chainable
*
* @param any ...fields One or more object with fields an their values.
*/
public setMany(...fields: any[]): OAuth {
for (var i = 0; i < fields.length; i++) {
var fieldObj = getOwnProperties(fields[i]);
if (TypeUtils.isNullOrUndefined(fieldObj)) {
continue;
}
for (var f in fieldObj) {
this.setField(f, fieldObj[f]);
}
}
return this;
}
}
/**
* Twitter OAuth authorizer.
*/
export class TwitterOAuth extends OAuth {
private _consumerKey: string;
private _consumerSecret: string;
private _token: string;
private _tokenSecret: string;
/**
* Initializes a new instance of that class.
*
* @param {String} consumerKey The consumer key.
* @param {String} consumerSecret The consumer secret.
* @param {String} token The token.
* @param {String} tokenSecret The token secret.
*/
constructor(consumerKey: string, consumerSecret: string,
token: string, tokenSecret: string) {
super();
this._consumerKey = consumerKey;
this._consumerSecret = consumerSecret;
this._token = token;
this._tokenSecret = tokenSecret;
// initial value for 'nonce' property
const NONCE_CHARS = '0123456789abcdef';
this.nonce = '';
for (var i = 0; i < 32; i++) {
this.nonce += NONCE_CHARS[Math.floor(Math.random() * NONCE_CHARS.length) % NONCE_CHARS.length];
}
}
/** @inheritdoc */
public prepare(reqOpts : HTTP.HttpRequestOptions) {
var timestamp = this.timestamp;
if (TypeUtils.isNullOrUndefined(timestamp)) {
timestamp = new Date();
}
if (!isEmptyString(this._consumerKey)) {
this.setField('oauth_consumer_key', this._consumerKey);
}
if (!TypeUtils.isNullOrUndefined(this.nonce)) {
this.setField('oauth_nonce', this.nonce);
}
if (!TypeUtils.isNullOrUndefined(this.signature)) {
this.setField('oauth_signature', this.signature);
}
if (!isEmptyString(this.signatureMethod)) {
this.setField('oauth_signature_method', this.signatureMethod);
}
this.setField('oauth_timestamp', Math.floor(timestamp.getTime() / 1000.0));
if (!isEmptyString(this._token)) {
this.setField('oauth_token', this._token);
}
if (!isEmptyString(this.version)) {
this.setField('oauth_version', this.version);
}
super.prepare(reqOpts);
}
/**
* Gets or sets the value for "oauth_nonce" (custom random crypto key).
*/
public nonce: string;
/**
* Gets or sets the value for "oauth_signature".
*/
public signature: string;
/**
* Gets or sets the value for "oauth_signature_method".
*/
public signatureMethod: string = 'HMAC-SHA1';
/**
* Gets or sets the value for "oauth_timestamp".
*/
public timestamp: Date;
/**
* Gets or sets the value for "oauth_version".
*/
public version: string = '1.0';
}
function encodeBase64(str: string) {
if (isEmptyString(str)) {
return str;
}
var padChar = '=';
var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var getByte = function(s: string, i: number) {
var cc = s.charCodeAt(i);
if (cc > 255) {
throw "INVALID_CHARACTER_ERR: DOM Exception 5";
}
return cc;
}
var b10, i;
var b64Chars = [];
var iMax = str.length - str.length % 3;
for (i = 0; i < iMax; i += 3) {
b10 = (getByte(str, i) << 16) |
(getByte(str, i + 1) << 8) |
getByte(str, i + 2);
b64Chars.push(alpha.charAt(b10 >> 18));
b64Chars.push(alpha.charAt((b10 >> 12) & 0x3F));
b64Chars.push(alpha.charAt((b10 >> 6) & 0x3f));
b64Chars.push(alpha.charAt(b10 & 0x3f));
}
switch (str.length - iMax) {
case 1:
b10 = getByte(str, i) << 16;
b64Chars.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
padChar + padChar);
break;
case 2:
b10 = (getByte(str, i) << 16) | (getByte(str, i + 1) << 8);
b64Chars.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
alpha.charAt((b10 >> 6) & 0x3F) + padChar);
break;
}
return b64Chars.join('');
}
function getOwnProperties(obj) {
if (TypeUtils.isNullOrUndefined(obj)) {
return undefined;
}
var properties : any = {};
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
properties[p] = obj[p];
}
}
return properties;
}
function invokeLogActions(client : ApiClient, msg : ILogMessage) {
for (var i = 0; i < client.logActions.length; i++) {
try {
var la = client.logActions[i];
la(msg);
}
catch (e) {
console.log("[ERROR] invokeLogActions(" + i +"): " + e);
}
}
}
function isEmptyString(str : string) : boolean {
if (TypeUtils.isNullOrUndefined(str)) {
return true;
}
return "" === str.trim();
}
function methodToString(method : any) : string {
if (TypeUtils.isNullOrUndefined(method)) {
return "GET";
}
if (typeof method !== "string") {
method = HttpMethod[method];
}
return method.toUpperCase().trim();
}
/**
* Creates a new client.
*
* @param any config The configuration data / base URL for the client.
*
* @return {IApiClient} The new client.
*/
export function newClient(config : IApiClientConfig | string) : IApiClient {
var cfg : any = config;
if (typeof cfg === "string") {
cfg = <IApiClientConfig>{
baseUrl: config
};
}
if (TypeUtils.isNullOrUndefined(cfg)) {
cfg = {};
}
return new ApiClient(cfg);
} | the_stack |
import * as Draft from "draft-js";
import * as React from "react";
import { useRef, useState, useCallback, forwardRef, useImperativeHandle } from "react";
import { splice } from "./utils/string";
import defaultImage from "./img/richtext/default.png";
import blackImage from "./img/richtext/black.png";
import whiteImage from "./img/richtext/white.png";
import redImage from "./img/richtext/red.png";
import greenImage from "./img/richtext/green.png";
import blueImage from "./img/richtext/blue.png";
import purpleImage from "./img/richtext/purple.png";
import yellowImage from "./img/richtext/yellow.png";
import AImage from "./img/richtext/A.png";
import BImage from "./img/richtext/B.png";
import SImage from "./img/richtext/S.png";
import CupImage from "./img/richtext/Cup.png";
import CdownImage from "./img/richtext/Cdown.png";
import CleftImage from "./img/richtext/Cleft.png";
import CrightImage from "./img/richtext/Cright.png";
import ZImage from "./img/richtext/Z.png";
import RImage from "./img/richtext/R.png";
import analogImage from "./img/richtext/analog.png";
import coinImage from "./img/richtext/coin.png";
import starImage from "./img/richtext/star.png";
import pauseImage from "./img/richtext/pause.png";
import feedImage from "./img/richtext/feed.png";
import darklightImage from "./img/richtext/darklight.png";
import divotImage from "./img/richtext/divot.png";
import "./css/texteditor.scss";
// Rich text editor for strings in Mario Party.
const {Editor, EditorState, ContentState, SelectionState, Modifier, RichUtils, CompositeDecorator} = Draft;
export enum MPEditorTheme {
Light = 0,
Dark = 1,
};
export enum MPEditorDisplayMode {
Edit = 0,
Readonly = 1,
Display = 2,
};
export enum MPEditorToolbarPlacement {
Top = 0,
Bottom = 1,
};
export interface IMPEditorProps {
value?: string;
id?: string;
theme?: MPEditorTheme;
displayMode?: MPEditorDisplayMode;
showToolbar?: boolean;
toolbarPlacement?: MPEditorToolbarPlacement;
itemBlacklist?: any;
onValueChange?: any;
onBlur?: any;
onFocus?: any;
maxlines?: number;
}
export interface IMPEditorRef {
focus: () => void;
}
/**
* Component for rich text editing.
* Supports controlled or local state editing.
*/
export const MPEditor = forwardRef<IMPEditorRef, IMPEditorProps>((props, ref) => {
const editor = useRef<Draft.Editor | null>(null);
const focus = useCallback(() => {
editor.current?.focus();
}, []);
useImperativeHandle(ref, () => ({
focus
}), [focus]);
const plaintextRef = useRef<string | undefined>(props.value);
const createEditorStateFromProps = useCallback(() => {
if (props.value) {
return MPEditorStringAdapter.stringToEditorState(props.value);
}
else {
return EditorState.createEmpty();
}
}, [props.value]);
const [editorStateValue, setEditorStateValue] = useState(createEditorStateFromProps);
// Compute effective state, based on whether component is controlled or not.
let editorState: Draft.EditorState;
if ("value" in props) {
if (props.value !== plaintextRef.current) {
editorState = createEditorStateFromProps();
}
else {
editorState = editorStateValue;
}
}
else {
editorState = editorStateValue;
}
const [theme, setTheme] = useState(() => {
// Take a specified theme, or make an educated guess.
let theme: MPEditorTheme = props.theme as MPEditorTheme;
if (typeof props.theme !== "number") {
if (props.value && props.value.indexOf("WHITE") >= 0)
theme = MPEditorTheme.Dark;
else
theme = MPEditorTheme.Light;
}
return theme;
});
const onChange = (newEditorState: Draft.EditorState) => {
const newStringValue = MPEditorStringAdapter.editorStateToString(newEditorState, {
theme,
});
plaintextRef.current = newStringValue;
setEditorStateValue(newEditorState);
if (props.onValueChange) {
props.onValueChange(props.id, newStringValue);
}
};
const handleReturn = (e: any, editorState: any) => {
if (props.maxlines) {
let text = editorState.getCurrentContent().getPlainText();
// = because Return would create an additional line
if (text.split("\n").length >= props.maxlines)
return "handled";
}
return "not-handled";
};
const onFocus = (event: any) => {
if (props.onFocus)
props.onFocus(event);
};
const onBlur = (event: any) => {
if (props.onBlur)
props.onBlur(event);
};
const onToolbarClick = (item: IToolbarItem) => {
switch (item.type) {
case "COLOR":
toggleColor(item.key);
break;
case "IMAGE":
addImage(item.char!);
break;
case "ACTION":
switch (item.key) {
case "DARKLIGHT":
const nextTheme = theme === MPEditorTheme.Light
? MPEditorTheme.Dark
: MPEditorTheme.Light;
setTheme(nextTheme);
break;
}
break;
}
setTimeout(() => {
focus();
}, 0);
};
const toggleColor = (toggledColor: string) => {
const selection = editorState.getSelection();
const prevContentState = editorState.getCurrentContent();
// Let's just allow one color at a time. Turn off all active colors.
const nextContentState = Object.keys(colorStyleMap).reduce((contentState, color) => {
return Modifier.removeInlineStyle(contentState, selection, color)
}, prevContentState);
let nextEditorState = EditorState.push(
editorState,
nextContentState,
'change-inline-style'
);
const currentStyle = editorState.getCurrentInlineStyle();
// Unset style override for current color.
if (selection.isCollapsed()) {
nextEditorState = currentStyle.reduce((state, color) => {
return RichUtils.toggleInlineStyle(state!, color!);
}, nextEditorState);
}
// If the color is being toggled on, apply it.
if (!currentStyle.has(toggledColor)) {
nextEditorState = RichUtils.toggleInlineStyle(
nextEditorState,
toggledColor
);
}
onChange(nextEditorState);
};
const addImage = (char: string) => {
const selection = editorState.getSelection();
// Insert a character that will be styled into an image.
const nextContentState = Modifier.replaceText(
editorState.getCurrentContent(),
selection,
char
);
let nextEditorState = EditorState.push(
editorState,
nextContentState,
"insert-characters"
);
onChange(nextEditorState);
};
const displayMode = props.displayMode || MPEditorDisplayMode.Edit;
let toolbar;
const showToolbar = props.showToolbar;
if (showToolbar && displayMode === MPEditorDisplayMode.Edit) {
toolbar = (
<MPEditorToolbar onItemClick={onToolbarClick}
itemBlacklist={props.itemBlacklist} />
);
}
const toolbarPlacement = props.toolbarPlacement || MPEditorToolbarPlacement.Top;
let className = "mpEditor";
if (displayMode === MPEditorDisplayMode.Display)
className += " mpDisplay";
if (theme === MPEditorTheme.Light)
className += " mpEditorLight";
else if (theme === MPEditorTheme.Dark)
className += " mpEditorDark";
if (toolbar) {
if (toolbarPlacement === MPEditorToolbarPlacement.Bottom)
className += " mpEditorShowToolbarBottom";
else
className += " mpEditorShowToolbarTop";
}
return (
<div className={className}>
{toolbarPlacement === MPEditorToolbarPlacement.Top && toolbar}
<div className="mpEditorWrapper">
<Editor ref={ref => { editor.current = ref; }}
editorState={editorState}
stripPastedStyles={true}
readOnly={displayMode !== MPEditorDisplayMode.Edit}
customStyleMap={colorStyleMap}
onChange={onChange}
onFocus={onFocus}
onBlur={onBlur}
handleReturn={handleReturn} />
</div>
{toolbarPlacement === MPEditorToolbarPlacement.Bottom && toolbar}
</div>
);
});
function imageStrategy(contentBlock: Draft.ContentBlock, callback: any, contentState: unknown) {
const text = contentBlock.getText();
for (let i = 0; i < text.length; i++) {
if (_ToolbarCharToKey[text.charAt(i)])
callback(i, i + 1);
}
}
const MPImageComponent = (props: any) => {
let ch = props.children[0].props.text; // 1337 draft.js h4x
let className = "mpImage";
let key = _ToolbarCharToKey[ch];
className += " mpImageKey-" + key;
// Stop React warnings from unwanted spreaded props...
let outerSpanProps = {...props};
delete outerSpanProps.contentState;
delete outerSpanProps.decoratedText;
delete outerSpanProps.entityKey;
delete outerSpanProps.offsetKey;
delete outerSpanProps.blockKey;
return (
<span {...outerSpanProps} className={className}>
<span className="mpImageTextWrapper">{props.children}</span>
</span>
);
};
export const MPCompositeDecorator = new CompositeDecorator([
{
strategy: imageStrategy,
component: MPImageComponent,
}
]);
const colorStyleMap: { [name: string]: { color: string } } = {
DEFAULT: {
color: "#200E71",
},
BLACK: {
color: '#000000',
},
WHITE: {
color: '#FFFFFF',
},
RED: {
color: '#E70014',
},
GREEN: {
color: '#00AB29',
},
BLUE: {
color: "#003EF9",
},
PURPLE: {
color: "#E847CD",
},
YELLOW: {
color: '#FFEA38',
},
};
interface IToolbarItem {
key: string;
type: string;
icon: string;
desc: string;
char?: string;
items?: IToolbarItem[];
}
const _ToolbarItems: IToolbarItem[] = [
{ key: "COLOR", type: "SUBMENU", icon: defaultImage, desc: "Font color",
items: [
{ key: "DEFAULT", type: "COLOR", icon: defaultImage, desc: "Default" },
{ key: "BLACK", type: "COLOR", icon: blackImage, desc: "Black" },
{ key: "WHITE", type: "COLOR", icon: whiteImage, desc: "White" },
{ key: "RED", type: "COLOR", icon: redImage, desc: "Red" },
{ key: "GREEN", type: "COLOR", icon: greenImage, desc: "Green" },
{ key: "BLUE", type: "COLOR", icon: blueImage, desc: "Blue" },
{ key: "PURPLE", type: "COLOR", icon: purpleImage, desc: "Purple" },
{ key: "YELLOW", type: "COLOR", icon: yellowImage, desc: "Yellow" },
],
},
{ key: "IMAGE", type: "SUBMENU", icon: AImage, desc: "Insert image",
items: [
{ key: "A", type: "IMAGE", icon: AImage, desc: "A button", "char": "\u3000" },
{ key: "B", type: "IMAGE", icon: BImage, desc: "B button", "char": "\u3001" },
{ key: "S", type: "IMAGE", icon: SImage, desc: "Start button", "char": "\u3010" },
{ key: "CUP", type: "IMAGE", icon: CupImage, desc: "C-up button", "char": "\u3002" },
{ key: "CDOWN", type: "IMAGE", icon: CdownImage, desc: "C-down button", "char": "\u3005" },
{ key: "CLEFT", type: "IMAGE", icon: CleftImage, desc: "C-left button", "char": "\u3004" },
{ key: "CRIGHT", type: "IMAGE", icon: CrightImage, desc: "C-right button", "char": "\u3003" },
{ key: "Z", type: "IMAGE", icon: ZImage, desc: "Z button", "char": "\u3006" },
{ key: "R", type: "IMAGE", icon: RImage, desc: "R button", "char": "\u3011" },
{ key: "ANALOG", type: "IMAGE", icon: analogImage, desc: "Analog stick", "char": "\u3007" },
{ key: "COIN", type: "IMAGE", icon: coinImage, desc: "Coin", "char": "\u3008" },
{ key: "STAR", type: "IMAGE", icon: starImage, desc: "Star", "char": "\u3009" },
],
},
{ key: "ADVANCED", type: "SUBMENU", icon: pauseImage, desc: "Advanced text features",
items: [
{ key: "PAUSE", type: "IMAGE", icon: pauseImage, desc: "Pause to continue", "char": "\u3015" },
{ key: "FEED", type: "IMAGE", icon: feedImage, desc: "Feed new page", "char": "\u3014" },
],
},
{ key: "DARKLIGHT", type: "ACTION", icon: darklightImage, desc: "Toggle background color (has no effect on actual game)" },
];
let _ToolbarCharToKey: { [char: string]: string } = {};
let _ToolbarKeyToChar: { [char: string]: string } = {};
_ToolbarItems.forEach(_populateItemMaps);
function _populateItemMaps(item: any) {
if (item.items) {
item.items.forEach(_populateItemMaps);
}
if (item.char) {
_ToolbarCharToKey[item["char"]] = item.key;
_ToolbarKeyToChar[item.key] = item["char"];
}
}
function _toolbarItemToComponent(item: IToolbarItem, onItemClick: any) {
// if (item.type === "SEP") {
// return (
// <MPEditorToolbarSeparator key={key} />
// );
// }
switch (item.type) {
case "SUBMENU":
return (
<MPEditorToolbarSubmenu key={item.key}
item={item}
onItemClick={onItemClick}
items={item.items!} />
);
default:
return (
<MPEditorToolbarButton key={item.key}
item={item}
onItemClick={onItemClick} />
);
}
}
interface MPEditorToolbarProps {
itemBlacklist: any;
onItemClick: any;
}
class MPEditorToolbar extends React.Component<MPEditorToolbarProps> {
state = {}
render() {
const blacklist = this.props.itemBlacklist;
let items = _ToolbarItems.map(itemDef => {
if (blacklist && blacklist.indexOf(itemDef.key) !== -1) {
return null;
}
return _toolbarItemToComponent(itemDef, this.onItemClick);
});
return (
<div className="mpEditorToolbar">
{items}
</div>
);
}
onItemClick = (item: any) => {
if (this.props.onItemClick)
this.props.onItemClick(item);
}
};
interface MPEditorToolbarSubmenuProps {
item: IToolbarItem;
items: IToolbarItem[];
onItemClick: any;
}
class MPEditorToolbarSubmenu extends React.Component<MPEditorToolbarSubmenuProps> {
private expMenu: HTMLDivElement | null = null;
state = {
expanded: false,
}
render() {
const item = this.props.item;
let expansion;
if (this.state.expanded) {
const submenuItems = this.props.items.map(itemDef => {
return _toolbarItemToComponent(itemDef, this.onItemClick);
});
expansion = (
<div ref={(expMenu => { this.expMenu = expMenu; })}
className="mpEditorToolbarSubmenuExp"
tabIndex={-1}
onBlur={this.onBlur}>
{submenuItems}
</div>
);
}
return (
<div className="mpEditorToolbarButton" title={item.desc} onClick={this.onClick}>
<img src={item.icon} alt={item.desc}></img>
<img src={divotImage} alt="" />
{expansion}
</div>
);
}
componentDidMount() {
if (this.state.expanded)
this.expMenu!.focus();
}
componentDidUpdate() {
if (this.state.expanded)
this.expMenu!.focus();
}
onBlur = () => {
this.setState({ expanded: false });
}
onClick = () => {
this.setState({ expanded: !this.state.expanded });
}
onItemClick = (item: IToolbarItem) => {
if (this.props.onItemClick)
this.props.onItemClick(item);
}
};
interface MPEditorToolbarButtonProps {
item: IToolbarItem;
onItemClick: any;
}
class MPEditorToolbarButton extends React.Component<MPEditorToolbarButtonProps> {
state = {}
onClick = () => {
this.props.onItemClick(this.props.item);
}
render() {
const item = this.props.item;
return (
<div className="mpEditorToolbarButton" title={item.desc} onClick={this.onClick}>
<img src={item.icon} alt={item.desc}></img>
</div>
);
}
};
class MPEditorToolbarSeparator extends React.Component { // eslint-disable-line
state = {}
render() {
return (
<div className="mpEditorToolbarSeparator"></div>
);
}
};
/**
* Converts between game strings and Draft.js editor state.
*/
export const MPEditorStringAdapter = new class MPEditorStringAdapter {
editorStateToString(editorState: Draft.EditorState, args: { theme: MPEditorTheme }) {
const contentState = editorState.getCurrentContent();
let textBlocks: string[] = [];
const defaultColor = args.theme === MPEditorTheme.Light ? "DEFAULT" : "WHITE";
let currentColor = defaultColor;
let colorChanged = false;
const blockMap = contentState.getBlockMap();
blockMap.forEach((block) => {
let blockText = block!.getText();
const changes: { [index: number]: string} = {};
block!.findStyleRanges(
(characterMetadata) => {
const style = characterMetadata.getStyle();
let color = style.find(value => { return !!colorStyleMap[value!]; });
if (!color) {
color = defaultColor;
}
if (color !== currentColor) {
currentColor = color;
colorChanged = true;
}
return true;
},
(start, end) => {
if (!colorChanged)
return; // Avoid always starting strings with color, or repeating same color over again.
changes[start] = "<" + currentColor + ">";
}
);
let currentIndexOffset = 0;
for (let index in changes) {
const replaceIndex = currentIndexOffset + parseInt(index);
blockText = splice(blockText, replaceIndex, 0, changes[index]);
currentIndexOffset += changes[index].length;
}
textBlocks.push(blockText);
});
return textBlocks.join("\n");
}
stringToEditorState(str: string) {
let contentState = ContentState.createFromText(str || "");
// Go through each block (line) and convert color tags to Draft.js inline styles.
let contentBlocks = contentState.getBlocksAsArray();
for (let i = 0; i < contentBlocks.length; i++) {
let contentBlock = contentBlocks[i];
let text = contentBlock.getText();
let [styleTag, tagStartIndex, tagEndIndex] = _getNextStyleTag(text);
while (styleTag) {
// Create a "selection" around the <tag>
let contentBlockKey = contentBlock.getKey();
let selection: any = SelectionState.createEmpty(contentBlock.getKey());
selection = selection.merge({
anchorOffset: tagStartIndex,
focusKey: contentBlockKey,
focusOffset: tagEndIndex,
});
// Remove the <tag>
contentState = Modifier.replaceText(contentState, selection, "");
contentBlocks = contentState.getBlocksAsArray();
contentBlock = contentBlocks[i];
text = contentBlock.getText();
// Make the "selection" go to the end of the entire string
const lastContentBlock = contentBlocks[contentBlocks.length - 1];
selection = selection.merge({
focusKey: lastContentBlock.getKey(),
focusOffset: lastContentBlock.getText().length,
});
// Remove any pre-existing colors from the tag index to end of string.
contentState = Object.keys(colorStyleMap).reduce((contentState, color) => {
return Modifier.removeInlineStyle(contentState, selection, color)
}, contentState);
// Apply the new tag.
contentState = Modifier.applyInlineStyle(contentState, selection, styleTag as string);
contentBlocks = contentState.getBlocksAsArray();
contentBlock = contentBlocks[i];
text = contentBlock.getText();
[styleTag, tagStartIndex, tagEndIndex] = _getNextStyleTag(text);
}
}
return EditorState.createWithContent(contentState, MPCompositeDecorator);
}
}();
function _getNextStyleTag(rawString: string) {
let startingIndex = 0;
while (startingIndex < rawString.length) {
let styleStart = rawString.indexOf("<", startingIndex) + 1;
if (!styleStart) // indexOf yielded -1
return [];
let styleEnd = rawString.indexOf(">", styleStart);
if (styleEnd === -1)
return [];
const styleTag = rawString.substring(styleStart, styleEnd);
if (!colorStyleMap[styleTag]) {
// Could be something like "<<BLUE>"
startingIndex = styleStart;
continue;
}
return [styleTag, styleStart - 1, styleEnd + 1];
}
return [];
} | the_stack |
import { TestBed, fakeAsync, ComponentFixture, tick, flush } from '@angular/core/testing';
import { Component, Type } from '@angular/core';
import { MdcFloatingLabelDirective } from '../floating-label/mdc.floating-label.directive';
import { MdcNotchedOutlineDirective, MdcNotchedOutlineNotchDirective } from '../notched-outline/mdc.notched-outline.directive';
import { MdcTextFieldDirective, MdcTextFieldInputDirective, MdcTextFieldIconDirective,
MdcTextFieldHelperLineDirective, MdcTextFieldHelperTextDirective } from './mdc.text-field.directive';
import { hasRipple } from '../../testutils/page.test';
import { By } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
describe('MdcTextFieldDirective', () => {
it('filled: should render the text-field with ripple and label', fakeAsync(() => {
const { fixture } = setup();
const root = fixture.nativeElement.querySelector('.mdc-text-field');
expect(root.children.length).toBe(4);
expect(root.children[0].classList).toContain('mdc-text-field__ripple');
expect(root.children[1].classList).toContain('mdc-text-field__input');
expect(root.children[2].classList).toContain('mdc-floating-label');
expect(root.children[3].classList).toContain('mdc-line-ripple');
expect(hasRipple(root)).toBe(true, 'the ripple element should be attached');
// input must be labelled by the floating label:
expect(root.children[2].id).toMatch(/mdc-u-id-.*/);
expect(root.children[1].getAttribute('aria-labelledby')).toBe(root.children[2].id);
}));
it('filled: floating label must float when input has focus', fakeAsync(() => {
const { fixture, element } = setup();
const floatingLabelElm = fixture.nativeElement.querySelector('.mdc-floating-label');
expect(floatingLabelElm.classList).not.toContain('mdc-floating-label--float-above');
element.dispatchEvent(new Event('focus')); tick();
expect(floatingLabelElm.classList).toContain('mdc-floating-label--float-above');
element.dispatchEvent(new Event('blur')); tick();
expect(floatingLabelElm.classList).not.toContain('mdc-floating-label--float-above');
}));
it('outlined: should render the text-field with outline and label', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.outlined = true;
fixture.detectChanges(); tick(5); fixture.detectChanges();
const root = fixture.nativeElement.querySelector('.mdc-text-field');
expect(root.children.length).toBe(2);
expect(root.children[0].classList).toContain('mdc-text-field__input');
expect(root.children[1].classList).toContain('mdc-notched-outline');
const notchedOutline = root.children[1];
expect(notchedOutline.children.length).toBe(3);
expect(notchedOutline.children[0].classList).toContain('mdc-notched-outline__leading');
expect(notchedOutline.children[1].classList).toContain('mdc-notched-outline__notch');
expect(notchedOutline.children[2].classList).toContain('mdc-notched-outline__trailing');
const notch = notchedOutline.children[1];
expect(notch.children.length).toBe(1);
expect(notch.children[0].classList).toContain('mdc-floating-label');
const floatingLabel = notch.children[0];
expect(hasRipple(root)).toBe(false, 'no ripple allowed on outlined inputs');
// input must be labelled by the floating label:
expect(floatingLabel.id).toMatch(/mdc-u-id-.*/);
expect(root.children[0].getAttribute('aria-labelledby')).toBe(floatingLabel.id);
}));
it('value can be changed programmatically', fakeAsync(() => {
const { fixture, testComponent, element } = setup();
expect(testComponent.value).toBe(null);
expect(element.value).toBe('');
setAndCheck(fixture, 'ab');
setAndCheck(fixture, '');
setAndCheck(fixture, ' ');
setAndCheck(fixture, null);
}));
it('value can be changed by user', fakeAsync(() => {
const { fixture, element, testComponent } = setup();
expect(testComponent.value).toBe(null);
expect(element.value).toEqual('');
typeAndCheck(fixture, 'abc');
typeAndCheck(fixture, '');
}));
it('can be disabled', fakeAsync(() => {
const { fixture, testComponent, element, input } = setup();
testComponent.disabled = true;
fixture.detectChanges();
expect(element.disabled).toBe(true);
expect(input.disabled).toBe(true);
expect(testComponent.disabled).toBe(true);
const field = fixture.debugElement.query(By.directive(MdcTextFieldDirective)).injector.get(MdcTextFieldDirective);
expect(field['isRippleSurfaceDisabled']()).toBe(true);
expect(field['root'].nativeElement.classList).toContain('mdc-text-field--disabled');
testComponent.disabled = false;
fixture.detectChanges();
expect(element.disabled).toBe(false);
expect(input.disabled).toBe(false);
expect(testComponent.disabled).toBe(false);
expect(field['isRippleSurfaceDisabled']()).toBe(false);
expect(field['root'].nativeElement.classList).not.toContain('mdc-text-field--disabled');
}));
it('without label', fakeAsync(() => {
const { fixture, testComponent } = setup();
const field = fixture.debugElement.query(By.directive(MdcTextFieldDirective)).injector.get(MdcTextFieldDirective);
expect(field['root'].nativeElement.classList).not.toContain('mdc-text-field--no-label');
testComponent.labeled = false;
fixture.detectChanges(); tick(5);
expect(field['root'].nativeElement.classList).toContain('mdc-text-field--no-label');
}));
it('textarea', fakeAsync(() => {
const { fixture } = setup(TestTextareaComponent);
const root = fixture.nativeElement.querySelector('.mdc-text-field');
expect(root.classList).toContain('mdc-text-field--textarea');
expect(root.children.length).toBe(2);
expect(root.children[0].classList).toContain('mdc-text-field__input');
expect(root.children[1].classList).toContain('mdc-notched-outline');
expect(hasRipple(root)).toBe(false, 'no ripple allowed on outlined/textarea inputs');
checkFloating(fixture, false);
typeAndCheck(fixture, 'typing text\nin my textarea', TestTextareaComponent);
}));
it('helper text', fakeAsync(() => {
const { fixture, testComponent, element } = setup(TestWithHelperTextComponent);
testComponent.withHelperText = true;
const helperText: HTMLElement = fixture.nativeElement.querySelector('.mdc-text-field-helper-text');
expect(helperText.id).toMatch(/mdc-u-id-[0-9]+/);
const helperId = helperText.id;
expect(helperText.classList).not.toContain('mdc-text-field-helper-text--persistent');
expect(helperText.classList).not.toContain('mdc-text-field-helper-text--validation-msg');
expect(element.getAttribute('aria-controls')).toBe(helperId);
expect(element.getAttribute('aria-describedby')).toBe(helperId);
testComponent.persistent = true;
fixture.detectChanges(); flush();
expect(helperText.classList).toContain('mdc-text-field-helper-text--persistent');
expect(helperText.classList).not.toContain('mdc-text-field-helper-text--validation-msg');
testComponent.persistent = false;
testComponent.validation = true;
fixture.detectChanges(); flush();
expect(helperText.classList).not.toContain('mdc-text-field-helper-text--persistent');
expect(helperText.classList).toContain('mdc-text-field-helper-text--validation-msg');
}));
it('helper text dynamic ids', fakeAsync(() => {
const { fixture, testComponent, element } = setup(TestWithHelperTextDynamicIdComponent);
testComponent.withHelperText = true;
const helperText: HTMLElement = fixture.nativeElement.querySelector('.mdc-text-field-helper-text');
expect(helperText.id).toBe('someId');
expect(element.getAttribute('aria-controls')).toBe('someId');
expect(element.getAttribute('aria-describedby')).toBe('someId');
testComponent.helperId = 'otherId';
fixture.detectChanges(); flush();
expect(helperText.id).toBe('otherId');
expect(element.getAttribute('aria-controls')).toBe('otherId');
expect(element.getAttribute('aria-describedby')).toBe('otherId');
}));
it('icons', fakeAsync(() => {
const { fixture, testComponent } = setup();
const root = fixture.nativeElement.querySelector('.mdc-text-field');
expect(fixture.nativeElement.querySelectorAll('.mdc-text-field__icon').length).toBe(0);
expect(fixture.nativeElement.querySelectorAll('.mdc-text-field__icon--leading').length).toBe(0);
expect(fixture.nativeElement.querySelectorAll('.mdc-text-field__icon--trailing').length).toBe(0);
expect(root.classList).not.toContain('mdc-text-field--with-leading-icon');
expect(root.classList).not.toContain('mdc-text-field--with-trailing-icon');
testComponent.leadingIcon = true;
fixture.detectChanges(); tick(5); fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('.mdc-text-field__icon').length).toBe(1);
expect(fixture.nativeElement.querySelectorAll('.mdc-text-field__icon--leading').length).toBe(1);
expect(fixture.nativeElement.querySelectorAll('.mdc-text-field__icon--trailing').length).toBe(0);
expect(root.classList).toContain('mdc-text-field--with-leading-icon');
expect(root.classList).not.toContain('mdc-text-field--with-trailing-icon');
testComponent.trailingIcon = true;
fixture.detectChanges(); tick(5); fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('.mdc-text-field__icon').length).toBe(2);
expect(fixture.nativeElement.querySelectorAll('.mdc-text-field__icon--leading').length).toBe(1);
expect(fixture.nativeElement.querySelectorAll('.mdc-text-field__icon--trailing').length).toBe(1);
expect(root.classList).toContain('mdc-text-field--with-leading-icon');
expect(root.classList).toContain('mdc-text-field--with-trailing-icon');
const leadIcon = fixture.nativeElement.querySelector('.mdc-text-field__icon--leading');
const trailIcon = fixture.nativeElement.querySelector('.mdc-text-field__icon--trailing');
expect(leadIcon.getAttribute('role')).toBeNull(); // no interaction -> no role
expect(trailIcon.getAttribute('role')).toBe('button');
expect(leadIcon.tabIndex).toBe(-1); // no interaction -> no tabIndex
expect(trailIcon.tabIndex).toBe(0);
testComponent.disabled = true;
fixture.detectChanges(); tick(5); fixture.detectChanges();
expect(trailIcon.getAttribute('role')).toBeNull(); // disabled -> no role
expect(trailIcon.tabIndex).toBe(-1); // disabled -> no tabIndex
testComponent.disabled = false;
fixture.detectChanges(); tick(5); fixture.detectChanges();
// interactions:
expect(testComponent.trailingIconInteractions).toBe(0);
trailIcon.dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(testComponent.trailingIconInteractions).toBe(1);
}));
function setAndCheck(fixture: ComponentFixture<TestComponent>, value: any) {
const testComponent = fixture.debugElement.injector.get(TestComponent);
const element = fixture.nativeElement.querySelector('.mdc-text-field__input');
const input = fixture.debugElement.query(By.directive(MdcTextFieldInputDirective))?.injector.get(MdcTextFieldInputDirective);
testComponent.value = value;
fixture.detectChanges(); flush();
expect(element.value).toBe(value || '');
expect(input.value).toBe(value || '');
expect(testComponent.value).toBe(value);
checkFloating(fixture, value != null && value.length > 0);
}
function typeAndCheck(fixture: ComponentFixture<any>, value: string, type: Type<any> = TestComponent) {
const testComponent = fixture.debugElement.injector.get(type);
const element = fixture.nativeElement.querySelector('.mdc-text-field__input');
const input = fixture.debugElement.query(By.directive(MdcTextFieldInputDirective))?.injector.get(MdcTextFieldInputDirective);
element.value = value;
element.dispatchEvent(new Event('focus'));
element.dispatchEvent(new Event('input'));
element.dispatchEvent(new Event('blur')); // focus/blur events triggered for testing label float depending on value after blur
tick(); fixture.detectChanges();
expect(element.value).toBe(value);
expect(input.value).toBe(value);
expect(testComponent.value).toBe(value);
checkFloating(fixture, value != null && value.length > 0);
}
@Component({
template: `
<label mdcTextField>
<i *ngIf="leadingIcon" mdcTextFieldIcon class="material-icons">phone</i>
<input mdcTextFieldInput type="text" [value]="value" (input)="onInput($event)" [disabled]="disabled">
<i *ngIf="trailingIcon" mdcTextFieldIcon class="material-icons" (interact)="trailingIconInteract()">event</i>
<span *ngIf="outlined && labeled" mdcNotchedOutline>
<span mdcNotchedOutlineNotch>
<span mdcFloatingLabel>Floating Label</span>
</span>
</span>
<span *ngIf="!outlined && labeled" mdcFloatingLabel>Floating Label</span>
</label>
`
})
class TestComponent {
value: any = null;
outlined: any = null;
disabled: any = null;
labeled = true;
withHelperText = false;
leadingIcon = false;
trailingIcon = false;
trailingIconInteractions = 0;
onInput(e) {
this.value = e.target.value;
}
trailingIconInteract() {
++this.trailingIconInteractions;
}
}
@Component({
template: `
<label mdcTextField>
<textarea mdcTextFieldInput rows="8" cols="40" [value]="value" (input)="onInput($event)"></textarea>
<span mdcNotchedOutline>
<span mdcNotchedOutlineNotch>
<span mdcFloatingLabel>Floating Label</span>
</span>
</span>
</label>
`
})
class TestTextareaComponent {
value: any = null;
onInput(e) {
this.value = e.target.value;
}
}
@Component({
template: `
<label mdcTextField [helperText]="help">
<input mdcTextFieldInput type="text" [value]="value" (input)="onInput($event)" [disabled]="disabled">
<span *ngIf="outlined && labeled" mdcNotchedOutline>
<span mdcNotchedOutlineNotch>
<span mdcFloatingLabel>Floating Label</span>
</span>
</span>
<span *ngIf="!outlined && labeled" mdcFloatingLabel>Floating Label</span>
</label>
<div mdcTextFieldHelperLine>
<div mdcTextFieldHelperText #help="mdcHelperText" [persistent]="persistent" [validation]="validation">helper text</div>
</div>
`
})
class TestWithHelperTextComponent {
value: any = null;
persistent: any = null;
validation: any = null;
onInput(e) {
this.value = e.target.value;
}
}
@Component({
template: `
<label mdcTextField [helperText]="help">
<input mdcTextFieldInput type="text" [value]="value" (input)="onInput($event)">
<span mdcFloatingLabel>Floating Label</span>
</label>
<div mdcTextFieldHelperLine>
<div mdcTextFieldHelperText [id]="helperId" #help="mdcHelperText">helper text</div>
</div>
`
})
class TestWithHelperTextDynamicIdComponent {
value: any = null;
helperId = 'someId';
onInput(e) {
this.value = e.target.value;
}
}
function setup(compType: Type<any> = TestComponent) {
const fixture = TestBed.configureTestingModule({
declarations: [
MdcTextFieldDirective, MdcTextFieldInputDirective, MdcTextFieldIconDirective,
MdcTextFieldHelperLineDirective, MdcTextFieldHelperTextDirective,
MdcFloatingLabelDirective,
MdcNotchedOutlineNotchDirective, MdcNotchedOutlineDirective,
compType]
}).createComponent(compType);
fixture.detectChanges(); flush();
const testComponent = fixture.debugElement.injector.get(compType);
const input = fixture.debugElement.query(By.directive(MdcTextFieldInputDirective))?.injector.get(MdcTextFieldInputDirective);
const element: HTMLInputElement = fixture.nativeElement.querySelector('.mdc-text-field__input');
return { fixture, testComponent, input, element };
}
});
describe('MdcTextFieldDirective with FormsModule', () => {
it('ngModel can be set programmatically', fakeAsync(() => {
const { fixture, testComponent, element } = setup();
expect(testComponent.value).toBe(null);
expect(element.value).toBe('');
setAndCheck(fixture, 'ab');
setAndCheck(fixture, '');
setAndCheck(fixture, ' ');
setAndCheck(fixture, null);
}));
it('ngModel can be changed by updating value property', fakeAsync(() => {
const { fixture, testComponent, input } = setup();
input.value = 'new value';
fixture.detectChanges(); tick();
expect(testComponent.value).toBe('new value');
checkFloating(fixture, true);
input.value = '';
fixture.detectChanges(); tick();
expect(testComponent.value).toBe('');
checkFloating(fixture, false);
input.value = null; // the browser will change this to ''
fixture.detectChanges(); tick();
expect(testComponent.value).toBe('');
checkFloating(fixture, false);
}));
it('ngModel can be changed by user', fakeAsync(() => {
const { fixture, element, testComponent } = setup();
expect(testComponent.value).toBe(null);
expect(element.value).toEqual('');
typeAndCheck(fixture, 'abc');
typeAndCheck(fixture, '');
}));
it('can be disabled', fakeAsync(() => {
const { fixture, testComponent, element, input } = setup();
testComponent.disabled = true;
fixture.detectChanges(); tick(); fixture.detectChanges();
expect(element.disabled).toBe(true);
expect(input.disabled).toBe(true);
expect(testComponent.disabled).toBe(true);
const field = fixture.debugElement.query(By.directive(MdcTextFieldDirective)).injector.get(MdcTextFieldDirective);
expect(field['isRippleSurfaceDisabled']()).toBe(true);
expect(field['root'].nativeElement.classList).toContain('mdc-text-field--disabled');
testComponent.disabled = false;
fixture.detectChanges(); tick(); fixture.detectChanges();
expect(element.disabled).toBe(false);
expect(input.disabled).toBe(false);
expect(testComponent.disabled).toBe(false);
expect(field['isRippleSurfaceDisabled']()).toBe(false);
expect(field['root'].nativeElement.classList).not.toContain('mdc-text-field--disabled');
}));
function setAndCheck(fixture: ComponentFixture<TestComponent>, value: any) {
const testComponent = fixture.debugElement.injector.get(TestComponent);
const element = fixture.nativeElement.querySelector('.mdc-text-field__input');
const input = fixture.debugElement.query(By.directive(MdcTextFieldInputDirective))?.injector.get(MdcTextFieldInputDirective);
testComponent.value = value;
fixture.detectChanges(); flush();
expect(element.value).toBe(value || '');
expect(input.value).toBe(value || '');
expect(testComponent.value).toBe(value);
checkFloating(fixture, value != null && value.length > 0);
}
function typeAndCheck(fixture: ComponentFixture<TestComponent>, value: string) {
const testComponent = fixture.debugElement.injector.get(TestComponent);
const element = fixture.nativeElement.querySelector('.mdc-text-field__input');
const input = fixture.debugElement.query(By.directive(MdcTextFieldInputDirective))?.injector.get(MdcTextFieldInputDirective);
element.value = value;
element.dispatchEvent(new Event('focus'));
element.dispatchEvent(new Event('input'));
element.dispatchEvent(new Event('blur')); // focus/blur events triggered for testing label float depending on value after blur
tick(); fixture.detectChanges();
expect(element.value).toBe(value);
expect(input.value).toBe(value);
expect(testComponent.value).toBe(value);
checkFloating(fixture, value != null && value.length > 0);
}
@Component({
template: `
<label mdcTextField>
<input mdcTextFieldInput type="text" [(ngModel)]="value" [disabled]="disabled">
<span *ngIf="outlined" mdcNotchedOutline>
<span mdcNotchedOutlineNotch>
<span mdcFloatingLabel>Floating Label</span>
</span>
</span>
<span *ngIf="!outlined" mdcFloatingLabel>Floating Label</span>
</label>
`
})
class TestComponent {
value: any = null;
outlined: any = null;
disabled: any = null;
}
function setup(compType: Type<any> = TestComponent) {
const fixture = TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [
MdcTextFieldDirective, MdcTextFieldInputDirective, MdcTextFieldIconDirective,
MdcTextFieldHelperLineDirective, MdcTextFieldHelperTextDirective,
MdcFloatingLabelDirective,
MdcNotchedOutlineNotchDirective, MdcNotchedOutlineDirective,
compType]
}).createComponent(compType);
fixture.detectChanges(); flush();
const testComponent = fixture.debugElement.injector.get(compType);
const input = fixture.debugElement.query(By.directive(MdcTextFieldInputDirective))?.injector.get(MdcTextFieldInputDirective);
const element = fixture.nativeElement.querySelector('.mdc-text-field__input');
return { fixture, testComponent, input, element };
}
});
function checkFloating(fixture: ComponentFixture<any>, expected: boolean) {
// when not empty, the label must be floating:
const floatingLabelElm = fixture.nativeElement.querySelector('.mdc-floating-label');
if (floatingLabelElm) {
if (expected)
expect(floatingLabelElm.classList).toContain('mdc-floating-label--float-above');
else
expect(floatingLabelElm.classList).not.toContain('mdc-floating-label--float-above');
}
} | the_stack |
import React, {RefObject} from 'react';
import { Flex, Box } from 'reflexbox'
//import {disableBodyScroll, enableBodyScroll} from "body-scroll-lock";
/** React layouts **/
import MainLayout from '../layouts/MainLayout';
import DashboardLayoutContainer from "../layouts/DashboardLayoutContainer";
/** React components **/
import AppStartingContainer from "../containers/AppStartingContainer";
import ModuleNetatmoInformationContainer from "../containers/ModuleNetatmoInformationContainer";
import ModuleDateTimeContainer from "../containers/ModuleDateTimeContainer";
import ModuleNetatmoStationContainer from "../containers/ModuleNetatmoStationContainer";
import ModuleNetatmoOutdoorContainer from "../containers/ModuleNetatmoOutdoorContainer";
import ModuleNetatmoIndoorContainer from "../containers/ModuleNetatmoIndoorContainer";
import ModuleNetatmoIndoorSecondContainer from "../containers/ModuleNetatmoIndoorSecondContainer";
import ModuleNetatmoIndoorThirdContainer from "../containers/ModuleNetatmoIndoorThirdContainer";
import ModuleNetatmoRainContainer from "../containers/ModuleNetatmoRainContainer";
import ModuleNetatmoWindContainer from "../containers/ModuleNetatmoWindContainer";
import ModuleNetatmoBarometerContainer from "../containers/ModuleNetatmoBarometerContainer";
import ModuleForecastContainer from "../containers/ModuleForecastContainer";
import ModuleNetatmoGraphContainer from "../containers/ModuleNetatmoGraphContainer";
import { ConnectedReduxProps } from '../store';
import { IAvailableModules } from "../models/NetatmoNAMain";
import { Orientation } from "../store/application/types";
// Separate state props + dispatch props to their own interfaces.
interface IPropsFromState {
isConfigured: boolean
orientation?: Orientation
mobile?: string
phone?: string
tablet?: string
available_modules: IAvailableModules|undefined
number_of_additional_modules?: number
selected_indoor_module: number
}
// We can use `typeof` here to map our dispatch types to the props, like so.
interface IPropsFromDispatch {
[key: string]: any
}
// Combine both state + dispatch props - as well as any props we want to pass - in a union type.
type AllProps = IPropsFromState & IPropsFromDispatch & ConnectedReduxProps;
class App extends React.Component<AllProps> {
private lockScrollElement: RefObject<any> = React.createRef();
/*public componentDidMount() {
//disableBodyScroll(this.lockScrollElement.current);
}*/
/*public componentDidUpdate(prevProps: Readonly<AllProps>, prevState: Readonly<{}>, snapshot?: any) {
if (prevProps.orientation !== this.props.orientation && this.props.orientation === 'portrait') {
//setTimeout(() => disableBodyScroll(this.lockScrollElement.current), 1000)
} else {
//enableBodyScroll(this.lockScrollElement.current)
}
}*/
public render() {
const { available_modules, number_of_additional_modules, orientation, mobile, phone, tablet } = this.props;
return (
<MainLayout>
{
this.props.isConfigured ? (
<DashboardLayoutContainer>
{
this._layoutChooser(mobile, phone, tablet, orientation, available_modules, number_of_additional_modules)
}
</DashboardLayoutContainer>
) : (
<AppStartingContainer />
)
}
</MainLayout>
)
}
private _layoutChooser = (
mobile?: string,
phone?: string,
tablet?: string,
orientation?: Orientation,
available_modules?: IAvailableModules,
number_of_additional_modules?: number
) => {
// If we are in desktop render the RPI layout 800x480
// TODO create a view for desktop with bigger screen
if (!mobile) return this._renderRpiLayout(available_modules, number_of_additional_modules);
// Mobile renders
if (!!phone && orientation === 'landscape') return this._renderPhoneLandscapeLayout(available_modules, number_of_additional_modules);
if (!!phone && orientation === 'portrait') return this._renderPhonePortraitLayout(available_modules);
if (!!tablet && orientation === 'landscape') return this._renderTabletLandscapeLayout(available_modules, number_of_additional_modules);
if (!!tablet && orientation === 'portrait') return this._renderTabletPortraitLayout(available_modules, number_of_additional_modules);
}
private _renderRpiLayout = (available_modules?: IAvailableModules, number_of_additional_modules?: number) => {
if (available_modules?.INDOOR ||
available_modules?.INDOOR_SECOND ||
available_modules?.INDOOR_THIRD ||
available_modules?.RAIN ||
available_modules?.WIND) {
return (
<>
<Flex flexDirection='column' width={[ '100%', '35%' ]}>
<ModuleDateTimeContainer/>
<ModuleNetatmoStationContainer />
<ModuleNetatmoOutdoorContainer />
<ModuleNetatmoBarometerContainer />
</Flex>
<Flex flexDirection='column' width={[ '100%', '65%' ]}>
<Flex flexWrap='wrap' flex={1}>
<ModuleForecastContainer />
{
available_modules?.INDOOR ? (
<Box width={number_of_additional_modules as number !== 1 ? [ '100%', '50%' ] : '100%'}>
{
this.props.selected_indoor_module === 0 ? (
<ModuleNetatmoIndoorContainer />
) : null
}
{
this.props.selected_indoor_module === 1 ? (
<ModuleNetatmoIndoorSecondContainer />
) : null
}
{
this.props.selected_indoor_module === 2 ? (
<ModuleNetatmoIndoorThirdContainer />
) : null
}
</Box>
) : null
}
{
available_modules?.INDOOR_SECOND && number_of_additional_modules as number <= 3 ? (
<Box width={number_of_additional_modules as number !== 1 ? [ '100%', '50%' ] : '100%'}>
<ModuleNetatmoIndoorSecondContainer />
</Box>
) : null
}
{
available_modules?.INDOOR_THIRD && number_of_additional_modules as number <= 3 ? (
<Box width={number_of_additional_modules as number !== 1 ? [ '100%', '50%' ] : '100%'}>
<ModuleNetatmoIndoorThirdContainer />
</Box>
) : null
}
{
available_modules?.RAIN ? (
<Box width={number_of_additional_modules as number !== 1 ? [ '100%', '50%' ] : '100%'}>
<ModuleNetatmoRainContainer />
</Box>
) : null
}
{
available_modules?.WIND ? (
<Box width={number_of_additional_modules as number !== 1 ? [ '100%', '50%' ] : '100%'}>
<ModuleNetatmoWindContainer />
</Box>
) : null
}
<Box width={number_of_additional_modules as number !== 1 && number_of_additional_modules as number !== 2 ?
[ '100%', '50%' ] : '100%'}>
<ModuleNetatmoGraphContainer />
</Box>
</Flex>
<ModuleNetatmoInformationContainer />
</Flex>
</>
)
} else {
// No additional modules
return (
<>
<Flex flexDirection='column' width={[ '100%', '35%' ]}>
<ModuleDateTimeContainer/>
<ModuleNetatmoStationContainer />
<ModuleNetatmoOutdoorContainer />
<ModuleNetatmoBarometerContainer />
</Flex>
<Flex flexDirection='column' width={[ '100%', '65%' ]}>
<ModuleForecastContainer />
<ModuleNetatmoGraphContainer />
<ModuleNetatmoInformationContainer />
</Flex>
</>
)
}
}
private _renderPhoneLandscapeLayout = (available_modules?: IAvailableModules, number_of_additional_modules?: number) => {
return this._renderRpiLayout(available_modules, number_of_additional_modules);
}
private _renderPhonePortraitLayout = (available_modules?: IAvailableModules) => {
return (
<Flex flexDirection='column' width={'100%'}>
<Flex flexDirection='column' ref={this.lockScrollElement} style={{overflowY: 'auto'}}>
<ModuleNetatmoInformationContainer />
<ModuleNetatmoOutdoorContainer />
<ModuleNetatmoStationContainer />
{
available_modules?.INDOOR && (
<ModuleNetatmoIndoorContainer module_name='indoor' />
)
}
{
available_modules?.INDOOR_SECOND && (
<ModuleNetatmoIndoorSecondContainer module_name='indoor_second' />
)
}
{
available_modules?.INDOOR_THIRD && (
<ModuleNetatmoIndoorThirdContainer module_name='indoor_third' />
)
}
{
available_modules?.RAIN && (
<ModuleNetatmoRainContainer />
)
}
{
available_modules?.WIND && (
<ModuleNetatmoWindContainer />
)
}
</Flex>
<ModuleForecastContainer />
</Flex>
)
}
private _renderTabletLandscapeLayout = (available_modules?: IAvailableModules, number_of_additional_modules?: number) => {
return this._renderRpiLayout(available_modules, number_of_additional_modules);
}
private _renderTabletPortraitLayout = (available_modules?: IAvailableModules, number_of_additional_modules?: number) => {
return this._renderRpiLayout(available_modules, number_of_additional_modules);
}
}
export default App | the_stack |
import { StrictMode } from 'react';
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { Column } from '../src';
import DataGrid, { SelectColumn } from '../src';
import { useFocusRef } from '../src/hooks';
import { setup, getSelectedCell, validateCellPosition, getCellsAtRowIndex, getGrid } from './utils';
type Row = undefined;
const rows: readonly Row[] = Array(100);
const summaryRows: readonly Row[] = [undefined, undefined];
const columns: readonly Column<Row>[] = [
SelectColumn,
{ key: 'col2', name: 'col2' },
{ key: 'col3', name: 'col3' },
{ key: 'col4', name: 'col4' },
{ key: 'col5', name: 'col5' },
{ key: 'col6', name: 'col6' },
{ key: 'col7', name: 'col7' }
];
test('keyboard navigation', () => {
setup({ columns, rows, summaryRows });
// no initial selection
expect(getSelectedCell()).not.toBeInTheDocument();
// tab into the grid
userEvent.tab();
validateCellPosition(0, 0);
// tab to the next cell
userEvent.tab();
validateCellPosition(1, 0);
// tab back to the previous cell
userEvent.tab({ shift: true });
validateCellPosition(0, 0);
// arrow navigation
userEvent.keyboard('{arrowdown}');
validateCellPosition(0, 1);
userEvent.keyboard('{arrowright}');
validateCellPosition(1, 1);
userEvent.keyboard('{arrowup}');
validateCellPosition(1, 0);
userEvent.keyboard('{arrowleft}');
validateCellPosition(0, 0);
// page {up,down}
userEvent.keyboard('{PageDown}');
validateCellPosition(0, 27);
userEvent.keyboard('{PageDown}');
validateCellPosition(0, 54);
userEvent.keyboard('{PageUp}');
validateCellPosition(0, 27);
// home/end navigation
userEvent.keyboard('{end}');
validateCellPosition(6, 27);
userEvent.keyboard('{home}');
validateCellPosition(0, 27);
userEvent.keyboard('{ctrl}{end}');
validateCellPosition(6, 102);
userEvent.keyboard('{arrowdown}');
validateCellPosition(6, 102);
userEvent.keyboard('{arrowright}');
validateCellPosition(6, 102);
userEvent.keyboard('{end}');
validateCellPosition(6, 102);
userEvent.keyboard('{ctrl}{end}');
validateCellPosition(6, 102);
userEvent.keyboard('{PageDown}');
validateCellPosition(6, 102);
userEvent.keyboard('{ctrl}{home}');
validateCellPosition(0, 0);
userEvent.keyboard('{home}');
validateCellPosition(0, 0);
userEvent.keyboard('{ctrl}{home}');
validateCellPosition(0, 0);
userEvent.keyboard('{PageUp}');
validateCellPosition(0, 0);
// tab at the end of a row selects the first cell on the next row
userEvent.keyboard('{end}');
userEvent.tab();
validateCellPosition(0, 1);
// shift tab should select the last cell of the previous row
userEvent.tab({ shift: true });
validateCellPosition(6, 0);
});
test('cellNavigationMode="NONE"', () => {
setup({ columns, rows, summaryRows, cellNavigationMode: 'NONE' });
// pressing arrowleft on the leftmost cell does nothing
userEvent.tab();
userEvent.keyboard('{arrowdown}');
validateCellPosition(0, 1);
userEvent.keyboard('{arrowleft}');
validateCellPosition(0, 1);
// pressing arrowright on the rightmost cell does nothing
userEvent.keyboard('{end}');
validateCellPosition(6, 1);
userEvent.keyboard('{arrowright}');
validateCellPosition(6, 1);
// pressing tab on the rightmost cell navigates to the leftmost cell on the next row
userEvent.tab();
validateCellPosition(0, 2);
// pressing shift+tab on the leftmost cell navigates to the rightmost cell on the previous row
userEvent.tab({ shift: true });
validateCellPosition(6, 1);
});
test('cellNavigationMode="CHANGE_ROW"', () => {
setup({ columns, rows, summaryRows, cellNavigationMode: 'CHANGE_ROW' });
// pressing arrowleft on the leftmost cell navigates to the rightmost cell on the previous row
userEvent.tab();
userEvent.keyboard('{arrowdown}');
validateCellPosition(0, 1);
userEvent.keyboard('{arrowleft}');
validateCellPosition(6, 0);
// pressing arrowright on the rightmost cell navigates to the leftmost cell on the next row
userEvent.keyboard('{arrowright}');
validateCellPosition(0, 1);
// pressing shift+tab on the leftmost cell navigates to the rightmost cell on the previous row
userEvent.tab({ shift: true });
validateCellPosition(6, 0);
// pressing tab on the rightmost cell navigates to the leftmost cell on the next row
userEvent.tab();
validateCellPosition(0, 1);
});
test('cellNavigationMode="LOOP_OVER_ROW"', () => {
setup({ columns, rows, summaryRows, cellNavigationMode: 'LOOP_OVER_ROW' });
// pressing arrowleft on the leftmost cell navigates to the rightmost cell on the same row
userEvent.tab();
validateCellPosition(0, 0);
userEvent.keyboard('{arrowleft}');
validateCellPosition(6, 0);
// pressing arrowright on the rightmost cell navigates to the leftmost cell on the same row
userEvent.keyboard('{arrowright}');
validateCellPosition(0, 0);
// pressing shift+tab on the leftmost cell navigates to the rightmost cell on the same row
userEvent.tab({ shift: true });
validateCellPosition(6, 0);
// pressing tab on the rightmost cell navigates to the leftmost cell on the same row
userEvent.tab();
validateCellPosition(0, 0);
});
test('grid enter/exit', () => {
setup({ columns, rows: Array(5), summaryRows });
// no initial selection
expect(getSelectedCell()).not.toBeInTheDocument();
// tab into the grid
userEvent.tab();
validateCellPosition(0, 0);
// shift+tab tabs out of the grid if we are at the first cell
userEvent.tab({ shift: true });
expect(document.body).toHaveFocus();
userEvent.tab();
validateCellPosition(0, 0);
userEvent.keyboard('{arrowdown}{arrowdown}');
validateCellPosition(0, 2);
// tab should select the last selected cell
// click outside the grid
userEvent.click(document.body);
userEvent.tab();
userEvent.keyboard('{arrowdown}');
validateCellPosition(0, 3);
// shift+tab should select the last selected cell
userEvent.click(document.body);
userEvent.tab({ shift: true });
userEvent.keyboard('{arrowup}');
validateCellPosition(0, 2);
// tab tabs out of the grid if we are at the last cell
userEvent.keyboard('{ctrl}{end}');
userEvent.tab();
expect(document.body).toHaveFocus();
});
test('navigation with focusable formatter', () => {
setup({ columns, rows: Array(1), summaryRows });
userEvent.tab();
userEvent.keyboard('{arrowdown}');
validateCellPosition(0, 1);
// cell should not set tabIndex to 0 if it contains a focusable formatter
expect(getSelectedCell()).toHaveAttribute('tabIndex', '-1');
const checkbox = getSelectedCell()!.querySelector('input');
expect(checkbox).toHaveFocus();
expect(checkbox).toHaveAttribute('tabIndex', '0');
userEvent.tab();
validateCellPosition(1, 1);
// cell should set tabIndex to 0 if it does not have focusable formatter
expect(getSelectedCell()).toHaveAttribute('tabIndex', '0');
});
test('navigation when header and summary rows have focusable elements', () => {
function Test({ id, isCellSelected }: { id: string; isCellSelected: boolean }) {
const { ref, tabIndex } = useFocusRef<HTMLInputElement>(isCellSelected);
return <input ref={ref} tabIndex={tabIndex} id={id} />;
}
const columns: readonly Column<Row>[] = [
{
key: 'col2',
name: 'col2',
headerRenderer(p) {
return <Test id="header-filter1" isCellSelected={p.isCellSelected} />;
},
summaryFormatter(p) {
return <Test id="summary-formatter1" isCellSelected={p.isCellSelected} />;
}
},
{
key: 'col3',
name: 'col3',
headerRenderer(p) {
return <Test id="header-filter2" isCellSelected={p.isCellSelected} />;
},
summaryFormatter(p) {
return <Test id="summary-formatter2" isCellSelected={p.isCellSelected} />;
}
}
];
setup({ columns, rows: Array(2), summaryRows });
userEvent.tab();
// should set focus on the header filter
expect(document.getElementById('header-filter1')).toHaveFocus();
userEvent.tab();
expect(document.getElementById('header-filter2')).toHaveFocus();
userEvent.tab();
validateCellPosition(0, 1);
userEvent.tab({ shift: true });
expect(document.getElementById('header-filter2')).toHaveFocus();
userEvent.tab({ shift: true });
expect(document.getElementById('header-filter1')).toHaveFocus();
userEvent.tab();
userEvent.tab();
userEvent.keyboard('{ctrl}{end}{arrowup}{arrowup}');
validateCellPosition(1, 2);
userEvent.tab();
expect(document.getElementById('summary-formatter1')).toHaveFocus();
userEvent.tab();
expect(document.getElementById('summary-formatter2')).toHaveFocus();
userEvent.tab({ shift: true });
userEvent.tab({ shift: true });
validateCellPosition(1, 2);
expect(getSelectedCell()).toHaveFocus();
});
test('navigation when selected cell not in the viewport', () => {
const columns: Column<Row>[] = [SelectColumn];
for (let i = 0; i < 99; i++) {
columns.push({ key: `col${i}`, name: `col${i}`, frozen: i < 5 });
}
setup({ columns, rows, summaryRows });
userEvent.tab();
validateCellPosition(0, 0);
const grid = getGrid();
userEvent.keyboard('{ctrl}{end}{arrowup}{arrowup}');
validateCellPosition(99, 100);
expect(getCellsAtRowIndex(100)).not.toHaveLength(1);
grid.scrollTop = 0;
expect(getCellsAtRowIndex(99)).toHaveLength(1);
userEvent.keyboard('{arrowup}');
validateCellPosition(99, 99);
expect(getCellsAtRowIndex(99)).not.toHaveLength(1);
grid.scrollLeft = 0;
userEvent.keyboard('{arrowdown}');
validateCellPosition(99, 100);
userEvent.keyboard(
'{home}{arrowright}{arrowright}{arrowright}{arrowright}{arrowright}{arrowright}{arrowright}'
);
validateCellPosition(7, 100);
grid.scrollLeft = 2000;
userEvent.keyboard('{arrowleft}');
validateCellPosition(6, 100);
});
test('reset selected cell when column is removed', () => {
const columns: readonly Column<Row>[] = [
{ key: '1', name: '1' },
{ key: '2', name: '2' }
];
const rows = [undefined, undefined];
function Test({ columns }: { columns: readonly Column<Row>[] }) {
return <DataGrid columns={columns} rows={rows} />;
}
const { rerender } = render(
<StrictMode>
<Test columns={columns} />
</StrictMode>
);
userEvent.tab();
userEvent.keyboard('{arrowdown}{arrowright}');
validateCellPosition(1, 1);
rerender(
<StrictMode>
<Test columns={[columns[0]]} />
</StrictMode>
);
expect(getSelectedCell()).not.toBeInTheDocument();
});
test('reset selected cell when row is removed', () => {
const columns: readonly Column<Row>[] = [
{ key: '1', name: '1' },
{ key: '2', name: '2' }
];
const rows = [undefined, undefined];
function Test({ rows }: { rows: readonly undefined[] }) {
return <DataGrid columns={columns} rows={rows} />;
}
const { rerender } = render(
<StrictMode>
<Test rows={rows} />
</StrictMode>
);
userEvent.tab();
userEvent.keyboard('{arrowdown}{arrowdown}{arrowright}');
validateCellPosition(1, 2);
rerender(
<StrictMode>
<Test rows={[rows[0]]} />
</StrictMode>
);
expect(getSelectedCell()).not.toBeInTheDocument();
}); | the_stack |
import JSZip from 'jszip'
import { SheetData } from './model/sheet'
import { TopicData } from './model/topic'
const MANIFEST_XML_PATH = 'META-INF/manifest.xml'
const CONTENT_XML_PATH = 'content.xml'
const STYLES_XML_PATH = 'styles.xml'
const CONTENT_JSON_PATH = 'content.json'
const FILE_ENTRIES = 'file-entries'
const FILE_ENTRY = 'file-entry'
const FULL_PATH = 'full-path'
export function loadFromXMind(zip: JSZip) {
if (zip?.files) {
const files = zip.files
if (CONTENT_JSON_PATH in files) {
return _fromJSON(zip)
} else if (CONTENT_XML_PATH in files) {
return _fromXML(zip)
}
}
return Promise.reject('Not a valid XMind file.')
}
function _fromJSON(zip: JSZip) {
return new Promise((resolve, reject) => {
const contentZipObj = zip?.file(CONTENT_JSON_PATH)
if (!contentZipObj) {
return reject('Must have a content.xml file.')
}
contentZipObj.async('text').then(jsonStr => {
return JSON.parse(jsonStr)
}).then(content => {
resolve({
sheets: content
})
}).catch((e) => {
reject(e)
})
})
}
function _fromXML(zip: JSZip) {
return new Promise((resolve, reject) => {
if (!zip) {
return reject('Must have a valid XMind file.')
}
const manifestZipObj = zip.file(MANIFEST_XML_PATH)
if (!manifestZipObj) {
return reject('Must have a manifest.xml file.')
}
let domParser
if (typeof((<any>global).window) === 'undefined') {
const jsdom = require("jsdom")
const DOMParser = new jsdom.JSDOM('').window.DOMParser
domParser = new DOMParser()
} else {
domParser = new DOMParser()
}
manifestZipObj.async('text').then(xmlStr => {
const dom = domParser.parseFromString(xmlStr, 'application/xml')
return _parseManifestDOM(dom)
}).then(manifest => {
const jobs = []
jobs.push(Promise.resolve(manifest))
// load content.xml
const contentZipObj = zip.file(CONTENT_XML_PATH)
if (!contentZipObj) {
return reject('Must have a content.xml file.')
}
jobs.push(contentZipObj.async('text').then(xmlStr => {
return domParser.parseFromString(xmlStr, 'application/xml')
}))
//load styles.xml
const stylesZipObj = zip.file(STYLES_XML_PATH)
if (stylesZipObj) {
jobs.push(stylesZipObj.async('text').then(xmlStr => {
return domParser.parseFromString(xmlStr, 'application/xml')
}))
} else {
jobs.push(Promise.resolve(null))
}
Promise.all(jobs).then(([manifest, contentDOM, stylesDOM]) => {
const sheets: SheetData[] = []
const parseSheetPromises = []
Array.from(contentDOM.getElementsByTagName('sheet')).forEach((sheetDOM: Document) => {
parseSheetPromises.push(_parseSheetDOM(sheetDOM, sheets, { stylesDOM }))
})
Promise.all(parseSheetPromises).then(() => {
if (!sheets.length) {
return reject('Faild to load XMind file.')
}
resolve({
sheets
})
})
})
}).catch(e => {
reject(e)
})
})
}
function _parseManifestDOM(dom: Document) {
const manifestJSON = { [FILE_ENTRIES]: {} }
const fileEntries = dom.getElementsByTagName(FILE_ENTRY)
Array.from(fileEntries).forEach(fileEntry => {
const fullPath = fileEntry.getAttribute(FULL_PATH)
manifestJSON[FILE_ENTRIES][fullPath] = {}
})
return manifestJSON
}
function _parseSheetDOM(sheetDOM: Document, sheets: SheetData[], options?: { stylesDOM: Document }) {
const sheetTitleDOMArr = Array.from(sheetDOM.childNodes).filter(item => item.nodeName?.toLowerCase() == 'title')
const sheetTitleDOM = sheetTitleDOMArr.length > 0 && sheetTitleDOMArr[0]
const title = sheetTitleDOM?.firstChild?.nodeValue || 'Missing Sheet Title'
const sheet: any = {
id: UUID(),
title
}
sheets.push(sheet)
fillTheme()
return new Promise(resolve => {
Promise.all([fillTopic()]).then(resolve)
})
function fillTopic() {
return new Promise(resolve => {
parseTopicDOM(sheetDOM.getElementsByTagName('topic')[0]).then((topicInfo: TopicData) => {
sheet.rootTopic = topicInfo
resolve()
})
function parseTopicDOM(topicDOM: Element) {
return new Promise(resolve => {
const promises = []
const topicData: any = {}
// id
topicData.id = topicDOM.getAttribute('id')
// title
const titleDomArr = topicDOM.getElementsByTagName('title')
const titleNode = titleDomArr.length >0 && titleDomArr[0]
if (titleNode?.firstChild) {
const value = titleNode.firstChild.nodeValue
if (value) topicData.title = value.replace(/\r/g, '')
topicData.customWidth = titleNode.getAttribute('svg:width')
}
// structureClass
topicData.structureClass = topicDOM.getAttribute('structure-class')
// styles
const styleId = topicDOM.getAttribute('style-id')
if (styleId) {
const stylesDOM = options?.stylesDOM
const userStyleDOM = stylesDOM?.getElementById(styleId)
const styleProps = userStyleDOM?.getElementsByTagName('topic-properties')
if (styleProps && styleProps[0]) {
topicData.style = { type: 'topic' }
const props = {}
Array.from(styleProps[0].attributes).forEach(attrNode => {
props[attrNode.name] = attrNode.value
})
topicData.style.properties = props
}
}
// extensions
const extensionsDOMArr = Array.from(topicDOM.childNodes).filter(item => item.nodeName?.toLowerCase() == 'extensions')
if (extensionsDOMArr.length > 0) {
const extensionsDOM = extensionsDOMArr[0] as Element
const extensionDOMArr = extensionsDOM.getElementsByTagName('extension')
if (extensionDOMArr) {
const extensionsResult = []
Array.from(extensionDOMArr).forEach(extensionDOM => {
const extensionData: any = {}
extensionData.provider = extensionDOM.getAttribute('provider')
const contentContainer = extensionDOM.getElementsByTagName('content') && extensionDOM.getElementsByTagName('content')[0]
const contentDomArray = Array.from(contentContainer.childNodes).filter(item => item.nodeType === item.ELEMENT_NODE)
const contentResult = []
contentDomArray.forEach((contentDom: Element) => {
contentResult.push({
name: contentDom.nodeName,//tagName && contentDom.tagName.toLowerCase(),
content: parseExtensionContent(contentDom)
})
})
extensionData.content = contentResult
extensionsResult.push(extensionData)
})
topicData.extensions = extensionsResult
}
}
function parseExtensionContent (extensionContentDOM: Element) {
const getAttrs = (dom: Element) => {
let attrs = {}
for (let attr of Array.from(dom.attributes)) {
attrs[attr.name] = attr.value
}
if (Object.keys(attrs))
return attrs
return null
}
let content: any
let extensionChildrenDOM = Array.from(extensionContentDOM.childNodes).filter(item => item.nodeType === item.ELEMENT_NODE)
if (extensionChildrenDOM && extensionChildrenDOM.length) {
content = []
extensionChildrenDOM.forEach((childDOM: Element) => {
let obj: any = {}
obj.name = childDOM.nodeName//childDom.tagName && childDom.tagName.toLowerCase()
obj.content = parseExtensionContent(childDOM)
let attrs = getAttrs(childDOM)
if (attrs)
obj.attrs = attrs
//resourceRefs
content.push(obj)
})
} else if (extensionContentDOM.firstChild) {
content = extensionContentDOM.firstChild.nodeValue
}
return content
}
// children
let attached: TopicData[] = []
const childrenDom = Array.from(topicDOM.childNodes).filter(item => item.nodeName?.toLowerCase() == 'children')
if (childrenDom.length > 0) {
topicData.children = {}
parseChildDOM('attached')
}
function parseChildDOM(type: string) {
const topicsDOM = Array.from(childrenDom[0].childNodes).find((item: Element) => {
return item.nodeName?.toLowerCase() == 'topics'
&& item.getAttribute('type') == type
})
if (topicsDOM) {
topicData.children[type] = []
const topicsDOMArr = Array.from(topicsDOM.childNodes).filter(item => item.nodeName?.toLowerCase() == 'topic')
for (let index in topicsDOMArr) {
const childDOM = topicsDOMArr[index] as Element
promises.push(parseTopicDOM(childDOM).then(childTopicInfo => {
topicData.children[type][index] = childTopicInfo
}))
}
}
}
Promise.all(promises).then(() => {
resolve(topicData)
})
})
}
})
}
function fillTheme() {
if (!sheetDOM || !options?.stylesDOM) return
const sheetThemeId = (sheetDOM as any).getAttribute('theme')
if (!sheetThemeId)
return
const stylesDOM = options.stylesDOM
const masterStylesContainer = stylesDOM.getElementById(sheetThemeId)
if (!masterStylesContainer) return
const theme = {}
const defaultStyleDomArray = Array.from(masterStylesContainer.getElementsByTagName('default-style'))
defaultStyleDomArray.forEach((dsDom) => {
const styleId = dsDom.getAttribute('style-id')
const styleFamily = dsDom.getAttribute('style-family')
if (!stylesDOM || !styleId)
return
const amStyleDom = stylesDOM.getElementById(styleId)
if (!amStyleDom) return
const type = amStyleDom.getAttribute('type')
theme[styleFamily] = {
type,
properties: {}
}
amStyleDom.getElementsByTagName(type + '-properties') && amStyleDom.getElementsByTagName(type + '-properties')[0] &&
Array.from(amStyleDom.getElementsByTagName(type + '-properties')[0].attributes).forEach((attrNode) => {
theme[styleFamily].properties[attrNode.name] = attrNode.value
})
})
sheet.theme = theme
}
function UUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
})
}
} | the_stack |
import { expectSaga } from 'redux-saga-test-plan'
import * as matchers from 'redux-saga-test-plan/matchers'
import { throwError } from 'redux-saga-test-plan/providers'
import request from 'app/utils/request'
import actions from 'app/containers/Projects/actions'
import OrgActions from 'app/containers/Organizations/actions'
import {
getProjects,
addProject,
editProject,
deleteProject,
addProjectAdmin,
addProjectRole,
transferProject,
searchProject,
unStarProject,
getProjectStarUser,
getCollectProjects,
editCollectProject,
loadRelRoleProject,
updateRelRoleProject,
deleteRelRoleProject,
getProjectRoles,
excludeRole
} from 'app/containers/Projects/sagas'
import { mockStore } from './fixtures'
import { getMockResponse } from 'test/utils/fixtures'
describe('Projects Sagas', () => {
const { projects, project, projectId } = mockStore
describe('getProjects Saga', () => {
it('should dispatch the projectsLoaded action if it requests the data successfully', () => {
return expectSaga(getProjects, actions.loadProjects())
.provide([[matchers.call.fn(request), getMockResponse(projects)]])
.put(actions.projectsLoaded(projects))
.run()
})
it('should call the loadProjectsFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(getProjects, actions.loadProjects())
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.loadProjectsFail())
.run()
})
})
describe('addProjects Saga', () => {
const addProjectActions = actions.addProject(project, () => void 0)
it('should dispatch the projectAdded action if it requests the data successfully', () => {
return expectSaga(addProject, addProjectActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.projectAdded(project))
.run()
})
it('should call the addProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(addProject, addProjectActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.addProjectFail())
.run()
})
})
describe('editProjects Saga', () => {
const editProjectActions = actions.editProject(project, () => void 0)
it('should dispatch the projectEdited action if it requests the data successfully', () => {
return expectSaga(editProject, editProjectActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.projectEdited(project))
.run()
})
it('should call the editProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(editProject, editProjectActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.editProjectFail())
.run()
})
})
describe('deleteProjects Saga', () => {
const deleteProjectActions = actions.deleteProject(projectId, () => void 0)
it('should dispatch the projectDeleted action if it requests the data successfully', () => {
return expectSaga(deleteProject, deleteProjectActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.projectDeleted(projectId))
.run()
})
it('should call the deleteProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(deleteProject, deleteProjectActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.deleteProjectFail())
.run()
})
})
describe('addProjectAdmin Saga', () => {
const addProjectAdminActions = actions.addProjectAdmin(
projectId,
projectId,
() => void 0
)
it('should call the addProjectAdminFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(addProjectAdmin, addProjectAdminActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.addProjectFail())
.run()
})
})
describe('addProjectRole Saga', () => {
const addProjectRoleActions = actions.addProjectRole(
projectId,
[projectId],
() => void 0
)
it('should call the addProjectRoleFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(addProjectRole, addProjectRoleActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.addProjectRoleFail())
.run()
})
})
describe('transferProject Saga', () => {
const transferProjectActions = actions.transferProject(projectId, projectId)
it('should dispatch the projectTransfered action if it requests the data successfully', () => {
return expectSaga(transferProject, transferProjectActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.projectTransfered(project))
.run()
})
it('should call the transferProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(transferProject, transferProjectActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.transferProjectFail())
.run()
})
})
describe('searchProject Saga', () => {
const [keywords, pageNum, pageSize] = ['abc', 1, 20]
const transferProjectActions = actions.searchProject({keywords, pageNum, pageSize})
it('should dispatch the projectSearched action if it requests the data successfully', () => {
return expectSaga(searchProject, transferProjectActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.projectSearched(project))
.run()
})
it('should call the searchProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(searchProject, transferProjectActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.searchProjectFail())
.run()
})
})
describe('unStarProject Saga', () => {
const transferProjectActions = actions.unStarProject(projectId, () => void 0)
it('should dispatch the unStarProjectSuccess action if it requests the data successfully', () => {
return expectSaga(unStarProject, transferProjectActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.unStarProjectSuccess(project))
.run()
})
it('should call the unStarProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(unStarProject, transferProjectActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.unStarProjectFail())
.run()
})
})
describe('getProjectStarUser Saga', () => {
const getProjectStarUserActions = actions.getProjectStarUser(projectId)
it('should dispatch the getProjectStarUserSuccess action if it requests the data successfully', () => {
return expectSaga(getProjectStarUser, getProjectStarUserActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.getProjectStarUserSuccess(project))
.run()
})
it('should call the getProjectStarUserFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(getProjectStarUser, getProjectStarUserActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.getProjectStarUserFail())
.run()
})
})
describe('getCollectProjects Saga', () => {
it('should dispatch the collectProjectLoaded action if it requests the data successfully', () => {
return expectSaga(getCollectProjects)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.collectProjectLoaded(project))
.run()
})
it('should call the collectProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(getCollectProjects)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.collectProjectFail())
.run()
})
})
describe('editCollectProject Saga', () => {
const [
isFavorite,
proId,
resolve] = [false, projectId, () => void 0]
const clickCollectProjectsActions = actions.clickCollectProjects(isFavorite, proId, resolve)
it('should dispatch the collectProjectClicked action if it requests the data successfully', () => {
return expectSaga(editCollectProject, clickCollectProjectsActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.collectProjectClicked({isFavorite, proId, resolve}))
.run()
})
it('should call the clickCollectProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(editCollectProject, clickCollectProjectsActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.clickCollectProjectFail())
.run()
})
})
describe('loadRelRoleProject Saga', () => {
const loadRelRoleProjectsActions = actions.loadRelRoleProject(
projectId,
projectId
)
it('should dispatch the relRoleProjectLoaded action if it requests the data successfully', () => {
return expectSaga(loadRelRoleProject, loadRelRoleProjectsActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.relRoleProjectLoaded(project))
.run()
})
it('should call the loadRelRoleProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(loadRelRoleProject, loadRelRoleProjectsActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.loadRelRoleProjectFail())
.run()
})
})
describe('updateRelRoleProject Saga', () => {
const loadRelRoleProjectsActions = actions.updateRelRoleProject(
projectId,
projectId,
project
)
it('should dispatch the relRoleProjectUpdated action if it requests the data successfully', () => {
return expectSaga(updateRelRoleProject, loadRelRoleProjectsActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.relRoleProjectUpdated(project))
.run()
})
it('should call the updateRelRoleProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(updateRelRoleProject, loadRelRoleProjectsActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.updateRelRoleProjectFail())
.run()
})
})
describe('deleteRelRoleProject Saga', () => {
const deleteRelRoleProjectsActions = actions.deleteRelRoleProject(
projectId,
projectId,
() => void 0
)
it('should dispatch the relRoleProjectDeleted action if it requests the data successfully', () => {
return expectSaga(deleteRelRoleProject, deleteRelRoleProjectsActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.relRoleProjectDeleted(project))
.run()
})
it('should call the deleteRelRoleProjectFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(deleteRelRoleProject, deleteRelRoleProjectsActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.deleteRelRoleProjectFail())
.run()
})
})
describe('getProjectRoles Saga', () => {
const loadProjectRolesActions = OrgActions.loadProjectRoles(
projectId
)
it('should dispatch the projectRolesLoaded action if it requests the data successfully', () => {
return expectSaga(getProjectRoles, loadProjectRolesActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(OrgActions.projectRolesLoaded(project))
.run()
})
it('should call the loadProjectRolesFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(getProjectRoles, loadProjectRolesActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(OrgActions.loadProjectRolesFail())
.run()
})
})
describe('excludeRole Saga', () => {
const excludeRolesFailActions = actions.excludeRoles(
projectId,
'type',
() => void 0
)
it('should dispatch the rolesExcluded action if it requests the data successfully', () => {
return expectSaga(excludeRole, excludeRolesFailActions)
.provide([[matchers.call.fn(request), getMockResponse(project)]])
.put(actions.rolesExcluded(project))
.run()
})
it('should call the excludeRolesFail action if the response errors', () => {
const errors = new Error('error')
return expectSaga(excludeRole, excludeRolesFailActions)
.provide([[matchers.call.fn(request), throwError(errors)]])
.put(actions.excludeRolesFail(errors))
.run()
})
})
}) | the_stack |
import type { IQService } from 'angular';
import * as angular from 'angular';
import _ from 'lodash';
import type { Application, InstanceTypeService } from '@spinnaker/core';
import {
AccountService,
DeploymentStrategyRegistry,
INSTANCE_TYPE_SERVICE,
NameUtils,
SubnetReader,
} from '@spinnaker/core';
import { AWSProviderSettings } from '../../aws.settings';
import type { IAmazonLaunchTemplateOverrides, ILaunchTemplateData } from '../../domain';
import type { IAmazonServerGroup, IAmazonServerGroupView, INetworkInterface } from '../../domain';
import type {
AwsServerGroupConfigurationService,
IAmazonInstanceTypeOverride,
IAmazonServerGroupCommand,
IAmazonServerGroupCommandViewState,
IAmazonServerGroupDeployConfiguration,
} from './serverGroupConfiguration.service';
import { AWS_SERVER_GROUP_CONFIGURATION_SERVICE } from './serverGroupConfiguration.service';
export const AMAZON_SERVERGROUP_CONFIGURE_SERVERGROUPCOMMANDBUILDER_SERVICE =
'spinnaker.amazon.serverGroupCommandBuilder.service';
export const name = AMAZON_SERVERGROUP_CONFIGURE_SERVERGROUPCOMMANDBUILDER_SERVICE; // for backwards compatibility
export interface AwsServerGroupCommandBuilder {
buildNewServerGroupCommand(
application: Application,
defaults?: { account?: string; region?: string; subnet?: string; mode?: string },
): PromiseLike<Partial<IAmazonServerGroupCommand>>;
buildServerGroupCommandFromExisting(
application: Application,
serverGroup: IAmazonServerGroupView,
mode?: string,
): PromiseLike<Partial<IAmazonServerGroupCommand>>;
buildNewServerGroupCommandForPipeline(): PromiseLike<Partial<IAmazonServerGroupCommand>>;
buildServerGroupCommandFromPipeline(
application: Application,
originalCluster: IAmazonServerGroupDeployConfiguration,
): PromiseLike<Partial<IAmazonServerGroupCommand>>;
buildUpdateServerGroupCommand(serverGroup: IAmazonServerGroup): Partial<IAmazonServerGroupCommand>;
}
angular
.module(AMAZON_SERVERGROUP_CONFIGURE_SERVERGROUPCOMMANDBUILDER_SERVICE, [
INSTANCE_TYPE_SERVICE,
AWS_SERVER_GROUP_CONFIGURATION_SERVICE,
])
.factory('awsServerGroupCommandBuilder', [
'$q',
'instanceTypeService',
'awsServerGroupConfigurationService',
function (
$q: IQService,
instanceTypeService: InstanceTypeService,
awsServerGroupConfigurationService: AwsServerGroupConfigurationService,
) {
function buildNewServerGroupCommand(
application: Application,
defaults: { account?: string; region?: string; subnet?: string; mode?: string } = {},
) {
const credentialsLoader = AccountService.getCredentialsKeyedByAccount('aws');
const defaultCredentials =
defaults.account || application.defaultCredentials.aws || AWSProviderSettings.defaults.account;
const defaultRegion = defaults.region || application.defaultRegions.aws || AWSProviderSettings.defaults.region;
const defaultSubnet = defaults.subnet || AWSProviderSettings.defaults.subnetType || '';
const preferredZonesLoader = AccountService.getAvailabilityZonesForAccountAndRegion(
'aws',
defaultCredentials,
defaultRegion,
);
return $q
.all([preferredZonesLoader, credentialsLoader])
.then(function ([preferredZones, credentialsKeyedByAccount]) {
const credentials = credentialsKeyedByAccount[defaultCredentials];
const keyPair = credentials ? credentials.defaultKeyPair : null;
const applicationAwsSettings = application.attributes?.providerSettings?.aws ?? {};
let defaultIamRole = AWSProviderSettings.defaults.iamRole || 'BaseIAMRole';
defaultIamRole = defaultIamRole.replace('{{application}}', application.name);
const useAmiBlockDeviceMappings = applicationAwsSettings.useAmiBlockDeviceMappings || false;
const command: Partial<IAmazonServerGroupCommand> = {
application: application.name,
credentials: defaultCredentials,
region: defaultRegion,
strategy: '',
capacity: {
min: 1,
max: 1,
desired: 1,
},
targetHealthyDeployPercentage: 100,
cooldown: 10,
enabledMetrics: [],
healthCheckType: 'EC2',
healthCheckGracePeriod: 600,
instanceMonitoring: false,
ebsOptimized: false,
selectedProvider: 'aws',
iamRole: defaultIamRole,
terminationPolicies: ['Default'],
vpcId: null,
subnetType: defaultSubnet,
availabilityZones: preferredZones,
keyPair: keyPair,
suspendedProcesses: [],
securityGroups: [],
stack: '',
freeFormDetails: '',
spotPrice: '',
tags: {},
useAmiBlockDeviceMappings: useAmiBlockDeviceMappings,
copySourceCustomBlockDeviceMappings: false, // default to using block device mappings from current instance type
viewState: {
instanceProfile: 'custom',
useSimpleInstanceTypeSelector: true,
useAllImageSelection: false,
useSimpleCapacity: true,
usePreferredZones: true,
mode: defaults.mode || 'create',
disableStrategySelection: true,
dirty: {},
submitButtonLabel: getSubmitButtonLabel(defaults.mode || 'create'),
} as IAmazonServerGroupCommandViewState,
};
if (application.attributes?.platformHealthOnlyShowOverride && application.attributes?.platformHealthOnly) {
command.interestingHealthProviderNames = ['Amazon'];
}
if (defaultCredentials === 'test' && AWSProviderSettings.serverGroups?.enableIPv6) {
command.associateIPv6Address = true;
}
if (AWSProviderSettings.serverGroups?.enableIMDSv2) {
/**
* Older SDKs do not support IMDSv2. A timestamp can be optionally configured at which any apps created after can safely default to using IMDSv2.
*/
const appAgeRequirement = AWSProviderSettings.serverGroups.defaultIMDSv2AppAgeLimit;
const creationDate = application.attributes?.createTs;
command.requireIMDSv2 = appAgeRequirement && creationDate && Number(creationDate) > appAgeRequirement;
}
return command;
});
}
function buildServerGroupCommandFromPipeline(
application: Application,
originalCluster: IAmazonServerGroupDeployConfiguration,
) {
const pipelineCluster = _.cloneDeep(originalCluster);
const region = Object.keys(pipelineCluster.availabilityZones)[0];
const instanceTypes = pipelineCluster.launchTemplateOverridesForInstanceType
? pipelineCluster.launchTemplateOverridesForInstanceType.map((o) => o.instanceType)
: [pipelineCluster.instanceType];
const instanceTypeCategoryLoader = instanceTypeService.getCategoryForMultipleInstanceTypes(
'aws',
instanceTypes,
);
const commandOptions = { account: pipelineCluster.account, region: region };
const asyncLoader = $q.all([
buildNewServerGroupCommand(application, commandOptions),
instanceTypeCategoryLoader,
]);
return asyncLoader.then(function ([command, instanceProfile]) {
const zones = pipelineCluster.availabilityZones[region];
const usePreferredZones = zones.join(',') === command.availabilityZones.join(',');
const viewState = {
instanceProfile,
disableImageSelection: true,
useSimpleCapacity:
pipelineCluster.capacity.min === pipelineCluster.capacity.max &&
pipelineCluster.useSourceCapacity !== true,
usePreferredZones: usePreferredZones,
mode: 'editPipeline',
submitButtonLabel: 'Done',
templatingEnabled: true,
existingPipelineCluster: true,
dirty: {},
useSimpleInstanceTypeSelector: isSimpleModeEnabled(pipelineCluster),
};
const viewOverrides = {
region: region,
credentials: pipelineCluster.account,
availabilityZones: pipelineCluster.availabilityZones[region],
iamRole: pipelineCluster.iamRole,
viewState: viewState,
};
pipelineCluster.strategy = pipelineCluster.strategy || '';
return angular.extend({}, command, pipelineCluster, viewOverrides);
});
}
// Only used to prepare view requiring template selecting
function buildNewServerGroupCommandForPipeline() {
return $q.when({
viewState: {
requiresTemplateSelection: true,
} as IAmazonServerGroupCommandViewState,
});
}
function getSubmitButtonLabel(mode: string) {
switch (mode) {
case 'createPipeline':
return 'Add';
case 'editPipeline':
return 'Done';
case 'clone':
return 'Clone';
default:
return 'Create';
}
}
function buildUpdateServerGroupCommand(serverGroup: IAmazonServerGroup) {
const command = ({
type: 'modifyAsg',
asgs: [{ asgName: serverGroup.name, region: serverGroup.region }],
cooldown: serverGroup.asg.defaultCooldown,
enabledMetrics: (serverGroup.asg?.enabledMetrics ?? []).map((m) => m.metric),
healthCheckGracePeriod: serverGroup.asg.healthCheckGracePeriod,
healthCheckType: serverGroup.asg.healthCheckType,
terminationPolicies: angular.copy(serverGroup.asg.terminationPolicies),
credentials: serverGroup.account,
capacityRebalance: serverGroup.asg.capacityRebalance,
} as Partial<IAmazonServerGroupCommand>) as IAmazonServerGroupCommand;
awsServerGroupConfigurationService.configureUpdateCommand(command);
return command;
}
function buildServerGroupCommandFromExisting(
application: Application,
serverGroup: IAmazonServerGroupView,
mode = 'clone',
) {
const preferredZonesLoader = AccountService.getPreferredZonesByAccount('aws');
const subnetsLoader = SubnetReader.listSubnets();
const serverGroupName = NameUtils.parseServerGroupName(serverGroup.asg.autoScalingGroupName);
let instanceTypes;
if (serverGroup.mixedInstancesPolicy) {
const ltOverrides = serverGroup.mixedInstancesPolicy?.launchTemplateOverridesForInstanceType;
// note: single launch template case is currently the only supported case for mixed instances policy
instanceTypes = ltOverrides
? ltOverrides.map((o) => o.instanceType)
: [serverGroup.mixedInstancesPolicy?.launchTemplates[0]?.launchTemplateData?.instanceType];
} else if (serverGroup.launchTemplate) {
instanceTypes = [_.get(serverGroup, 'launchTemplate.launchTemplateData.instanceType')];
} else if (serverGroup.launchConfig) {
instanceTypes = [_.get(serverGroup, 'launchConfig.instanceType')];
}
const instanceTypeCategoryLoader = instanceTypeService.getCategoryForMultipleInstanceTypes(
'aws',
instanceTypes,
);
return $q
.all([preferredZonesLoader, subnetsLoader, instanceTypeCategoryLoader])
.then(([preferredZones, subnets, instanceProfile]) => {
const zones = serverGroup.asg.availabilityZones.sort();
let usePreferredZones = false;
const preferredZonesForAccount = preferredZones[serverGroup.account];
if (preferredZonesForAccount) {
const preferredZones = preferredZonesForAccount[serverGroup.region].sort();
usePreferredZones = zones.join(',') === preferredZones.join(',');
}
// These processes should never be copied over, as the affect launching instances and enabling traffic
const enabledProcesses = ['Launch', 'Terminate', 'AddToLoadBalancer'];
const applicationAwsSettings = application.attributes?.providerSettings?.aws ?? {};
const useAmiBlockDeviceMappings = applicationAwsSettings.useAmiBlockDeviceMappings || false;
const existingTags: { [key: string]: string } = {};
// These tags are applied by Clouddriver (if configured to do so), regardless of what the user might enter
// Might be worth feature flagging this if it turns out other folks are hard-coding these values
const reservedTags = ['spinnaker:application', 'spinnaker:stack', 'spinnaker:details'];
if (serverGroup.asg.tags) {
serverGroup.asg.tags
.filter((t) => !reservedTags.includes(t.key))
.forEach((tag) => {
existingTags[tag.key] = tag.value;
});
}
const command: Partial<IAmazonServerGroupCommand> = {
application: application.name,
strategy: '',
stack: serverGroupName.stack,
freeFormDetails: serverGroupName.freeFormDetails,
credentials: serverGroup.account,
cooldown: serverGroup.asg.defaultCooldown,
enabledMetrics: _.get(serverGroup, 'asg.enabledMetrics', []).map((m) => m.metric),
healthCheckGracePeriod: serverGroup.asg.healthCheckGracePeriod,
healthCheckType: serverGroup.asg.healthCheckType,
terminationPolicies: serverGroup.asg.terminationPolicies,
loadBalancers: serverGroup.asg.loadBalancerNames,
region: serverGroup.region,
useSourceCapacity: false,
capacity: {
min: serverGroup.asg.minSize,
max: serverGroup.asg.maxSize,
desired: serverGroup.asg.desiredCapacity,
},
targetHealthyDeployPercentage: 100,
availabilityZones: zones,
selectedProvider: 'aws',
source: {
account: serverGroup.account,
region: serverGroup.region,
asgName: serverGroup.asg.autoScalingGroupName,
},
suspendedProcesses: (serverGroup.asg.suspendedProcesses || [])
.map((process) => process.processName)
.filter((name) => !enabledProcesses.includes(name)),
tags: Object.assign({}, serverGroup.tags, existingTags),
targetGroups: serverGroup.targetGroups,
useAmiBlockDeviceMappings: useAmiBlockDeviceMappings,
copySourceCustomBlockDeviceMappings: mode === 'clone', // default to using block device mappings if not cloning
viewState: {
instanceProfile,
useAllImageSelection: false,
useSimpleCapacity: serverGroup.asg.minSize === serverGroup.asg.maxSize,
usePreferredZones: usePreferredZones,
mode: mode,
submitButtonLabel: getSubmitButtonLabel(mode),
isNew: false,
dirty: {},
} as IAmazonServerGroupCommandViewState,
};
if (application.attributes?.platformHealthOnlyShowOverride && application.attributes?.platformHealthOnly) {
command.interestingHealthProviderNames = ['Amazon'];
}
if (mode === 'editPipeline') {
command.useSourceCapacity = true;
command.viewState.useSimpleCapacity = false;
command.strategy = 'redblack';
const redblack = DeploymentStrategyRegistry.getStrategy('redblack');
redblack.initializationMethod && redblack.initializationMethod(command);
command.suspendedProcesses = [];
}
const vpcZoneIdentifier = serverGroup.asg.vpczoneIdentifier;
if (vpcZoneIdentifier !== '') {
const subnetId = vpcZoneIdentifier.split(',')[0];
const subnet = subnets.find((x) => x.id === subnetId);
command.subnetType = subnet.purpose;
command.vpcId = subnet.vpcId;
} else {
command.subnetType = '';
command.vpcId = null;
}
if (serverGroup.launchConfig) {
angular.extend(command, {
instanceType: serverGroup.launchConfig.instanceType,
iamRole: serverGroup.launchConfig.iamInstanceProfile,
keyPair: serverGroup.launchConfig.keyName,
associatePublicIpAddress: serverGroup.launchConfig.associatePublicIpAddress,
ramdiskId: serverGroup.launchConfig.ramdiskId,
instanceMonitoring:
serverGroup.launchConfig.instanceMonitoring && serverGroup.launchConfig.instanceMonitoring.enabled,
ebsOptimized: serverGroup.launchConfig.ebsOptimized,
spotPrice: serverGroup.launchConfig.spotPrice,
});
if (serverGroup.launchConfig.userData) {
command.base64UserData = serverGroup.launchConfig.userData;
}
command.viewState.imageId = serverGroup.launchConfig.imageId;
command.viewState.useSimpleInstanceTypeSelector = true;
}
if (serverGroup.launchTemplate || serverGroup.mixedInstancesPolicy) {
let launchTemplateData: ILaunchTemplateData, spotMaxPrice: string;
if (serverGroup.launchTemplate) {
launchTemplateData = serverGroup.launchTemplate.launchTemplateData;
spotMaxPrice = launchTemplateData.instanceMarketOptions?.spotOptions?.maxPrice;
command.instanceType = launchTemplateData.instanceType;
command.viewState.useSimpleInstanceTypeSelector = true;
}
if (serverGroup.mixedInstancesPolicy) {
const mip = serverGroup.mixedInstancesPolicy;
// note: single launch template case is currently the only supported case for mixed instances policy
launchTemplateData = mip?.launchTemplates?.[0]?.launchTemplateData;
spotMaxPrice = mip?.instancesDistribution?.spotMaxPrice;
command.securityGroups = launchTemplateData.networkInterfaces
? (launchTemplateData.networkInterfaces.find((ni) => ni.deviceIndex === 0) ?? {}).groups
: launchTemplateData.securityGroups;
command.onDemandAllocationStrategy = mip.instancesDistribution.onDemandAllocationStrategy;
command.onDemandBaseCapacity = mip.instancesDistribution.onDemandBaseCapacity;
command.onDemandPercentageAboveBaseCapacity =
mip.instancesDistribution.onDemandPercentageAboveBaseCapacity;
command.spotAllocationStrategy = mip.instancesDistribution.spotAllocationStrategy;
command.spotInstancePools = mip.instancesDistribution.spotInstancePools;
// 'launchTemplateOverridesForInstanceType' is used for multiple instance types case, 'instanceType' is used for all other cases.
if (mip.launchTemplateOverridesForInstanceType) {
command.launchTemplateOverridesForInstanceType = getInstanceTypesWithPriority(
mip.launchTemplateOverridesForInstanceType,
);
} else {
command.instanceType = launchTemplateData.instanceType;
}
command.viewState.useSimpleInstanceTypeSelector = isSimpleModeEnabled(command);
}
const ipv6AddressCount = _.get(launchTemplateData, 'networkInterfaces[0]');
const asgSettings = AWSProviderSettings.serverGroups;
const isTestEnv = serverGroup.accountDetails && serverGroup.accountDetails.environment === 'test';
const shouldAutoEnableIPv6 =
asgSettings && asgSettings.enableIPv6 && asgSettings.setIPv6InTest && isTestEnv;
angular.extend(command, {
iamRole: launchTemplateData.iamInstanceProfile.name,
keyPair: launchTemplateData.keyName,
associateIPv6Address: shouldAutoEnableIPv6 || Boolean(ipv6AddressCount),
ramdiskId: launchTemplateData.ramdiskId,
instanceMonitoring: launchTemplateData.monitoring && launchTemplateData.monitoring.enabled,
ebsOptimized: launchTemplateData.ebsOptimized,
spotPrice: spotMaxPrice || undefined,
requireIMDSv2: Boolean(launchTemplateData.metadataOptions?.httpTokens === 'required'),
unlimitedCpuCredits: launchTemplateData.creditSpecification
? launchTemplateData.creditSpecification.cpuCredits === 'unlimited'
: undefined,
});
command.viewState.imageId = launchTemplateData.imageId;
}
if (mode === 'clone' && serverGroup.image && serverGroup.image.name) {
command.amiName = serverGroup.image.name;
}
if (serverGroup.launchConfig && serverGroup.launchConfig.securityGroups.length) {
command.securityGroups = serverGroup.launchConfig.securityGroups;
}
if (serverGroup.launchTemplate && serverGroup.launchTemplate.launchTemplateData.securityGroups.length) {
command.securityGroups = serverGroup.launchTemplate.launchTemplateData.securityGroups;
}
if (serverGroup.launchTemplate && serverGroup.launchTemplate.launchTemplateData.networkInterfaces) {
const networkInterface =
serverGroup.launchTemplate.launchTemplateData.networkInterfaces.find((ni) => ni.deviceIndex === 0) ??
({} as INetworkInterface);
command.securityGroups = networkInterface.groups;
}
return command;
});
}
// Since Deck allows changing priority of instance types via drag handle, fill priority field explicitly if empty
function getInstanceTypesWithPriority(
instanceTypeOverrides: IAmazonLaunchTemplateOverrides[],
): IAmazonInstanceTypeOverride[] {
let explicitPriority = 1;
return _.sortBy(instanceTypeOverrides, ['priority']).map((override) => {
const { instanceType, weightedCapacity } = override;
let priority;
if (override.priority) {
priority = override.priority;
explicitPriority = override.priority + 1;
} else {
priority = explicitPriority++;
}
return { instanceType, weightedCapacity, priority };
});
}
function isSimpleModeEnabled(
command: IAmazonServerGroupDeployConfiguration | Partial<IAmazonServerGroupCommand>,
) {
const isAdvancedModeEnabledInCommand =
command.onDemandAllocationStrategy ||
command.onDemandBaseCapacity ||
command.onDemandPercentageAboveBaseCapacity ||
command.spotAllocationStrategy ||
command.spotInstancePools ||
(command.launchTemplateOverridesForInstanceType && command.launchTemplateOverridesForInstanceType.length > 0);
return !isAdvancedModeEnabledInCommand;
}
return {
buildNewServerGroupCommand,
buildServerGroupCommandFromExisting,
buildNewServerGroupCommandForPipeline,
buildServerGroupCommandFromPipeline,
buildUpdateServerGroupCommand,
} as AwsServerGroupCommandBuilder;
},
]); | the_stack |
declare const map: AMap.Map;
declare const lnglat: AMap.LngLat;
declare const size: AMap.Size;
declare const lnglatTuple: [number, number];
declare const pixel: AMap.Pixel;
declare const layer: AMap.Layer;
declare const ambientLight: AMap.Lights.AmbientLight;
declare const directionLight: AMap.Lights.DirectionLight;
declare const line: AMap.Object3D.Line;
declare const mesh: AMap.Object3D.Mesh;
declare const object3d: AMap.Object3D;
declare const geometry: AMap.Geometry3D.Mesh;
/**
* lights.ts
*/
// $ExpectType AmbientLight
const testAmbientLight = new AMap.Lights.AmbientLight([0.1, 0, 0.1], 1);
// $ExpectType void
testAmbientLight.setColor([0.1, 1, 0.5]);
// $ExpectType void
testAmbientLight.setIntensity(1);
// $ExpectType DirectionLight
const testDirectionLight = new AMap.Lights.DirectionLight([1, 2, 3], [1, 2, 3], 1);
// $ExpectType void
testDirectionLight.setColor([1, 2, 3]);
// $ExpectType void
testDirectionLight.setIntensity(1);
// $ExpectType void
testDirectionLight.setDirection([1, 2, 3]);
/**
* map3d.ts
*/
// $ExpectType Object3DResult | null
map.getObject3DByContainerPos(pixel);
// $ExpectType Object3DResult | null
const containserPos = map.getObject3DByContainerPos(pixel, [layer], true);
if (containserPos) {
// $ExpectType number
containserPos.index;
// $ExpectType Vector3
containserPos.point;
// $ExpectType number
containserPos.distance;
// $ExpectType Object3D
containserPos.object;
} else {
// $ExpectType null
containserPos;
}
map.AmbientLight = ambientLight;
map.AmbientLight = undefined;
map.DirectionLight = directionLight;
map.DirectionLight = undefined;
/**
* object3d-group.ts
*/
// $ExpectType Object3DGroup<Object3D>
const testObject3dGroup1 = new AMap.Object3DGroup();
// $ExpectType Object3DGroup<Mesh>
const testObject3dGroup2 = new AMap.Object3DGroup<AMap.Object3D.Mesh>();
// $ExpectType Object3D[]
testObject3dGroup1.children;
// $ExpectType Mesh[]
testObject3dGroup2.children;
// $ExoectType void
testObject3dGroup1.add(line);
// $ExoectType void
testObject3dGroup1.add(mesh);
// $ExoectType void
testObject3dGroup2.add(mesh);
// $ExpectError
testObject3dGroup2.add(line);
// $ExoectType void
testObject3dGroup1.remove(line);
// $ExoectType void
testObject3dGroup1.remove(mesh);
// $ExoectType void
testObject3dGroup2.remove(mesh);
// $ExpectError
testObject3dGroup2.remove(line);
/**
* object3d-Layer.ts
*/
// $ExpectType Object3DLayer
new AMap.Object3DLayer();
// $ExpectType Object3DLayer
new AMap.Object3DLayer({});
// $ExpectType Object3DLayer
const testObject3DLayer = new AMap.Object3DLayer({
map,
visible: true,
opacity: 0.1,
zIndex: 2,
zooms: [1, 2]
});
// $ExpectType void
testObject3DLayer.setMap(null);
// $ExpectType void
testObject3DLayer.setMap(map);
// $ExpectType Map | null | undefined
testObject3DLayer.getMap();
// $ExpectType void
testObject3DLayer.hide();
// $ExpectType void
testObject3DLayer.show();
// $ExpectType void
testObject3DLayer.setOpacity(1);
// $ExpectType number
testObject3DLayer.getOpacity();
// $ExpectType void
testObject3DLayer.setzIndex(1);
// $ExpectType number
testObject3DLayer.getzIndex();
// $ExpectType [number, number]
testObject3DLayer.getZooms();
// $ExpectType void
testObject3DLayer.add(object3d);
// $ExpectType void
testObject3DLayer.remove(object3d);
// $ExpectType void
testObject3DLayer.clear();
// $ExpectType void
testObject3DLayer.reDraw();
/**
* vector3.ts
*/
// $ExpectType Vector3
const testVector = new AMap.Vector3([1, 2, 3]);
// $ExpectType Vector3
new AMap.Vector3(testVector);
// $ExpectType [number, number, number]
testVector.elements;
// $ExpectType void
testVector.set(1, 2, 3);
// $ExpectType number
testVector.dot();
// $ExpectType Vector3
testVector.clone();
// $ExpectType Vector3
testVector.add(testVector);
// $ExpectType Vector3
testVector.add([1, 2, 3]);
// $ExpectType Vector3
testVector.sub(testVector);
// $ExpectType Vector3
testVector.sub([1, 2, 3]);
// $ExpectType Vector3
testVector.addVectors(testVector, testVector);
// $ExpectType Vector3
testVector.subVectors(testVector, testVector);
// $ExpectType Vector3
testVector.crossVectors(testVector, testVector);
// $ExpectType Vector3
testVector.normalize();
// $ExpectType number
testVector.length();
/**
* object3d/mesh.ts
*/
// $ExpectType Mesh
const testMesh = new AMap.Object3D.Mesh();
// $ExpectError
testMesh.geometry = geometry;
// $ExpectType number[]
testMesh.geometry.vertices;
// $ExpectError
testMesh.geometry.vertices = [];
testMesh.geometry.vertices.shift();
// $ExpectType number[]
testMesh.geometry.vertexColors;
// $ExpectError
testMesh.geometry.vertexColors = [];
testMesh.geometry.vertexColors.shift();
// $ExpectType number[]
testMesh.geometry.vertexUVs;
// $ExpectError
testMesh.geometry.vertexUVs = [];
testMesh.geometry.vertexUVs.shift();
// $ExpectType number[]
testMesh.geometry.faces;
// $ExpectError
testMesh.geometry.faces = [];
testMesh.geometry.faces.shift();
// $ExpectType number[]
testMesh.geometry.textureIndices;
// $ExpectError
testMesh.geometry.textureIndices = [];
testMesh.geometry.textureIndices.shift();
// $ExpectType (string | HTMLCanvasElement)[]
testMesh.textures;
// $ExpectType boolean
testMesh.needUpdate;
// $ExpectType boolean
testMesh.transparent;
// $ExpectType boolean
testMesh.DEPTH_TEST;
// $ExpectType void
testMesh.reDraw();
/**
* object3d/meshAcceptLights.ts
*/
// $ExpectType MeshAcceptLights
const testMeshAcceptLights = new AMap.Object3D.MeshAcceptLights();
// $ExpectError
testMeshAcceptLights.geometry = geometry;
// $ExpectType number[]
testMeshAcceptLights.geometry.vertices;
// $ExpectError
testMeshAcceptLights.geometry.vertices = [];
testMeshAcceptLights.geometry.vertices.shift();
// $ExpectType number[]
testMeshAcceptLights.geometry.vertexColors;
// $ExpectError
testMeshAcceptLights.geometry.vertexColors = [];
testMeshAcceptLights.geometry.vertexColors.shift();
// $ExpectType number[]
testMeshAcceptLights.geometry.vertexUVs;
// $ExpectError
testMeshAcceptLights.geometry.vertexUVs = [];
testMeshAcceptLights.geometry.vertexUVs.shift();
// $ExpectType number[]
testMeshAcceptLights.geometry.faces;
// $ExpectError
testMeshAcceptLights.geometry.faces = [];
testMeshAcceptLights.geometry.faces.shift();
// $ExpectType number[]
testMeshAcceptLights.geometry.textureIndices;
// $ExpectError
testMeshAcceptLights.geometry.textureIndices = [];
testMeshAcceptLights.geometry.textureIndices.shift();
// $ExpectType number[]
testMeshAcceptLights.geometry.vertexNormals;
// $ExpectError
testMeshAcceptLights.geometry.vertexNormals = [];
testMeshAcceptLights.geometry.vertexNormals.shift();
// $ExpectType (string | HTMLCanvasElement)[]
testMeshAcceptLights.textures;
// $ExpectType boolean
testMeshAcceptLights.needUpdate;
// $ExpectType boolean
testMeshAcceptLights.transparent;
// $ExpectType boolean
testMeshAcceptLights.DEPTH_TEST;
// $ExpectType void
testMeshAcceptLights.reDraw();
/**
* object3d/meshLine.ts
*/
// $ExpectError
new AMap.Object3D.MeshLine();
// $ExpectError
new AMap.Object3D.MeshLine({});
// $ExpectType MeshLine
const testMeshLine = new AMap.Object3D.MeshLine({
path: [lnglat],
width: 1,
height: 1,
color: 'red'
});
// $ExpectType MeshLine
new AMap.Object3D.MeshLine({
path: [lnglat],
color: [0, 0, 1, 1]
});
// $ExpectType MeshLine
new AMap.Object3D.MeshLine({
path: [[1, 2]]
});
// $ExpectType MeshLine
new AMap.Object3D.MeshLine({
path: [lnglat],
unit: 'meter'
});
// $ExpectType MeshLine
new AMap.Object3D.MeshLine({
path: [pixel],
unit: 'px'
});
// $ExpectError
new AMap.Object3D.MeshLine({
path: [lnglat],
unit: 'px'
});
// $ExpectError
new AMap.Object3D.MeshLine({
path: [pixel],
unit: 'meter'
});
// $ExpectType number[]
testMeshLine.geometry.vertices;
// $ExpectError
testMeshLine.geometry.vertices = [];
testMeshLine.geometry.vertices.shift();
// $ExpectType number[]
testMeshLine.geometry.vertexUVs;
// $ExpectError
testMeshLine.geometry.vertexUVs = [];
testMeshLine.geometry.vertexUVs.shift();
// $ExpectType number[]
testMeshLine.geometry.vertexColors;
// $ExpectError
testMeshLine.geometry.vertexColors = [];
testMeshLine.geometry.vertexColors.shift();
// $ExpectType number[]
testMeshLine.geometry.vertexColors;
// $ExpectError
testMeshLine.geometry.vertexColors = [];
testMeshLine.geometry.vertexColors.shift();
// $ExpectType number[]
testMeshLine.geometry.vertexIndices;
// $ExpectError
testMeshLine.geometry.vertexIndices = [];
testMeshLine.geometry.vertexIndices.shift();
// $ExpectType number[]
testMeshLine.geometry.directions;
// $ExpectError
testMeshLine.geometry.directions = [];
testMeshLine.geometry.directions.shift();
// $ExpectType number[]
testMeshLine.geometry.textureIndices;
// $ExpectError
testMeshLine.geometry.textureIndices = [];
testMeshLine.geometry.textureIndices.shift();
// $ExpectType number
testMeshLine.width;
// $ExpectType void
testMeshLine.setPath([lnglat]);
// $ExpectType void
testMeshLine.setPath([lnglatTuple]);
// $ExpectType void
testMeshLine.setPath([pixel]);
// $ExpectType void
testMeshLine.setWidth(10);
// $ExpectType void
testMeshLine.setHeight(10);
// $ExpectType void
testMeshLine.setColor('red');
/**
* object3d/prism.ts
*/
// $ExpectError
new AMap.Object3D.Prism();
// $ExpectError
new AMap.Object3D.Prism({});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [lnglat],
color: 'red'
});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [lnglat],
color: 'red',
height: 1,
color2: 'blue'
});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [pixel],
color: 'red'
});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [lnglat],
color: 'red'
});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [[lnglat]],
color: 'red'
});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [[pixel]],
color: 'red'
});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [[lnglatTuple]],
color: 'red'
});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [lnglat],
color: ['red']
});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [lnglat],
color: [1, 1, 1, 1]
});
// $ExpectType Prism
new AMap.Object3D.Prism({
path: [lnglat],
color: [[1, 1, 1, 1]]
}); | the_stack |
import assert from 'assert'
import { JSONSchema7 } from 'json-schema'
import { updateSchema } from '../src/json-schema'
import {
addProperty,
inside,
map,
headProperty,
wrapProperty,
hoistProperty,
plungeProperty,
renameProperty,
convertValue,
} from '../src/helpers'
describe('transforming a json schema', () => {
const v1Schema = {
$schema: 'http://json-schema.org/draft-07/schema',
type: 'object',
title: 'ProjectDoc',
description: 'An Arthropod project with some tasks',
additionalProperties: false,
$id: 'ProjectV1',
properties: {
name: {
type: 'string',
default: '',
},
summary: {
type: 'string',
default: '',
},
},
required: ['name', 'summary'],
} as JSONSchema7 // need to convince typescript this is valid json schema
describe('addProperty', () => {
it('adds the property', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'description', type: 'string' }),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
description: { type: 'string', default: '' },
})
})
it('supports nullable fields', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'description', type: ['string', 'null'] }),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
description: { type: ['string', 'null'], default: null },
})
})
it('uses default value if provided', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'description', type: 'string', default: 'hi' }),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
description: { type: 'string', default: 'hi' },
})
})
it('sets field as required', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'description', type: 'string', required: true }),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
description: { type: 'string', default: '' },
})
assert.deepEqual(newSchema.required, [...(v1Schema.required || []), 'description'])
})
it('fails when presented with invalid data', () => {
const badData: any = { garbage: 'input' }
assert.throws(() => {
updateSchema(v1Schema, [addProperty(badData)])
}, `Missing property name in addProperty.\nFound:\n${JSON.stringify(badData)}`)
})
})
describe('renameProperty', () => {
const newSchema = updateSchema(v1Schema, [renameProperty('name', 'title')])
it('adds a new property and removes the old property', () => {
assert.deepEqual(newSchema.properties, {
title: {
type: 'string',
default: '',
},
summary: {
type: 'string',
default: '',
},
})
})
it('removes the old property from required array', () => {
assert.equal(newSchema.required?.indexOf('name'), -1)
})
})
describe('convertValue', () => {
it('changes the type on the existing property', () => {
const newSchema = updateSchema(v1Schema, [
convertValue(
'summary',
[
{ todo: false, inProgress: false, done: true },
{ false: 'todo', true: 'done' },
],
'string',
'boolean'
),
])
assert.deepEqual(newSchema.properties, {
name: {
type: 'string',
default: '',
},
summary: {
type: 'boolean',
default: false,
},
})
})
it("doesn't update the schema when there's no type change", () => {
const newSchema = updateSchema(v1Schema, [
convertValue('summary', [{ something: 'another' }, { another: 'something' }]),
])
assert.deepEqual(newSchema, v1Schema)
})
it('fails when presented with invalid data', () => {
const badData: any = { garbage: 'input' }
assert.throws(() => {
updateSchema(v1Schema, [addProperty(badData)])
}, `Missing property destinationType in 'convert'.\nFound:\n${JSON.stringify(badData)}`)
})
})
describe('inside', () => {
it('adds new properties inside a key', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'metadata', type: 'object' }),
inside('metadata', [
addProperty({ name: 'createdAt', type: 'number' }),
addProperty({ name: 'updatedAt', type: 'number' }),
]),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
metadata: {
type: 'object',
default: {},
properties: {
createdAt: {
type: 'number',
default: 0,
},
updatedAt: {
type: 'number',
default: 0,
},
},
required: ['createdAt', 'updatedAt'],
},
})
})
it('renames properties inside a key', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'metadata', type: 'object' }),
inside('metadata', [
addProperty({ name: 'createdAt', type: 'number' }),
renameProperty('createdAt', 'created'),
]),
])
assert.deepEqual(newSchema.properties, {
name: {
type: 'string',
default: '',
},
summary: {
type: 'string',
default: '',
},
metadata: {
type: 'object',
default: {},
properties: {
created: {
type: 'number',
default: 0,
},
},
required: ['created'],
},
})
})
})
describe('map', () => {
it('adds new properties inside an array', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'tasks', type: 'array', items: { type: 'object' as const } }),
inside('tasks', [
map([
addProperty({ name: 'name', type: 'string' }),
addProperty({ name: 'description', type: 'string' }),
]),
]),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
tasks: {
type: 'array',
default: [],
items: {
type: 'object',
default: {},
properties: {
name: {
type: 'string',
default: '',
},
description: {
type: 'string',
default: '',
},
},
required: ['name', 'description'],
},
},
})
})
it('renames properties inside an array', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'tasks', type: 'array', items: { type: 'object' as const } }),
inside('tasks', [
map([addProperty({ name: 'name', type: 'string' }), renameProperty('name', 'title')]),
]),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
tasks: {
type: 'array',
default: [],
items: {
type: 'object',
default: {},
properties: {
title: {
type: 'string',
default: '',
},
},
required: ['title'],
},
},
})
})
})
describe('headProperty', () => {
it('can turn an array into a scalar', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'assignees', type: 'array', items: { type: 'string' as const } }),
headProperty('assignees'),
])
// Really, the correct result would be:
// { { type: 'null', type: 'string' }, default: 'Joe' } }
// the behaviour you see below here doesn't really work with at least AJV
// https://github.com/ajv-validator/ajv/issues/276
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
assignees: { anyOf: [{ type: 'null' }, { type: 'string', default: '' }] },
})
})
it('can preserve schema information for an array of objects becoming a single object', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'assignees', type: 'array', items: { type: 'object' as const } }),
inside('assignees', [map([addProperty({ name: 'name', type: 'string' })])]),
headProperty('assignees'),
])
const expectedSchema = {
...v1Schema.properties,
assignees: {
anyOf: [
{ type: 'null' },
{
type: 'object',
default: {},
properties: {
name: { type: 'string', default: '' },
},
required: ['name'],
},
],
},
}
assert.deepEqual(newSchema.properties, expectedSchema)
})
})
describe('wrapProperty', () => {
it('can wrap a scalar into an array', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'assignee', type: ['string', 'null'] }),
wrapProperty('assignee'),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
assignee: {
type: 'array',
default: [],
items: {
type: 'string' as const,
default: '',
},
},
})
})
it.skip('can wrap an object into an array', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'assignee', type: ['object', 'null'] }),
inside('assignee', [
addProperty({ name: 'id', type: 'string' }),
addProperty({ name: 'name', type: 'string' }),
]),
wrapProperty('assignee'),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
assignee: {
type: 'array',
default: [],
items: {
type: 'object' as const,
properties: {
name: { type: 'string', default: '' },
id: { type: 'string', default: '' },
},
},
},
})
})
})
describe('hoistProperty', () => {
it('hoists the property up in the schema', () => {
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'metadata', type: 'object' }),
inside('metadata', [
addProperty({ name: 'createdAt', type: 'number' }),
addProperty({ name: 'editedAt', type: 'number' }),
]),
hoistProperty('metadata', 'createdAt'),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
metadata: {
type: 'object',
default: {},
properties: {
editedAt: {
type: 'number',
default: 0,
},
},
required: ['editedAt'],
},
createdAt: {
type: 'number',
default: 0,
},
})
})
it('hoists up an object with child properties', () => {
// hoist up a details object out of metadata
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'metadata', type: 'object' }),
inside('metadata', [
addProperty({ name: 'details', type: 'object' }),
inside('details', [addProperty({ name: 'title', type: 'string' })]),
]),
hoistProperty('metadata', 'details'),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
metadata: {
type: 'object',
default: {},
properties: {},
required: [],
},
details: {
type: 'object',
default: {},
properties: {
title: { type: 'string', default: '' },
},
required: ['title'],
},
})
})
})
describe('plungeProperty', () => {
it('plunges the property down in the schema', () => {
// move the existing summary down into a metadata object
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'metadata', type: 'object' }),
inside('metadata', [
addProperty({ name: 'createdAt', type: 'number' }),
addProperty({ name: 'editedAt', type: 'number' }),
]),
plungeProperty('metadata', 'summary'),
])
assert.deepEqual(newSchema.properties, {
name: v1Schema.properties?.name,
metadata: {
type: 'object',
default: {},
properties: {
createdAt: {
type: 'number',
default: 0,
},
editedAt: {
type: 'number',
default: 0,
},
summary: {
type: 'string',
default: '',
},
},
required: ['createdAt', 'editedAt', 'summary'],
},
})
})
it('fails when presented with invalid data', () => {
assert.throws(() => {
updateSchema(v1Schema, [plungeProperty('metadata', 'nosaj-thing')])
}, /Could not find a property called nosaj-thing among/)
})
it.skip('plunges an object down with its child properties', () => {
// plunge metadata object into a container object
const newSchema = updateSchema(v1Schema, [
addProperty({ name: 'container', type: 'object' }),
addProperty({ name: 'metadata', type: 'object' }),
inside('metadata', [
addProperty({ name: 'createdAt', type: 'number' }),
addProperty({ name: 'editedAt', type: 'number' }),
]),
plungeProperty('container', 'metadata'),
])
assert.deepEqual(newSchema.properties, {
...v1Schema.properties,
container: {
type: 'object',
default: {},
required: ['metadata'],
properties: {
metadata: {
type: 'object',
default: {},
properties: {
createdAt: {
type: 'number',
default: 0,
},
editedAt: {
type: 'number',
default: 0,
},
},
required: ['createdAt', 'editedAt', 'summary'],
},
},
},
})
})
})
}) | the_stack |
import { Buffer } from './buffer';
import { Context } from './context';
import { Initializable } from './initializable';
/* spellchecker: enable */
/**
* Class to encapsulating a WebGL buffer adding functionality to record changes to the underlying buffer without
* instantly propagating them to the WebGL buffer. It is intended to be a direct replacement for {@link Buffer}.
* When calling {@link subData} the data will be copied to an internal, CPU-sided buffer and the affecting range will be
* recorded. If the newly recorded range overrides a part of or the whole of a previously recorded range the older one
* will either be discarded completely or merged with the new one according to a specifiable merge threshold.
* To propagate all recorded changes to the GPU-sided buffer, {@link update} has to be called. This will take care of
* both the allocation of the GPU-sided buffer and the transfer of the changed data.
* While {@link update} can must only be called after initializing the object, {@link subData},
* {@link mergeSubDataRanges} and resizing (@see{@link size}) can be called on the unitialized object.
* The GPU-sided buffer is created on initialization and deleted on uninitialization.
* A typical usage could look like this:
* ```
* // Create a unified buffer with the size of 1028 bytes and a mergeThreshold of 32 bytes
* const unifiedBuffer = new UnifiedBuffer(context, 1028, gl.STATIC_DRAW, 32, 'UnifiedBuffer');
* unifiedBuffer.initialize(gl.ARRAY_BUFFER);
* unifiedBuffer.attribEnable(0, 1, gl.FLOAT, gl.FALSE, 0, 0, true, false);
* unifiedBuffer.attribEnable(1, 1, gl.SHORT, gl.FALSE, 0, 512, false, true);
*
* unifiedBuffer.subData(0, new Float32Array(64).fill(3.14));
* unifiedBuffer.subData(512, new Int16Array(128).fill(1200));
*
* unifiedBuffer.update(true, true);
*
* unifiedBuffer.subData(128, new Float32Array(32).fill(1.57));
* unifiedBuffer.subData(640, new Int36Array(64).fill(600));
*
* unifiedBuffer.mergeThreshold = -1;
* // This will merge both already existing ranges resulting in a single update
* unifiedBuffer.mergeSubDataRanges();
*
* unifiedBuffer.bind();
* unifiedBuffer.update();
* unifiedBuffer.unbind();
* ```
*/
export class UnifiedBuffer extends Initializable {
protected _cpuBuffer: ArrayBuffer;
protected _gpuBuffer: Buffer;
protected _updates = new Array<Update>();
/** @see {@link usage} */
protected _usage: GLenum;
/** @see {@link mergeThreshold} */
protected _mergeThreshold: number;
/**
* Checks if two updates have to be merged according to the mergeThreshold. Note: lhsUpdate.begin has to be smaller
* than rhsUpdate.begin.
* @param lhsUpdate - First update
* @param rhsUpdate - Second update
* @param mergeThreshold - Threshold considered for merging.
* @returns - True if mergeThreshold == -1 or distance between the two updates <= mergeThreshold, false otherwise.
*/
protected static updatesNeedMerge(lhsUpdate: Update, rhsUpdate: Update, mergeThreshold: number): boolean {
return rhsUpdate.begin - lhsUpdate.end < mergeThreshold || mergeThreshold === -1;
}
/**
* Creates a zero initialized buffer with the given size.
* @param context - Context used for all GPU operations.
* @param sizeInBytes - Size of the buffer in bytes.
* @param usage - Usage hint for allocation of the GPU-sided buffer.
* @param mergeThreshold - Threshold in which all updates will get merged.
* @param identifier - Unique identifier for this UnifiedBuffer.
*/
constructor(context: Context, sizeInBytes: number, usage: GLenum, mergeThreshold = 0, identifier?: string) {
super();
this._cpuBuffer = new ArrayBuffer(sizeInBytes);
this._gpuBuffer = new Buffer(context, identifier);
this._usage = usage;
this._mergeThreshold = mergeThreshold;
}
/**
* Merges all updates left of index transitively with the update at index until there are no more updates within the
* merge threshold.
* @param index - Index of the update that should get merged.
* @returns - Number of merged updates.
*/
protected mergeUpdatesLeft(index: number): number {
let removeCount = 0;
const rhs = this._updates[index];
for (let i = index - 1; i >= 0; i--) {
const lhs = this._updates[i];
if (UnifiedBuffer.updatesNeedMerge(lhs, rhs, this._mergeThreshold)) {
rhs.begin = Math.min(rhs.begin, lhs.begin);
rhs.end = Math.max(rhs.end, lhs.end);
removeCount++;
} else {
break;
}
}
this._updates.splice(index - removeCount, removeCount);
return removeCount + 1;
}
/**
* Merges all updates right of index transitively with the update at index until there are no more updates within
* the merge threshold.
* @param index - Index of the update that should get merged.
* @returns - Number of merged updates.
*/
protected mergeUpdatesRight(index: number): number {
let removeCount = 0;
const lhs = this._updates[index];
for (let i = index + 1; i < this._updates.length; i++) {
const rhs = this._updates[i];
if (UnifiedBuffer.updatesNeedMerge(lhs, rhs, this._mergeThreshold)) {
lhs.begin = Math.min(lhs.begin, rhs.begin);
lhs.end = Math.max(lhs.end, rhs.end);
removeCount++;
} else {
break;
}
}
this._updates.splice(index + 1, removeCount);
return removeCount + 1;
}
/**
* Adds a range to recorded updates. Transitively merges all already recorded updates within the mergeThreshold of
* the added range.
* @param update - Range to add to the updates.
*/
protected addUpdate(update: Update): void {
const start = this._updates.findIndex((current: Update) => {
return update.begin < current.begin;
});
if (start === -1) {
this._updates.push(update);
this.mergeUpdatesLeft(this._updates.length - 1);
} else {
this._updates.splice(start, 0, update);
this.mergeUpdatesRight(start);
this.mergeUpdatesLeft(start);
}
}
/**
* Create the buffer object on the GPU.
* @param target - Target used as binding point.
*/
@Initializable.initialize()
initialize(target: GLenum): boolean {
return this._gpuBuffer.initialize(target);
}
/**
* Delete the buffer object on the GPU. This should have the reverse effect of `create`.
*/
@Initializable.uninitialize()
uninitialize(): void {
this._gpuBuffer.uninitialize();
}
/**
* Binds the buffer object as buffer to predefined target.
*/
@Initializable.assert_initialized()
bind(): void {
this._gpuBuffer.bind();
}
/**
* Binds null as current buffer to predefined target;
*/
@Initializable.assert_initialized()
unbind(): void {
this._gpuBuffer.unbind();
}
/**
* Specifies the memory layout of the buffer for a binding point.
* @param index - Index of the vertex attribute that is to be setup and enabled.
* @param size - Number of components per vertex attribute.
* @param type - Data type of each component in the array.
* @param normalized - Whether integer data values should be normalized when being casted to a float.
* @param stride - Offset in bytes between the beginning of consecutive vertex attributes.
* @param offset - Offset in bytes of the first component in the vertex attribute array.
* @param bind - Allows to skip binding the object (e.g., when binding is handled outside).
* @param unbind - Allows to skip unbinding the object (e.g., when binding is handled outside).
*/
@Initializable.assert_initialized()
attribEnable(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean = false,
stride: GLsizei = 0, offset: GLintptr = 0, bind: boolean = true, unbind: boolean = true): void {
this._gpuBuffer.attribEnable(index, size, type, normalized, stride, offset, bind, unbind);
}
/**
* Disables a buffer binding point.
* @param index - Index of the vertex attribute that is to be disabled.
* @param bind - Allows to skip binding the object (e.g., when binding is handled outside).
* @param unbind - Allows to skip unbinding the object (e.g., when binding is handled outside).
*/
@Initializable.assert_initialized()
attribDisable(index: GLuint, bind: boolean = true, unbind: boolean = true): void {
this._gpuBuffer.attribDisable(index, bind, unbind);
}
/**
* Merges all recorded subData ranges.
*/
mergeSubDataRanges(): void {
let index = 0;
while (index < this._updates.length) {
index += this.mergeUpdatesRight(index);
}
}
/**
* Copies the new data into the CPU-sided buffer and records the range as changed. All previously added ranges will
* get merged transitively with the new one, if they are within the set mergeThreshold.
* Note: This does not transfer anything to the GPU-sided buffer yet.
* @param dstByteOffset - Offset of bytes into the destination buffer.
* @param srcData - Data that will be copied into the destination buffer.
*/
subData(dstByteOffset: GLintptr, srcData: ArrayBufferView | ArrayBuffer): void {
let src: Uint8Array;
if (srcData instanceof ArrayBuffer) {
src = new Uint8Array(srcData);
} else {
src = new Uint8Array(srcData.buffer).subarray(srcData.byteOffset, srcData.byteOffset + srcData.byteLength);
}
const dst = new Uint8Array(this._cpuBuffer);
dst.set(src, dstByteOffset);
this.addUpdate({ begin: dstByteOffset, end: dstByteOffset + src.byteLength });
}
/**
* Copies all previously recorded ranges and their data to the GPU. (Re-)Allocate the GPU-sided buffer if the size
* changed or the object was reinitialized.
* @param bind - Allows to skip binding the object (e.g., when binding is handled outside).
* @param unbind - Allows to skip unbinding the object (e.g., when binding is handled outside).
*/
@Initializable.assert_initialized()
update(bind: boolean = false, unbind: boolean = false): void {
if (bind) {
this._gpuBuffer.bind();
}
if (this._gpuBuffer.bytes !== this._cpuBuffer.byteLength) {
this._gpuBuffer.data(this._cpuBuffer, this._usage);
} else {
const bufferView = new Uint8Array(this._cpuBuffer);
for (const update of this._updates) {
const subBufferView = bufferView.subarray(update.begin, update.end);
this._gpuBuffer.subData(update.begin, subBufferView);
}
}
if (unbind) {
this._gpuBuffer.unbind();
}
this._updates.length = 0;
}
/**
* Returns the size of the CPU-sided buffer. This is not necessarily the same as the size of the GPU-sided buffer,
* if update has not been called after resizing the buffer.
*/
get size(): number {
return this._cpuBuffer.byteLength;
}
/**
* Resizes the buffer. Note, that this does not resize the GPU-sided buffer. To update the size of the GPU-sided
* buffer update has to be called.
*/
set size(sizeInBytes: number) {
const oldBuffer = this._cpuBuffer;
this._cpuBuffer = new ArrayBuffer(sizeInBytes);
// Takes the whole buffer, if sizeInBytes > oldBuffer
// Takes sizeInBytes of oldBuffer otherwise
const src = new Uint8Array(oldBuffer).slice(0, sizeInBytes);
const dst = new Uint8Array(this._cpuBuffer);
dst.set(src);
}
/**
* Target to which the buffer object is bound (either GL_ARRAY_BUFFER or GL_ELEMENT_ARRAY_BUFFER).
* Readonly access to the target (as specified on initialization) the buffer will be bound to.
*/
get target(): GLenum | undefined {
this.assertInitialized();
return this._gpuBuffer.target;
}
/**
* Returns the usage hint used for allocation of the GPU-sided buffer.
*/
get usage(): GLenum {
return this._usage;
}
/**
* Sets the usage hint used for allocation of the GPU-sided buffer.
*/
set usage(usage: GLenum) {
this._usage = usage;
}
/**
* Returns the threshold used to determine whether two ranges have to be merged.
*/
get mergeThreshold(): number {
return this._mergeThreshold;
}
/**
* Sets the threshold determining whether two ranges have to be merged. If the mergeThreshold is set to -1 all
* ranges will get merged disregarding their distance to each other.
*/
set mergeThreshold(mergeThreshold: number) {
this._mergeThreshold = mergeThreshold;
}
}
interface Update {
/** inclusive */
begin: number;
/** exclusive */
end: number;
} | the_stack |
import { Trans, t } from "@lingui/macro";
import { withI18n, i18nMark } from "@lingui/react";
import * as React from "react";
import { Hooks } from "#SRC/js/plugin-bridge/PluginSDK";
import gql from "graphql-tag";
import { DataLayerType, DataLayer } from "@extension-kid/data-layer";
import { take } from "rxjs/operators";
import { Confirm } from "reactjs-components";
import isEqual from "lodash/isEqual";
import FullScreenModal from "#SRC/js/components/modals/FullScreenModal";
import FullScreenModalHeader from "#SRC/js/components/modals/FullScreenModalHeader";
import FullScreenModalHeaderActions from "#SRC/js/components/modals/FullScreenModalHeaderActions";
import DataValidatorUtil from "#SRC/js/utils/DataValidatorUtil";
import ModalHeading from "#SRC/js/components/modals/ModalHeading";
import ToggleButton from "#SRC/js/components/ToggleButton";
import { deepCopy } from "#SRC/js/utils/Util";
import container from "#SRC/js/container";
import {
getDefaultJobSpec,
getDefaultContainer,
getDefaultDocker,
} from "./form/helpers/DefaultFormData";
import {
FormError,
JobSpec,
JobOutput,
Action,
Container,
JobAPIOutput,
} from "./form/helpers/JobFormData";
import { JobResponse } from "src/js/events/MetronomeClient";
import JobForm from "./JobsForm";
import {
MetronomeSpecValidators,
validateSpec,
} from "./form/helpers/MetronomeJobValidators";
import {
jobSpecToOutputParser,
removeBlankProperties,
} from "./form/helpers/JobParsers";
import { jobFormOutputToSpecReducer } from "./form/reducers/JobReducers";
import UserSettingsStore from "#SRC/js/stores/UserSettingsStore";
interface JobFormModalProps {
job?: JobResponse;
isEdit: boolean;
isOpen: boolean;
closeModal: () => void;
i18n: any;
}
interface JobFormModalState {
jobOutput: JobOutput;
jobSpec: JobSpec;
hasSchedule: boolean; // Whether the original job has a schedule or not, so that we know whether to PUT or POST a schedule if added
scheduleFailure: boolean;
validationErrors: FormError[];
formJSONErrors: FormError[];
serverErrors: FormError[];
formInvalid: boolean;
processing: boolean;
confirmOpen: boolean;
showValidationErrors: boolean;
activeTab: string;
isJSONModeActive: boolean;
submitFailed: boolean;
isConfirmOpen: boolean;
}
const dataLayer = container.get<DataLayer>(DataLayerType);
const createJobMutation = gql`
mutation {
createJob(data: $data) {
jobId
}
}
`;
const editJobMutation = gql`
mutation {
updateJob(id: $jobId, data: $data, existingSchedule: $existingSchedule) {
jobId
}
}
`;
class JobFormModal extends React.Component<
JobFormModalProps,
JobFormModalState
> {
constructor(props: JobFormModalProps) {
super(props);
this.state = this.getInitialState();
this.onChange = this.onChange.bind(this);
this.handleJSONToggle = this.handleJSONToggle.bind(this);
this.handleJobRun = this.handleJobRun.bind(this);
this.getAllErrors = this.getAllErrors.bind(this);
this.handleTabChange = this.handleTabChange.bind(this);
this.handleFormErrorsChange = this.handleFormErrorsChange.bind(this);
this.handleClose = this.handleClose.bind(this);
this.getSubmitAction = this.getSubmitAction.bind(this);
this.getErrorMessage = this.getErrorMessage.bind(this);
this.confirmClose = this.confirmClose.bind(this);
this.handleCancelClose = this.handleCancelClose.bind(this);
this.validateSpec = this.validateSpec.bind(this);
}
public UNSAFE_componentWillReceiveProps(nextProps: JobFormModalProps) {
if (!isEqual(nextProps.job, this.props.job)) {
const jobSpec = nextProps.job
? this.getJobSpecFromResponse(nextProps.job)
: getDefaultJobSpec();
this.setState({ jobSpec });
}
}
public shouldComponentUpdate(
nextProps: JobFormModalProps,
nextState: JobFormModalState
) {
const { job, isOpen } = this.props;
if (nextState !== this.state) {
return true;
}
if (
((nextProps.job || job) && nextProps.job === job) ||
nextProps.isOpen === isOpen
) {
return false;
}
return true;
}
public getInitialState() {
const { job } = this.props;
const jobSpec = job
? this.getJobSpecFromResponse(job)
: getDefaultJobSpec();
const hasSchedule = !!(jobSpec.job.schedules && jobSpec.job.schedules[0]);
const jobOutput = jobSpecToOutputParser(jobSpec);
return {
jobSpec,
jobOutput,
hasSchedule,
scheduleFailure: false,
validationErrors: [],
formJSONErrors: [],
serverErrors: [],
processing: false,
confirmOpen: false,
isJSONModeActive: UserSettingsStore.JSONEditorExpandedSetting,
showValidationErrors: false,
formInvalid: false,
submitFailed: false,
activeTab: "general",
isConfirmOpen: false,
};
}
public getJobSpecFromResponse(job: JobResponse): JobSpec {
const jobCopy = deepCopy(job);
const cmdOnly = !(jobCopy.run.docker || jobCopy.run.ucr);
const container = jobCopy.run.docker ? Container.Docker : Container.UCR;
if (jobCopy.run.ucr) {
jobCopy.run.docker = getDefaultDocker();
jobCopy.run.docker.image =
jobCopy.run.ucr.image && jobCopy.run.ucr.image.id;
jobCopy.run.docker.forcePullImage =
jobCopy.run.ucr.image && jobCopy.run.ucr.image.forcePull;
} else if (jobCopy.run.docker) {
jobCopy.run.ucr = getDefaultContainer();
jobCopy.run.ucr.image.id = jobCopy.run.docker.image;
jobCopy.run.ucr.image.forcePull = jobCopy.run.docker.forcePullImage;
} else {
jobCopy.run.docker = getDefaultDocker();
jobCopy.run.ucr = getDefaultContainer();
}
if (jobCopy.labels) {
jobCopy.labels = Object.entries(jobCopy.labels);
}
if (jobCopy.run.env) {
jobCopy.run.env = Object.entries(jobCopy.run.env);
}
const { _itemData, ...jobOnly } = jobCopy;
const jobSpec = {
cmdOnly,
container,
job: jobOnly,
};
return Hooks.applyFilter("jobResponseToSpecParser", jobSpec);
}
public onChange(action: Action) {
const { submitFailed, jobSpec } = this.state;
const newJobSpec = jobFormOutputToSpecReducer(action, jobSpec);
const specErrors = this.validateSpec(newJobSpec);
const outputErrors = this.validateJobOutput(
jobSpecToOutputParser(newJobSpec)
);
const validationErrors = submitFailed
? outputErrors.concat(specErrors)
: [];
this.setState({ jobSpec: newJobSpec, validationErrors });
}
public handleTabChange(activeTab: string) {
this.setState({ activeTab });
}
public handleClose() {
const { closeModal } = this.props;
closeModal();
this.setState(this.getInitialState());
}
public handleCancelClose() {
this.setState({ isConfirmOpen: false });
}
public confirmClose() {
this.setState({ isConfirmOpen: true });
}
public handleJSONToggle() {
UserSettingsStore.setJSONEditorExpandedSetting(
!this.state.isJSONModeActive
);
this.setState({ isJSONModeActive: !this.state.isJSONModeActive });
}
public getSubmitAction(jobOutput: JobOutput) {
const { isEdit } = this.props;
const { hasSchedule, scheduleFailure } = this.state;
const data: JobAPIOutput = {
job: jobOutput,
};
if (jobOutput.schedules) {
data.schedule = jobOutput.schedules[0];
delete jobOutput.schedules;
}
if (isEdit || scheduleFailure) {
const editContext = {
jobId: jobOutput.id,
data,
existingSchedule: hasSchedule,
};
return dataLayer.query(editJobMutation, editContext);
}
{
const createContext = {
data,
};
return dataLayer.query(createJobMutation, createContext);
}
}
public getErrorMessage(err: any) {
if (err.response && err.response.details && err.response.details.length) {
return err.response.details.map(
(e: { path: string; errors: string[]; type?: string }) => {
// Error message will be specific to either the job or the schedule, so we need to
// prefix the given path with `job` or `schedule` to give the error messages the correct
// visibility.
const prefix = err.type === "SCHEDULE" ? "schedule" : "job";
// The path from the server error will look like ex `\/run\/gpus` so splitting on "\/"
// will give the correct array path.
const path = [prefix].concat(
// Linter does not like `\` but it is necessary here.
e.path.split("/").filter((pathSegment) => pathSegment !== "")
);
return {
path,
message: e.errors.join(" "),
};
}
);
}
{
const message =
err.response && err.response.message
? err.response.message
: err.response
? err.response
: err;
return [
{
path: [],
message,
},
];
}
}
public validateSpec(jobSpec: JobSpec): FormError[] {
return Hooks.applyFilter(
"jobsValidateSpec",
validateSpec(jobSpec),
jobSpec
);
}
public handleJobRun() {
const { jobSpec, formJSONErrors } = this.state;
const jobOutput = removeBlankProperties(jobSpecToOutputParser(jobSpec));
const validationErrors = this.validateJobOutput(jobOutput).concat(
this.validateSpec(jobSpec)
);
const totalErrors = validationErrors.concat(formJSONErrors);
if (totalErrors.length) {
this.setState({
validationErrors,
showValidationErrors: true,
submitFailed: true,
});
} else {
this.setState({
validationErrors,
processing: true,
submitFailed: false,
jobOutput,
});
this.getSubmitAction(jobOutput)
.pipe(take(1))
.subscribe({
next: () => this.handleClose(),
error: (e) => {
if (e.type === "SCHEDULE") {
this.setState({
scheduleFailure: true,
processing: false,
serverErrors: this.getErrorMessage(e),
showValidationErrors: true,
});
} else {
this.setState({
processing: false,
serverErrors: this.getErrorMessage(e),
showValidationErrors: true,
});
}
},
});
}
}
public handleFormErrorsChange(errors: FormError[]) {
this.setState({ formJSONErrors: errors });
}
/**
* This function returns errors produced by the form validators
*/
public validateJobOutput(jobOutput: JobOutput) {
return DataValidatorUtil.validate(
jobOutput,
Object.values(
Hooks.applyFilter("metronomeValidators", MetronomeSpecValidators)
)
);
}
/**
* This function combines the errors received from metronome and the errors
* produced by the form into a unified error array
*/
public getAllErrors(): FormError[] {
const { serverErrors, formJSONErrors, validationErrors } = this.state;
return serverErrors.concat(formJSONErrors).concat(validationErrors);
}
public getHeader() {
// TODO: This should say edit if the component is given a job to edit
const { isEdit } = this.props;
const { scheduleFailure } = this.state;
const title =
isEdit || scheduleFailure ? (
<Trans render="span">Edit Job</Trans>
) : (
<Trans render="span">New Job</Trans>
);
return (
<FullScreenModalHeader>
<FullScreenModalHeaderActions
actions={this.getSecondaryActions()}
type="secondary"
/>
<div className="modal-full-screen-header-title">{title}</div>
<FullScreenModalHeaderActions
actions={this.getPrimaryActions()}
type="primary"
/>
</FullScreenModalHeader>
);
}
public getModalContent() {
const {
isJSONModeActive,
jobSpec,
showValidationErrors,
activeTab,
} = this.state;
const { isEdit } = this.props;
return (
<JobForm
errors={this.getAllErrors()}
activeTab={activeTab}
handleTabChange={this.handleTabChange}
isJSONModeActive={isJSONModeActive}
onChange={this.onChange}
jobSpec={jobSpec}
showAllErrors={showValidationErrors}
onErrorsChange={this.handleFormErrorsChange}
isEdit={isEdit}
/>
);
}
public getPrimaryActions() {
const { processing } = this.state;
return [
{
node: (
<ToggleButton
className="flush"
checkboxClassName="toggle-button toggle-button-align-left"
checked={this.state.isJSONModeActive}
onChange={this.handleJSONToggle}
key="json-editor"
>
<Trans render="span">JSON Editor</Trans>
</ToggleButton>
),
},
{
className: "button-primary flush-vertical",
clickHandler: this.handleJobRun,
label: processing ? i18nMark("Submitting...") : i18nMark("Submit"),
disabled: processing,
},
];
}
public getSecondaryActions() {
return [
{
className: "button-primary-link button-flush-horizontal",
clickHandler: this.confirmClose,
label: i18nMark("Cancel"),
},
];
}
public render() {
const { isOpen, i18n } = this.props;
const { isConfirmOpen } = this.state;
const useGemini = false;
return (
<FullScreenModal
header={this.getHeader()}
onClose={this.handleClose}
useGemini={useGemini}
open={isOpen}
>
{this.getModalContent()}
<Confirm
closeByBackdropClick={true}
header={
<ModalHeading>
<Trans render="span">Discard Changes?</Trans>
</ModalHeading>
}
open={isConfirmOpen}
leftButtonText={i18n._(t`Cancel`)}
leftButtonClassName="button button-primary-link flush-left"
leftButtonCallback={this.handleCancelClose}
rightButtonText={i18n._(t`Discard`)}
rightButtonClassName="button button-danger"
rightButtonCallback={this.handleClose}
showHeader={true}
>
<Trans render="p">
Are you sure you want to leave this page? Any data you entered will{" "}
be lost.
</Trans>
</Confirm>
</FullScreenModal>
);
}
}
export default withI18n()(JobFormModal); | the_stack |
// The MIT License (MIT)
//
// vs-deploy (https://github.com/mkloubert/vs-deploy)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import * as deploy_contracts from '../contracts';
import * as deploy_helpers from '../helpers';
import * as deploy_objects from '../objects';
import * as deploy_switch from '../switch';
import * as deploy_targets from '../targets';
import * as Enumerable from 'node-enumerable';
import * as i18 from '../i18';
import * as vscode from 'vscode';
import * as Workflows from 'node-workflows';
/**
* A button for a switch target.
*/
export interface DeploySwitchButton {
/**
* The custom (text) color for the button.
*/
color?: string;
/**
* Enable button or not.
*/
enabled?: boolean;
/**
* Put button on the right side or not.
*/
isRight?: boolean;
/**
* The priority.
*/
priority?: number;
/**
* The custom text.
*/
text?: string;
/**
* The custom tooltip.
*/
tooltip?: string;
}
/**
* A switch target.
*/
export interface DeployTargetSwitch extends deploy_contracts.DeployTarget {
/**
* A button for the switch.
*/
button?: DeploySwitchButton | boolean;
/**
* One or more options for the switch.
*/
options: DeployTargetSwitchOptionValue | DeployTargetSwitchOptionValue[];
}
/**
* An option entry for of a switch target.
*/
export interface DeployTargetSwitchOption extends deploy_contracts.Sortable {
/**
* [INTERNAL] DO NOT DEFINE OR OVERWRITE THIS PROPERTY BY YOUR OWN!
*
* Gets the ID of that option.
*/
__id?: any;
/**
* [INTERNAL] DO NOT DEFINE OR OVERWRITE THIS PROPERTY BY YOUR OWN!
*
* The zero-based index.
*/
__index?: number;
/**
* The description.
*/
description?: string;
/**
* Is default or not.
*/
isDefault?: boolean;
/**
* The (display) name.
*/
name?: string;
/**
* One or more other target names.
*/
targets?: string | string[];
}
/**
* A switch option value.
*/
export type DeployTargetSwitchOptionValue = DeployTargetSwitchOption | string;
class SwitchPlugin extends deploy_objects.MultiFileDeployPluginBase {
public get canGetFileInfo(): boolean {
return true;
}
public get canPull(): boolean {
return true;
}
public deployWorkspace(files: string[], target: DeployTargetSwitch, opts?: deploy_contracts.DeployWorkspaceOptions): void {
const ME = this;
if (!opts) {
opts = {};
}
let canceled = false;
ME.onCancelling(() => canceled = true,
opts);
let completedInvoked = false;
const COMPLETED = (err: any) => {
if (completedInvoked) {
return;
}
completedInvoked = true;
if (opts.onCompleted) {
opts.onCompleted(ME, {
canceled: canceled,
error: err,
target: target,
});
}
};
const OPTION = ME.getSwitchOption(target);
if (false === OPTION) {
canceled = true;
COMPLETED(null);
return;
}
const TARGETS_AND_PLUGINS = ME.getTargetsWithPlugins(target, OPTION.targets);
if (TARGETS_AND_PLUGINS.length < 1) {
canceled = true;
COMPLETED(null); //TODO: error message
return;
}
ME.forEachTargetAndPlugin(target, TARGETS_AND_PLUGINS, (t, p) => {
return new Promise<void>(async (resolve, reject) => {
const COMPLETED = deploy_helpers.createSimplePromiseCompletedAction(resolve, reject);
try {
if (p.deployWorkspace) {
p.deployWorkspace(files, t, {
baseDirectory: opts.baseDirectory,
context: opts.context || ME.context,
onBeforeDeployFile: (sender, e) => {
if (opts.onBeforeDeployFile) {
opts.onBeforeDeployFile(ME, {
destination: e.destination,
file: e.file,
target: t,
});
}
},
onCompleted: (sender, e) => {
COMPLETED(e.error);
},
onFileCompleted: (sender, e) => {
if (opts.onFileCompleted) {
opts.onFileCompleted(ME, {
canceled: e.canceled,
error: e.error,
file: e.file,
target: t,
});
}
}
});
}
else {
COMPLETED(null);
}
}
catch (e) {
COMPLETED(e);
}
});
}).then(() => {
COMPLETED(null);
}).catch((err) => {
COMPLETED(err);
});
}
public async downloadFile(file: string, target: DeployTargetSwitch, opts?: deploy_contracts.DeployFileOptions): Promise<Buffer> {
const ME = this;
if (!opts) {
opts = {};
}
let canceled = false;
ME.onCancelling(() => canceled = true,
opts);
let completedInvoked = false;
const COMPLETED = (err: any) => {
if (completedInvoked) {
return;
}
completedInvoked = true;
if (opts.onCompleted) {
opts.onCompleted(ME, {
canceled: canceled,
error: err,
file: file,
target: target,
});
}
};
const OPTION = ME.getSwitchOption(target);
if (false === OPTION) {
canceled = true;
COMPLETED(null);
return;
}
const TARGETS_AND_PLUGINS = ME.getTargetsWithPlugins(target, OPTION.targets);
if (TARGETS_AND_PLUGINS.length < 1) {
canceled = true;
COMPLETED(null); //TODO: error message
return;
}
let data: Buffer;
await ME.forEachTargetAndPlugin(target, TARGETS_AND_PLUGINS, async (t, p) => {
return new Promise<void>(async (resolve, reject) => {
const COMPLETED = deploy_helpers.createSimplePromiseCompletedAction(resolve, reject);
try {
if (p.downloadFile) {
data = await Promise.resolve(
p.downloadFile(file, t, {
baseDirectory: opts.baseDirectory,
context: opts.context || ME.context,
onBeforeDeploy: (sender, e) => {
if (opts.onBeforeDeploy) {
opts.onBeforeDeploy(ME, {
destination: e.destination,
file: e.file,
target: e.target,
});
}
},
onCompleted: (sender, e) => {
COMPLETED(e.error);
}
})
);
}
}
catch (e) {
COMPLETED(e);
}
});
});
return data;
}
private async forEachTargetAndPlugin(target: DeployTargetSwitch, targetsWithPlugins: deploy_contracts.DeployTargetWithPlugins[],
action: (target: deploy_contracts.DeployTarget, plugin: deploy_contracts.DeployPlugin) => any) {
const ME = this;
return new Promise<void>((resolve, reject) => {
const COMPLETED = deploy_helpers.createSimplePromiseCompletedAction(resolve, reject);
let canceled = false;
ME.onCancelling(() => canceled = true);
try {
let nextTarget: () => void;
nextTarget = () => {
if (canceled) {
COMPLETED(null);
return;
}
if (targetsWithPlugins.length < 1) {
COMPLETED(null);
return;
}
try {
const TARGET_AND_PLUGINS = targetsWithPlugins.shift();
const TARGET = deploy_helpers.cloneObject(
TARGET_AND_PLUGINS.target
);
const PLUGINS = TARGET_AND_PLUGINS.plugins.map(p => p);
let nextPlugin: () => void;
nextPlugin = () => {
if (canceled) {
COMPLETED(null);
return;
}
if (PLUGINS.length < 1) {
nextTarget();
return;
}
try {
const P = PLUGINS.shift();
if (action) {
Promise.resolve(action(TARGET, P)).then(() => {
nextPlugin();
}).catch((err) => {
COMPLETED(err);
});
}
else {
nextPlugin();
}
}
catch (e) {
COMPLETED(e);
}
};
nextPlugin(); // start with first plugin
// of current target
}
catch (e) {
COMPLETED(e);
}
};
nextTarget(); // start with first target
}
catch (e) {
COMPLETED(e);
}
});
}
public async getFileInfo(file: string, target: DeployTargetSwitch, opts?: deploy_contracts.DeployFileOptions): Promise<deploy_contracts.FileInfo> {
const ME = this;
if (!opts) {
opts = {};
}
let canceled = false;
ME.onCancelling(() => canceled = true,
opts);
let completedInvoked = false;
const COMPLETED = (err: any) => {
if (completedInvoked) {
return;
}
completedInvoked = true;
if (opts.onCompleted) {
opts.onCompleted(ME, {
canceled: canceled,
error: err,
file: file,
target: target,
});
}
};
const OPTION = ME.getSwitchOption(target);
if (false === OPTION) {
canceled = true;
COMPLETED(null);
return;
}
const TARGETS_AND_PLUGINS = ME.getTargetsWithPlugins(target, OPTION.targets);
if (TARGETS_AND_PLUGINS.length < 1) {
canceled = true;
COMPLETED(null); //TODO: error message
return;
}
let fi: deploy_contracts.FileInfo;
await ME.forEachTargetAndPlugin(target, TARGETS_AND_PLUGINS, async (t, p) => {
return new Promise<void>(async (resolve, reject) => {
const COMPLETED = deploy_helpers.createSimplePromiseCompletedAction(resolve, reject);
try {
if (p.getFileInfo) {
fi = await Promise.resolve(
p.getFileInfo(file, t, {
baseDirectory: opts.baseDirectory,
context: opts.context || ME.context,
onBeforeDeploy: (sender, e) => {
if (opts.onBeforeDeploy) {
opts.onBeforeDeploy(ME, {
destination: e.destination,
file: e.file,
target: e.target,
});
}
},
onCompleted: (sender, e) => {
COMPLETED(e.error);
}
})
);
}
}
catch (e) {
COMPLETED(e);
}
});
});
return fi;
}
private getSwitchOption(target: DeployTargetSwitch): DeployTargetSwitchOption | false {
const OPTION = deploy_switch.getCurrentOptionOf(target);
if (false === OPTION) {
vscode.window.showWarningMessage(
'[vs-deploy] ' + i18.t('plugins.switch.noOptionSelected')
);
return false;
}
return OPTION;
}
public info(): deploy_contracts.DeployPluginInfo {
return {
description: i18.t('plugins.switch.description'),
};
}
public pullFile(file: string, target: DeployTargetSwitch, opts?: deploy_contracts.DeployFileOptions): void {
const ME = this;
if (!opts) {
opts = {};
}
let canceled = false;
ME.onCancelling(() => canceled = true,
opts);
let completedInvoked = false;
const COMPLETED = (err: any) => {
if (completedInvoked) {
return;
}
completedInvoked = true;
if (opts.onCompleted) {
opts.onCompleted(ME, {
canceled: canceled,
error: err,
file: file,
target: target,
});
}
};
const OPTION = ME.getSwitchOption(target);
if (false === OPTION) {
canceled = true;
COMPLETED(null);
return;
}
const TARGETS_AND_PLUGINS = ME.getTargetsWithPlugins(target, OPTION.targets);
if (TARGETS_AND_PLUGINS.length < 1) {
canceled = true;
COMPLETED(null); //TODO: error message
return;
}
ME.forEachTargetAndPlugin(target, TARGETS_AND_PLUGINS, async (t, p) => {
return new Promise<void>((resolve, reject) => {
const COMPLETED = deploy_helpers.createSimplePromiseCompletedAction(resolve, reject);
try {
if (p.pullFile) {
p.pullFile(file, t, {
baseDirectory: opts.baseDirectory,
context: opts.context || ME.context,
onBeforeDeploy: (sender, e) => {
if (opts.onBeforeDeploy) {
opts.onBeforeDeploy(ME, {
destination: e.destination,
file: e.file,
target: e.target,
});
}
},
onCompleted: (sender, e) => {
COMPLETED(e.error);
},
});
}
}
catch (e) {
COMPLETED(e);
}
});
}).then(() => {
COMPLETED(null);
}).catch((err) => {
COMPLETED(err);
});
}
}
/**
* Creates a new Plugin.
*
* @param {deploy_contracts.DeployContext} ctx The deploy context.
*
* @returns {deploy_contracts.DeployPlugin} The new instance.
*/
export function createPlugin(ctx: deploy_contracts.DeployContext): deploy_contracts.DeployPlugin {
return new SwitchPlugin(ctx);
} | the_stack |
import {
SelectionStatus,
AvailabilityStatus,
} from "@commons/enums/Availability";
import { timeDay, timeHour, timeMinute } from "d3-time";
import { scaleTime } from "d3-scale";
import type { TimeInterval } from "d3-time";
import type { Manifest, TimeSlot } from "@commons/types/Availability";
import { arrayContainsArray } from "@commons/methods/component";
import type { ConsecutiveEvent } from "@commonstypes/Scheduler";
// map over the ticks() of the time scale between your start day and end day
// populate them with as many slots as your start_hour, end_hour, and slot_size dictate
export const generateDaySlots = (
timestamp: Date,
allCalendars: any[],
calendarID: string,
requiredParticipants: string[],
consecutiveOptions: ConsecutiveEvent[][],
consecutiveParticipants: string[],
internalProps: Manifest,
): any[] => {
const dayStart = timeHour(
new Date(new Date(timestamp).setHours(internalProps.start_hour)),
);
const dayEnd = timeHour(
new Date(new Date(timestamp).setHours(internalProps.end_hour)),
);
return scaleTime()
.domain([dayStart, dayEnd])
.ticks(timeMinute.every(internalProps.slot_size) as TimeInterval)
.slice(0, -1) // dont show the 25th hour
.map((time: Date) => {
const endTime = timeMinute.offset(time, internalProps.slot_size);
const freeCalendars: string[] = [];
let availability = AvailabilityStatus.FREE; // default
if (allCalendars.length) {
const currentSlot: TimeSlot = {
start_time: time,
end_time: endTime,
available_calendars: [],
expirySelection: "",
recurrence_cadence: "",
recurrence_expiry: "",
isBookable: false,
};
for (const calendar of allCalendars) {
// Adjust calendar.timeslots for buffers
const timeslots =
calendar.availability === AvailabilityStatus.BUSY
? calendar.timeslots.map((slot: TimeSlot) => ({
start_time: timeMinute.offset(
slot.start_time,
-internalProps.event_buffer,
),
end_time: timeMinute.offset(
slot.end_time,
internalProps.event_buffer,
),
}))
: calendar.timeslots.map((slot: TimeSlot) => ({
// Don't apply start-buffer to the first timeslot, nor end-buffer to the last timeslot.
// Works across multiple days; you won't get a random buffer at 11:50 / 00:10
start_time: timeMinute.offset(
slot.start_time,
slot === calendar.timeslots[0]
? 0
: internalProps.event_buffer,
),
end_time: timeMinute.offset(
slot.end_time,
slot === calendar.timeslots[calendar.timeslots.length - 1]
? 0
: -internalProps.event_buffer,
),
}));
let concurrentSlotEventsForUser = 0;
if (calendar.availability === AvailabilityStatus.BUSY) {
// For Busy calendars, a timeslot is considered available if its calendar has no overlapping events
concurrentSlotEventsForUser = overlap(timeslots, currentSlot);
} else if (calendar.availability === AvailabilityStatus.FREE) {
// For Free calendars, a timeslot is considered available if its calendar has a time that fully envelops it.
concurrentSlotEventsForUser = timeslots.some(
(blob: TimeSlot) =>
currentSlot.start_time >= blob.start_time &&
currentSlot.end_time <= blob.end_time,
)
? 1
: 0;
// slot availability is when a given timeslot has all of its minutes represented in calendar.free timeslots
}
if (calendar.availability === AvailabilityStatus.BUSY) {
if (
internalProps.capacity &&
internalProps.capacity >= 1 &&
concurrentSlotEventsForUser < internalProps.capacity
) {
freeCalendars.push(calendar?.account?.emailAddress || "");
} else if (!concurrentSlotEventsForUser) {
freeCalendars.push(calendar?.account?.emailAddress || "");
}
} else if (
calendar.availability === AvailabilityStatus.FREE ||
!calendar.availability
) {
// if a calendar is passed in without availability, assume the timeslots are available.
if (concurrentSlotEventsForUser) {
freeCalendars.push(calendar?.account?.emailAddress || "");
}
}
}
if (freeCalendars.length) {
if (freeCalendars.length === allCalendars.length) {
availability = AvailabilityStatus.FREE;
} else {
availability = AvailabilityStatus.PARTIAL;
}
} else {
availability = AvailabilityStatus.BUSY;
}
}
// If availability is partial (not 100% of calendars), and that ratio is less than partial_bookable_ratio,
// mark the slot as busy
if (
availability === AvailabilityStatus.PARTIAL &&
freeCalendars.length <
allCalendars.length * internalProps.partial_bookable_ratio
) {
availability = AvailabilityStatus.BUSY;
}
// Allows users to book over busy slots if partial_bookable_ratio is 0
if (
availability === AvailabilityStatus.BUSY &&
internalProps.partial_bookable_ratio === 0
) {
availability = AvailabilityStatus.PARTIAL;
}
// If availability is partial, but a required participant is unavailble, the slot becomes Busy
if (
availability === AvailabilityStatus.PARTIAL &&
internalProps.required_participants.length
) {
//Check if every participants is included in the available calendar
if (!arrayContainsArray(requiredParticipants, freeCalendars)) {
availability = AvailabilityStatus.BUSY;
}
}
// If mandate_top_of_hour, change any status to "busy" if it's not at :00
if (internalProps.mandate_top_of_hour && time.getMinutes() !== 0) {
availability = AvailabilityStatus.BUSY;
freeCalendars.length = 0;
}
// if the "open_hours" property has rules, adhere to them above any other event-based free/busy statuses
// (Mark the slot busy if it falls outside the open_hours)
if (internalProps.open_hours.length) {
if (availability !== AvailabilityStatus.BUSY) {
let dayRelevantRules = [];
dayRelevantRules = internalProps.open_hours.filter(
(rule) =>
!Object.prototype.hasOwnProperty.call(rule, "startWeekday") ||
rule.startWeekday === time.getDay() ||
rule.endWeekday === time.getDay(),
);
const slotExistsInOpenHours = dayRelevantRules.some((rule) => {
const ruleStartAppliedDate = Object.prototype.hasOwnProperty.call(
rule,
"startWeekday",
)
? timeDay.offset(
time,
(rule.startWeekday as number) - time.getDay(),
)
: new Date(time);
ruleStartAppliedDate.setHours(rule.startHour);
ruleStartAppliedDate.setMinutes(rule.startMinute);
const ruleEndAppliedDate = Object.prototype.hasOwnProperty.call(
rule,
"startWeekday",
)
? timeDay.offset(
time,
(rule.endWeekday as number) - time.getDay(),
)
: new Date(time);
ruleEndAppliedDate.setHours(rule.endHour);
ruleEndAppliedDate.setMinutes(rule.endMinute);
return (
time >= ruleStartAppliedDate && endTime <= ruleEndAppliedDate
);
});
if (!slotExistsInOpenHours) {
availability = AvailabilityStatus.CLOSED;
freeCalendars.length = 0;
}
}
}
// Handle the Consecutive Events model, where a slot if busy if it falls within a consecutive timeslot.
// None of the other above rules should apply, except (maybe!) Buffer and Open Hours.
if (internalProps.events?.length > 1 && consecutiveOptions.length) {
const existsWithinConsecutiveBlock = consecutiveOptions.some(
(event) => {
return (
time >= event[0].start_time &&
endTime <= event[event.length - 1].end_time
);
},
);
if (existsWithinConsecutiveBlock) {
availability = AvailabilityStatus.FREE;
freeCalendars.length = consecutiveParticipants.length;
} else {
availability = AvailabilityStatus.BUSY;
freeCalendars.length = 0;
}
}
const today = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
const dayOffset =
(new Date(timestamp).getTime() - today) / (1000 * 60 * 60 * 24);
const timeOffset =
(new Date(time).getTime() - new Date().getTime()) /
(1000 * 60 * 60 * 24);
return {
selectionStatus: SelectionStatus.UNSELECTED,
calendar_id: calendarID,
availability: availability,
available_calendars: freeCalendars,
start_time: time,
end_time: endTime,
isBookable:
timeOffset >= 0 &&
dayOffset >= internalProps.min_book_ahead_days &&
dayOffset <= internalProps.max_book_ahead_days,
};
});
};
// https://derickbailey.com/2015/09/07/check-for-date-range-overlap-with-javascript-arrays-sorting-and-reducing/
export function overlap(events: TimeSlot[], slot: TimeSlot): number {
return events.reduce((result, current) => {
const overlap =
slot.start_time < current.end_time && current.start_time < slot.end_time;
if (overlap) {
// store the amount of overlap
result++;
}
return result;
}, 0);
} | the_stack |
import {TypedSopNode} from './_Base';
import {
AttribClass,
AttribClassMenuEntries,
ObjectType,
ObjectTypeMenuEntries,
ObjectTypes,
objectTypeFromConstructor,
AttribType,
AttribTypeMenuEntries,
ATTRIBUTE_TYPES,
AttribSize,
ATTRIBUTE_CLASSES,
ATTRIBUTE_SIZE_RANGE,
} from '../../../core/geometry/Constant';
import {CoreGroup, Object3DWithGeometry} from '../../../core/geometry/Group';
import {CoreGeometry} from '../../../core/geometry/Geometry';
import {InputCloneMode} from '../../poly/InputCloneMode';
import {CorePoint} from '../../../core/geometry/Point';
import {CoreObject} from '../../../core/geometry/Object';
import {NodeParamsConfig, ParamConfig} from '../utils/params/ParamsConfig';
import {EntitySelectionHelper} from './utils/delete/EntitySelectionHelper';
import {
ByAttributeHelper,
ComparisonOperatorMenuEntries,
ComparisonOperator,
COMPARISON_OPERATORS,
} from './utils/delete/ByAttributeHelper';
import {ByExpressionHelper} from './utils/delete/ByExpressionHelper';
import {ByBboxHelper} from './utils/delete/ByBboxHelper';
import {Object3D} from 'three/src/core/Object3D';
import {ByObjectTypeHelper} from './utils/delete/ByObjectTypeHelper';
import {isBooleanTrue} from '../../../core/BooleanValue';
import {ByBoundingObjectHelper} from './utils/delete/ByBoundingObjectHelper';
class DeleteSopParamsConfig extends NodeParamsConfig {
/** @param defines the class that should be deleted (objects or vertices) */
class = ParamConfig.INTEGER(ATTRIBUTE_CLASSES.indexOf(AttribClass.VERTEX), {
menu: {
entries: AttribClassMenuEntries,
},
});
/** @param invert the selection created in the parameters below */
invert = ParamConfig.BOOLEAN(0);
// hide_objects = ParamConfig.BOOLEAN(0, {
// visibleIf: {class: ATTRIBUTE_CLASSES.indexOf(AttribClass.OBJECT)},
// });
// byObjectType
/** @param deletes objects by object type */
byObjectType = ParamConfig.BOOLEAN(0, {
visibleIf: {class: ATTRIBUTE_CLASSES.indexOf(AttribClass.OBJECT)},
});
/** @param sets which object types should be deleted */
objectType = ParamConfig.INTEGER(ObjectTypes.indexOf(ObjectType.MESH), {
menu: {
entries: ObjectTypeMenuEntries,
},
visibleIf: {
class: ATTRIBUTE_CLASSES.indexOf(AttribClass.OBJECT),
byObjectType: true,
},
separatorAfter: true,
});
// byExpression
/** @param deletes objects by an expression */
byExpression = ParamConfig.BOOLEAN(0);
/** @param sets the expression to select what should be deleted */
expression = ParamConfig.BOOLEAN('@ptnum==0', {
visibleIf: {byExpression: true},
expression: {forEntities: true},
separatorAfter: true,
});
// byAttrib
/** @param deletes objects by an attribute */
byAttrib = ParamConfig.BOOLEAN(0);
/** @param sets the type of the attribute for which items should be deleted */
attribType = ParamConfig.INTEGER(ATTRIBUTE_TYPES.indexOf(AttribType.NUMERIC), {
menu: {
entries: AttribTypeMenuEntries,
},
visibleIf: {byAttrib: 1},
});
/** @param name of the attribute used */
attribName = ParamConfig.STRING('', {
visibleIf: {byAttrib: 1},
});
/** @param size of the attribute used */
attribSize = ParamConfig.INTEGER(1, {
range: ATTRIBUTE_SIZE_RANGE,
rangeLocked: [true, true],
visibleIf: {byAttrib: 1, attribType: ATTRIBUTE_TYPES.indexOf(AttribType.NUMERIC)},
});
/** @param comparison operator */
attribComparisonOperator = ParamConfig.INTEGER(COMPARISON_OPERATORS.indexOf(ComparisonOperator.EQUAL), {
menu: {
entries: ComparisonOperatorMenuEntries,
},
visibleIf: {
byAttrib: true,
attribType: ATTRIBUTE_TYPES.indexOf(AttribType.NUMERIC),
attribSize: AttribSize.FLOAT,
},
});
/** @param value of the attribute to compare with (when using float attribute) */
attribValue1 = ParamConfig.FLOAT(0, {
visibleIf: {byAttrib: 1, attribType: ATTRIBUTE_TYPES.indexOf(AttribType.NUMERIC), attribSize: 1},
});
/** @param value of the attribute to compare with (when using vector2 attribute) */
attribValue2 = ParamConfig.VECTOR2([0, 0], {
visibleIf: {byAttrib: 1, attribType: ATTRIBUTE_TYPES.indexOf(AttribType.NUMERIC), attribSize: 2},
});
/** @param value of the attribute to compare with (when using vector3 attribute) */
attribValue3 = ParamConfig.VECTOR3([0, 0, 0], {
visibleIf: {byAttrib: 1, attribType: ATTRIBUTE_TYPES.indexOf(AttribType.NUMERIC), attribSize: 3},
});
/** @param value of the attribute to compare with (when using vector4 attribute) */
attribValue4 = ParamConfig.VECTOR4([0, 0, 0, 0], {
visibleIf: {byAttrib: 1, attribType: ATTRIBUTE_TYPES.indexOf(AttribType.NUMERIC), attribSize: 4},
});
/** @param value of the attribute to compare with (when using string attribute) */
attribString = ParamConfig.STRING('', {
visibleIf: {byAttrib: 1, attribType: ATTRIBUTE_TYPES.indexOf(AttribType.STRING)},
separatorAfter: true,
});
// byBbox
/** @param deletes objects that are inside a bounding box */
byBbox = ParamConfig.BOOLEAN(0, {
visibleIf: {
class: ATTRIBUTE_CLASSES.indexOf(AttribClass.VERTEX),
},
});
/** @param the bounding box size */
bboxSize = ParamConfig.VECTOR3([1, 1, 1], {
visibleIf: {
class: ATTRIBUTE_CLASSES.indexOf(AttribClass.VERTEX),
byBbox: true,
},
});
/** @param the bounding box center */
bboxCenter = ParamConfig.VECTOR3([0, 0, 0], {
visibleIf: {
class: ATTRIBUTE_CLASSES.indexOf(AttribClass.VERTEX),
byBbox: true,
},
separatorAfter: true,
});
// byBoundingObject
/** @param deletes objects that are inside an object. This uses the object from the 2nd input */
byBoundingObject = ParamConfig.BOOLEAN(0, {
visibleIf: {
class: ATTRIBUTE_CLASSES.indexOf(AttribClass.VERTEX),
},
});
// by_visible
// by_visible = ParamConfig.BOOLEAN(0, {
// visibleIf: {class: ATTRIBUTE_CLASSES.indexOf(AttribClass.OBJECT)},
// });
/** @param keeps points */
keepPoints = ParamConfig.BOOLEAN(0, {
visibleIf: {class: ATTRIBUTE_CLASSES.indexOf(AttribClass.OBJECT)},
});
}
const ParamsConfig = new DeleteSopParamsConfig();
export class DeleteSopNode extends TypedSopNode<DeleteSopParamsConfig> {
paramsConfig = ParamsConfig;
static type() {
return 'delete';
}
private _marked_for_deletion_per_object_index: Map<number, boolean> = new Map();
public readonly entitySelectionHelper = new EntitySelectionHelper(this);
public readonly byExpressionHelper = new ByExpressionHelper(this);
public readonly byAttributeHelper = new ByAttributeHelper(this);
public readonly byObjectTypeHelper = new ByObjectTypeHelper(this);
public readonly byBboxHelper = new ByBboxHelper(this);
public readonly byBoundingObjectHelper = new ByBoundingObjectHelper(this);
static displayedInputNames(): string[] {
return ['geometry to delete from', 'points inside this geometry will be deleted (optional)'];
}
initializeNode() {
this.io.inputs.setCount(1, 2);
this.io.inputs.initInputsClonedState(InputCloneMode.FROM_NODE);
}
async cook(input_contents: CoreGroup[]) {
const core_group = input_contents[0];
const core_group2 = input_contents[1];
switch (this.pv.class) {
case AttribClass.VERTEX:
await this._eval_for_points(core_group, core_group2);
break;
case AttribClass.OBJECT:
await this._eval_for_objects(core_group);
break;
}
}
set_class(attrib_class: AttribClass) {
this.p.class.set(attrib_class);
}
private async _eval_for_objects(core_group: CoreGroup) {
const core_objects = core_group.coreObjects();
this.entitySelectionHelper.init(core_objects);
this._marked_for_deletion_per_object_index = new Map();
for (let core_object of core_objects) {
this._marked_for_deletion_per_object_index.set(core_object.index(), false);
}
if (isBooleanTrue(this.pv.byExpression)) {
await this.byExpressionHelper.evalForEntities(core_objects);
}
if (isBooleanTrue(this.pv.byObjectType)) {
this.byObjectTypeHelper.eval_for_objects(core_objects);
}
if (isBooleanTrue(this.pv.byAttrib) && this.pv.attribName != '') {
this.byAttributeHelper.evalForEntities(core_objects);
}
const core_objects_to_keep = this.entitySelectionHelper.entities_to_keep() as CoreObject[];
const objects_to_keep = core_objects_to_keep.map((co) => co.object());
if (isBooleanTrue(this.pv.keepPoints)) {
const core_objects_to_delete = this.entitySelectionHelper.entities_to_delete() as CoreObject[];
for (let core_object_to_delete of core_objects_to_delete) {
const point_object = this._point_object(core_object_to_delete);
if (point_object) {
objects_to_keep.push(point_object);
}
}
}
this.setObjects(objects_to_keep);
}
private async _eval_for_points(core_group: CoreGroup, core_group2?: CoreGroup) {
const core_objects = core_group.coreObjects();
let core_object;
let objects: Object3D[] = [];
for (let i = 0; i < core_objects.length; i++) {
core_object = core_objects[i];
let core_geometry = core_object.coreGeometry();
if (core_geometry) {
const object = core_object.object() as Object3DWithGeometry;
const points = core_geometry.pointsFromGeometry();
this.entitySelectionHelper.init(points);
const init_points_count = points.length;
if (isBooleanTrue(this.pv.byExpression)) {
await this.byExpressionHelper.evalForEntities(points);
}
// TODO: the helpers do not yet take into account if an entity has been selected or not.
// This could really speed up iterating through them, as I could skip the ones that have already been
if (isBooleanTrue(this.pv.byAttrib) && this.pv.attribName != '') {
this.byAttributeHelper.evalForEntities(points);
}
if (isBooleanTrue(this.pv.byBbox)) {
this.byBboxHelper.evalForPoints(points);
}
if (isBooleanTrue(this.pv.byBoundingObject)) {
this.byBoundingObjectHelper.evalForPoints(points, core_group2);
}
const kept_points = this.entitySelectionHelper.entities_to_keep() as CorePoint[];
if (kept_points.length == init_points_count) {
objects.push(object);
} else {
core_geometry.geometry().dispose();
if (kept_points.length > 0) {
const new_geo = CoreGeometry.geometryFromPoints(
kept_points,
objectTypeFromConstructor(object.constructor)
);
if (new_geo) {
object.geometry = new_geo;
objects.push(object);
}
}
}
}
}
this.setObjects(objects);
}
private _point_object(core_object: CoreObject) {
const core_points = core_object.points();
const geometry = CoreGeometry.geometryFromPoints(core_points, ObjectType.POINTS);
if (geometry) return this.createObject(geometry, ObjectType.POINTS);
}
} | the_stack |
import * as singleLineString from "single-line-string";
import { BigNumber } from "../../utils/bignumber";
import {
BLOCK_TIME_ESTIMATE_SECONDS,
NULL_ADDRESS,
NULL_ECDSA_SIGNATURE,
SALT_DECIMALS,
} from "../../utils/constants";
import { CollateralizedSimpleInterestLoanOrder } from "../adapters/collateralized_simple_interest_loan_adapter";
import { Dharma } from "../types/dharma";
import { DebtOrderDataWrapper } from "../wrappers";
import { SignatureUtils } from "../../utils/signature_utils";
import {
DebtOrderData,
DurationUnit,
ECDSASignature,
EthereumAddress,
InterestRate,
TimeInterval,
TokenAmount,
UnderwriterRiskRating,
} from "../types";
export const DEBT_ORDER_ERRORS = {
ALREADY_SIGNED_BY_DEBTOR: `A debtor has already signed this debt order.`,
ALREADY_SIGNED_BY_CREDITOR: `A creditor has already signed this debt order.`,
ALREADY_SIGNED_BY_UNDERWRITER: `An underwriter has already signed this debt order.`,
PROXY_FILL_DISALLOWED: (className: string) =>
singleLineString`A ${className} must be signed by both the creditor and
debtor before it can be filled by proxy.`,
};
export interface DebtOrderConstructorParams {
principal: TokenAmount;
collateral: TokenAmount;
interestRate: InterestRate;
termLength: TimeInterval;
expiresAt: number;
// relayer
relayer?: EthereumAddress;
relayerFee?: TokenAmount;
// fee splitting
creditorFee?: TokenAmount;
debtorFee?: TokenAmount;
// underwriter
underwriterRiskRating?: UnderwriterRiskRating;
underwriterFee?: TokenAmount;
underwriter?: EthereumAddress;
}
export interface OrderData {
kernelVersion: string;
issuanceVersion: string;
principalAmount: string;
principalToken: string;
debtor: string;
debtorFee: string;
creditor: string;
creditorFee: string;
relayer: string;
relayerFee: string;
underwriter: string;
underwriterFee: string;
underwriterRiskRating: string;
termsContract: string;
termsContractParameters: string;
expirationTimestampInSec: string;
salt: string;
debtorSignature: ECDSASignature;
creditorSignature: ECDSASignature;
underwriterSignature: ECDSASignature;
}
export interface DebtOrderParams {
principalAmount: number;
principalToken: string;
collateralAmount: number;
collateralToken: string;
interestRate: number;
termDuration: number;
termUnit: DurationUnit;
expiresInDuration: number;
expiresInUnit: DurationUnit;
relayerAddress?: string;
relayerFeeAmount?: number;
creditorFeeAmount?: number;
underwriterAddress?: string;
underwriterRiskRating?: number;
underwriterFeeAmount?: number;
}
export interface DebtOrderTerms {
principalAmount: number;
principalTokenSymbol: string;
collateralAmount: number;
collateralTokenSymbol: string;
interestRate: number;
termDuration: number;
termUnit: string;
expiresAt: number;
}
export class DebtOrder {
public static generateSalt(): BigNumber {
return BigNumber.random(SALT_DECIMALS).times(new BigNumber(10).pow(SALT_DECIMALS));
}
public static async create<T extends DebtOrder>(
dharma: Dharma,
params: DebtOrderParams,
): Promise<T> {
const {
principalAmount,
principalToken,
collateralAmount,
collateralToken,
relayerAddress,
relayerFeeAmount,
interestRate,
termDuration,
termUnit,
expiresInDuration,
expiresInUnit,
creditorFeeAmount,
underwriterFeeAmount,
underwriterAddress,
underwriterRiskRating,
} = params;
const principal = new TokenAmount(principalAmount, principalToken);
const collateral = new TokenAmount(collateralAmount, collateralToken);
const interestRateTyped = new InterestRate(interestRate);
const termLength = new TimeInterval(termDuration, termUnit);
const expiresIn = new TimeInterval(expiresInDuration, expiresInUnit);
const currentBlocktime = new BigNumber(await dharma.blockchain.getCurrentBlockTime());
const expirationTimestampInSec = expiresIn.fromTimestamp(currentBlocktime);
const loanRequestConstructorParams: DebtOrderConstructorParams = {
principal,
collateral,
interestRate: interestRateTyped,
termLength,
expiresAt: expirationTimestampInSec.toNumber(),
};
const loanOrder: CollateralizedSimpleInterestLoanOrder = {
principalAmount: principal.rawAmount,
principalTokenSymbol: principal.tokenSymbol,
interestRate: interestRateTyped.raw,
amortizationUnit: termLength.getAmortizationUnit(),
termLength: new BigNumber(termLength.amount),
collateralTokenSymbol: collateral.tokenSymbol,
collateralAmount: collateral.rawAmount,
gracePeriodInDays: new BigNumber(0),
expirationTimestampInSec,
};
const data = await dharma.adapters.collateralizedSimpleInterestLoan.toDebtOrder(loanOrder);
const debtKernel = await dharma.contracts.loadDebtKernelAsync();
const repaymentRouter = await dharma.contracts.loadRepaymentRouterAsync();
const salt = this.generateSalt();
if (relayerAddress && relayerAddress !== NULL_ADDRESS) {
const relayer = new EthereumAddress(relayerAddress);
const relayerFee = new TokenAmount(relayerFeeAmount, principalToken);
loanRequestConstructorParams.relayer = relayer;
loanRequestConstructorParams.relayerFee = relayerFee;
data.relayer = relayer.toString();
data.relayerFee = relayerFee.rawAmount;
}
if (creditorFeeAmount && creditorFeeAmount > 0) {
const creditorFee = new TokenAmount(creditorFeeAmount, principalToken);
loanRequestConstructorParams.creditorFee = creditorFee;
data.creditorFee = creditorFee.rawAmount;
}
if (underwriterAddress && underwriterAddress !== NULL_ADDRESS) {
const undewriter = new EthereumAddress(underwriterAddress);
const underwriterFee = new TokenAmount(underwriterFeeAmount, principalToken);
const riskRating = new UnderwriterRiskRating(underwriterRiskRating);
loanRequestConstructorParams.underwriter = undewriter;
loanRequestConstructorParams.underwriterFee = underwriterFee;
loanRequestConstructorParams.underwriterRiskRating = riskRating;
data.underwriter = undewriter.toString();
data.underwriterFee = underwriterFee.rawAmount;
data.underwriterRiskRating = riskRating.scaled;
}
data.kernelVersion = debtKernel.address;
data.issuanceVersion = repaymentRouter.address;
data.salt = salt;
return new this(dharma, loanRequestConstructorParams, data) as T;
}
public static async load<T extends DebtOrder>(dharma: Dharma, data: OrderData): Promise<T> {
const debtOrderData: DebtOrderData = {
...data,
principalAmount: new BigNumber(data.principalAmount),
debtorFee: new BigNumber(data.debtorFee),
creditorFee: new BigNumber(data.creditorFee),
relayerFee: new BigNumber(data.relayerFee),
underwriterFee: new BigNumber(data.underwriterFee),
underwriterRiskRating: new BigNumber(data.underwriterRiskRating),
expirationTimestampInSec: new BigNumber(data.expirationTimestampInSec),
salt: new BigNumber(data.salt),
};
const loanOrder = await dharma.adapters.collateralizedSimpleInterestLoan.fromDebtOrder(
debtOrderData,
);
const principal = TokenAmount.fromRaw(
loanOrder.principalAmount,
loanOrder.principalTokenSymbol,
);
const collateral = TokenAmount.fromRaw(
loanOrder.collateralAmount,
loanOrder.collateralTokenSymbol,
);
const interestRate = InterestRate.fromRaw(loanOrder.interestRate);
const termLength = new TimeInterval(
loanOrder.termLength.toNumber(),
loanOrder.amortizationUnit,
);
const loanRequestParams: DebtOrderConstructorParams = {
principal,
collateral,
termLength,
interestRate,
expiresAt: loanOrder.expirationTimestampInSec.toNumber(),
};
if (debtOrderData.relayer && debtOrderData.relayer !== NULL_ADDRESS) {
const relayer = new EthereumAddress(debtOrderData.relayer);
const relayerFee = TokenAmount.fromRaw(debtOrderData.relayerFee, principal.tokenSymbol);
loanRequestParams.relayer = relayer;
loanRequestParams.relayerFee = relayerFee;
}
if (debtOrderData.underwriter && debtOrderData.underwriter !== NULL_ADDRESS) {
loanRequestParams.underwriter = new EthereumAddress(debtOrderData.underwriter);
loanRequestParams.underwriterFee = TokenAmount.fromRaw(
debtOrderData.underwriterFee,
principal.tokenSymbol,
);
loanRequestParams.underwriterRiskRating = new UnderwriterRiskRating(
debtOrderData.underwriterRiskRating,
);
}
if (debtOrderData.creditorFee && debtOrderData.creditorFee.greaterThan(0)) {
loanRequestParams.creditorFee = TokenAmount.fromRaw(
debtOrderData.creditorFee,
principal.tokenSymbol,
);
}
return new this(dharma, loanRequestParams, debtOrderData) as T;
}
protected constructor(
protected readonly dharma: Dharma,
protected readonly params: DebtOrderConstructorParams,
protected data: DebtOrderData,
) {}
/**
* Returns the terms of the loan request.
*
* @example
* const terms = loanRequest.getTerms();
*
* @returns {DebtOrderTerms}
*/
public getTerms(): DebtOrderTerms {
const { principal, collateral, interestRate, termLength, expiresAt } = this.params;
return {
principalAmount: principal.decimalAmount,
principalTokenSymbol: principal.tokenSymbol,
collateralAmount: collateral.decimalAmount,
collateralTokenSymbol: collateral.tokenSymbol,
interestRate: interestRate.percent,
termDuration: termLength.amount,
termUnit: termLength.getAmortizationUnit(),
expiresAt,
};
}
/**
* Eventually returns true if the current loan request will be expired for the next block.
*
* @example
* await loanRequest.isExpired();
* => true
*
* @returns {Promise<boolean>}
*/
public async isExpired(): Promise<boolean> {
// This timestamp comes from the blockchain.
const expirationTimestamp: BigNumber = this.data.expirationTimestampInSec;
// We compare this timestamp to the expected timestamp of the next block.
const latestBlockTime = await this.dharma.blockchain.getCurrentBlockTime();
const approximateNextBlockTime = latestBlockTime + BLOCK_TIME_ESTIMATE_SECONDS;
return expirationTimestamp.lt(approximateNextBlockTime);
}
/**
* Returns whether the loan request has been signed by a debtor.
*
* @example
* loanRequest.isSignedByDebtor();
* => true
*
* @return {boolean}
*/
public isSignedByDebtor(): boolean {
const debtOrderDataWrapper = new DebtOrderDataWrapper(this.data);
if (
this.data.debtorSignature === NULL_ECDSA_SIGNATURE ||
!SignatureUtils.isValidSignature(
debtOrderDataWrapper.getDebtorCommitmentHash(),
this.data.debtorSignature,
this.data.debtor,
)
) {
return false;
}
return true;
}
/**
* Eventually signs the loan request as the debtor.
*
* @throws Throws if the loan request is already signed by a debtor.
*
* @example
* loanRequest.signAsDebtor();
* => Promise<void>
*
* @return {void}
*/
public async signAsDebtor(debtorAddress?: string): Promise<void> {
if (this.isSignedByDebtor()) {
throw Error(DEBT_ORDER_ERRORS.ALREADY_SIGNED_BY_DEBTOR);
}
this.data.debtor = await EthereumAddress.validAddressOrCurrentUser(
this.dharma,
debtorAddress,
);
const isMetaMask = !!this.dharma.web3.currentProvider.isMetaMask;
this.data.debtorSignature = await this.dharma.sign.asDebtor(this.data, isMetaMask);
}
/**
* Eventually returns true if the loan request has been cancelled.
*
* @example
* await loanRequest.isCancelled();
* => true
*
* @returns {Promise<boolean>}
*/
public async isCancelled(): Promise<boolean> {
return this.dharma.order.isCancelled(this.data);
}
/**
* Eventually attempts to cancel the loan request.
*
* Note that a loan request can only be canceled by the debtor, and transaction will only
* succeed if the request has yet to be filled and has yet to expire.
*
* @example
* await loanRequest.cancel();
* => "0x000..."
*
* @returns {Promise<string>} the hash of the Ethereum transaction to cancel the loan request
*/
public async cancel(): Promise<string> {
return this.dharma.order.cancelOrderAsync(this.data, {
from: this.data.debtor,
});
}
/**
* Returns the loan request's unique identifier.
*
* @example
* const id = loanRequest.getAgreementId();
*
* @return {string}
*/
public getAgreementId(): string {
return new DebtOrderDataWrapper(this.data).getIssuanceCommitmentHash();
}
/**
* Returns the loan request's underlying data as JSON.
*
* Converting the loan request to JSON allows the resulting data to be written to disk,
* or transmitted over the wire.
*
* @example
* const data = loanRequest.toJSON();
*
* @return {OrderData}
*/
public toJSON(): OrderData {
return {
kernelVersion: this.data.kernelVersion!,
issuanceVersion: this.data.issuanceVersion!,
principalAmount: this.data.principalAmount.toString(),
principalToken: this.data.principalToken!,
debtor: this.data.debtor!,
debtorFee: this.data.debtorFee.toString(),
creditor: this.data.creditor!,
creditorFee: this.data.creditorFee.toString(),
relayer: this.data.relayer!,
relayerFee: this.data.relayerFee.toString(),
underwriter: this.data.underwriter!,
underwriterFee: this.data.underwriterFee.toString(),
underwriterRiskRating: this.data.underwriterRiskRating.toString(),
termsContract: this.data.termsContract!,
termsContractParameters: this.data.termsContractParameters!,
expirationTimestampInSec: this.data.expirationTimestampInSec.toString(),
salt: this.data.salt.toString(),
debtorSignature: this.data.debtorSignature!,
creditorSignature: this.data.creditorSignature!,
underwriterSignature: this.data.underwriterSignature!,
};
}
} | the_stack |
import {DebugElement, Component} from '@angular/core';
import {Location} from '@angular/common';
import {async, ComponentFixture, TestBed, tick, fakeAsync} from '@angular/core/testing';
import {MatCardModule, MatProgressSpinnerModule} from '@angular/material';
import {By} from '@angular/platform-browser';
import {ActivatedRoute, convertToParamMap} from '@angular/router';
import {RouterTestingModule} from '@angular/router/testing';
import {MomentModule} from 'ngx-moment';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {StatusIconModule} from '../common/components/status-icon/status-icon.module';
import {ToolbarModule} from '../common/components/toolbar/toolbar.module';
import {LogViewerModule} from '../common/components/log-viewer/log-viewer.module';
import {BuildStatus} from '../common/constants';
import {expectElementNotToExist, expectElementToExist, getAllElements, getElement} from '../common/test_helpers/element_helper_functions';
import {mockBuild, mockBuildResponse} from '../common/test_helpers/mock_build_data';
import {Build, BuildLogLine} from '../models/build';
import {BuildLogMessageEvent, BuildLogWebsocketService} from '../services/build-log-websocket.service';
import {DataService} from '../services/data.service';
import {BuildComponent} from './build.component';
import {DummyComponent} from '../common/test_helpers/dummy.component';
describe('BuildComponent', () => {
let location: Location;
let component: BuildComponent;
let fixture: ComponentFixture<BuildComponent>;
let fixtureEl: DebugElement;
let buildLogWebsocketService:
jasmine.SpyObj<Partial<BuildLogWebsocketService>>;
let dataService: jasmine.SpyObj<Partial<DataService>>;
let socketSubject: Subject<BuildLogMessageEvent>;
let buildSubject: Subject<Build>;
let buildLogsSubject: Subject<BuildLogLine[]>;
beforeEach(() => {
socketSubject = new Subject<BuildLogMessageEvent>();
buildSubject = new Subject<Build>();
buildLogsSubject = new Subject<BuildLogLine[]>();
buildLogWebsocketService = {
connect: jasmine.createSpy().and.returnValue(socketSubject.asObservable())
};
dataService = {
getBuild:
jasmine.createSpy().and.returnValue(buildSubject.asObservable()),
getBuildLogs:
jasmine.createSpy().and.returnValue(buildLogsSubject.asObservable())
};
TestBed
.configureTestingModule({
declarations: [BuildComponent, DummyComponent],
imports: [
ToolbarModule, StatusIconModule, RouterTestingModule.withRoutes(
[{path: '404', component: DummyComponent} ]
),
MatCardModule, MatProgressSpinnerModule, MomentModule, LogViewerModule
],
providers: [
{
provide: BuildLogWebsocketService,
useValue: buildLogWebsocketService
},
{provide: DataService, useValue: dataService}, {
provide: ActivatedRoute,
useValue: {
paramMap: Observable.of(
convertToParamMap({projectId: '123', buildId: '3'}))
}
}
]
})
.compileComponents();
fixture = TestBed.createComponent(BuildComponent);
fixtureEl = fixture.debugElement;
component = fixture.componentInstance;
location = TestBed.get(Location);
});
describe('Unit tests', () => {
it('should start socket connection with correct project/build IDs', () => {
fixture.detectChanges();
expect(buildLogWebsocketService.connect).toHaveBeenCalledWith('123', 3);
});
it('should get and set Build on init', () => {
fixture.detectChanges();
expect(dataService.getBuild).toHaveBeenCalledWith('123', 3);
buildSubject.next(mockBuild);
expect(component.build).toBe(mockBuild);
});
it('should redirect if API returns an error', fakeAsync(() => {
fixture.detectChanges();
expect(dataService.getBuild).toHaveBeenCalledWith('123', 3);
buildSubject.error({});
tick();
expect(location.path()).toBe('/404');
}));
it('should update logs as they come in', () => {
fixture.detectChanges();
expect(component.logs).toEqual([]);
socketSubject.next(
new MessageEvent('type', {data: '{"log":{"message": "log1"}}'}));
expect(component.logs).toEqual([{message: 'log1'}]);
socketSubject.next(
new MessageEvent('type', {data: '{"log":{"message": "log2"}}'}));
expect(component.logs).toEqual([{message: 'log1'}, {message: 'log2'}]);
});
it('should update breadcrumb urls after loading params', () => {
expect(component.breadcrumbs[1].url).toBeUndefined();
fixture.detectChanges(); // onInit()
expect(component.breadcrumbs[1].url).toBe('/project/123');
});
it('should update breadcrumb labels after loading build', () => {
expect(component.breadcrumbs[1].label).toBeUndefined();
expect(component.breadcrumbs[2].label).toBeUndefined();
fixture.detectChanges(); // onInit()
buildSubject.next(mockBuild);
expect(component.breadcrumbs[1].label).toBe('Project');
expect(component.breadcrumbs[2].label).toBe('Build 3');
});
it('should have toolbar with breadcrumbs', () => {
fixture.detectChanges(); // onInit()
// toolbar exists
expect(getAllElements(fixtureEl, '.fci-crumb').length).toBe(3);
expect(component.breadcrumbs[0].label).toBe('Dashboard');
expect(component.breadcrumbs[0].url).toBe('/');
expect(component.breadcrumbs[1].hint).toBe('Project');
expect(component.breadcrumbs[2].hint).toBe('Build');
});
it('should unsubscribe websocket on destroy', () => {
fixture.detectChanges(); // onInit()
expect(component.websocketSubscription.closed).toBe(false);
fixture.destroy();
expect(component.websocketSubscription.closed).toBe(true);
});
it('should not get build logs if build is incomplete ', () => {
fixture.detectChanges(); // onInit()
spyOn(mockBuild, 'isComplete').and.returnValue(false);
expect(component.websocketSubscription.closed).toBe(false);
buildSubject.next(mockBuild);
buildLogsSubject.next([{message: 'some logs'}]);
expect(component.logs.length).toBe(0);
});
});
describe('shallow tests', () => {
beforeEach(async(() => {
fixture.detectChanges(); // onInit()
fixture.whenStable();
}));
it('should show connecting while no logs is connecting', () => {
const logsEl = getElement(fixtureEl, '.fci-build-logs').nativeElement;
expect(component.logs.length).toBe(0);
expect(logsEl.innerText).toBe('Connecting...');
socketSubject.next(
new MessageEvent('type', {data: '{"log":{"message": "this is a log"}}'}));
fixture.detectChanges();
expect(logsEl.innerText.trim()).toBe('this is a log');
});
describe('header', () => {
let headerEl: DebugElement;
beforeEach(() => {
headerEl = getElement(fixtureEl, '.fci-build-header');
});
it('should show status icon after loading', () => {
expectElementNotToExist(headerEl, 'fci-status-icon');
buildSubject.next(mockBuild);
fixture.detectChanges();
const iconsEl = getAllElements(headerEl, 'fci-status-icon');
expect(iconsEl.length).toBe(1);
expect(iconsEl[0].nativeElement.innerText).toBe('warning');
});
it('should show build number in title after loading', () => {
const titleEl = getElement(headerEl, '.fci-build-title').nativeElement;
expect(titleEl.innerText).toBe('Build');
buildSubject.next(mockBuild);
fixture.detectChanges();
expect(titleEl.innerText).toBe('Build 3');
});
it('should show build description after loading', () => {
expectElementNotToExist(headerEl, '.fci-build-description');
buildSubject.next(mockBuild);
fixture.detectChanges();
const descriptionsEl =
getAllElements(headerEl, '.fci-build-description');
expect(descriptionsEl.length).toBe(1);
expect(descriptionsEl[0].nativeElement.innerText)
.toBe(
'fastlane.ci encountered an error, check fastlane.ci logs for more information');
});
});
describe('build details card', () => {
let detailsEl: DebugElement;
beforeEach(() => {
detailsEl = getElement(fixtureEl, '.fci-build-details');
});
it('should show spinner while loading', () => {
expectElementToExist(detailsEl, '.fci-loading-spinner');
buildSubject.next(mockBuild);
fixture.detectChanges();
expectElementNotToExist(detailsEl, '.fci-loading-spinner');
});
describe('after build loaded', () => {
beforeEach(() => {
buildSubject.next(mockBuild);
fixture.detectChanges();
});
it('should show build trigger', () => {
expect(detailsEl.nativeElement.innerText).toContain('TRIGGER');
expect(detailsEl.nativeElement.innerText).toContain('commit');
});
it('should show build branch', () => {
expect(detailsEl.nativeElement.innerText).toContain('BRANCH');
expect(detailsEl.nativeElement.innerText).toContain('test-branch');
});
it('should show shortened SHA', () => {
expect(detailsEl.nativeElement.innerText).toContain('SHA');
expect(detailsEl.nativeElement.innerText).toContain('5903a0');
});
it('should show start time', () => {
expect(detailsEl.nativeElement.innerText).toContain('STARTED');
// No good time to test the time since it's relative, and always
// changing
});
it('should show duration if build is not pending', () => {
expect(component.build.status).not.toBe(BuildStatus.PENDING);
expect(detailsEl.nativeElement.innerText).toContain('DURATION');
expect(detailsEl.nativeElement.innerText).toContain('2 minutes');
});
it('should not show duration if build is pending', () => {
component.build =
new Build({...mockBuildResponse, status: 'pending'});
expect(component.build.status).toBe(BuildStatus.PENDING);
fixture.detectChanges();
expect(detailsEl.nativeElement.innerText).not.toContain('DURATION');
expect(detailsEl.nativeElement.innerText).not.toContain('2 minutes');
});
});
});
describe('artifacts card', () => {
let cardEl: DebugElement;
beforeEach(() => {
cardEl = getElement(fixtureEl, '.fci-artifacts');
});
it('should show spinner while loading', () => {
expectElementToExist(cardEl, '.fci-loading-spinner');
buildSubject.next(mockBuild);
fixture.detectChanges();
expectElementNotToExist(cardEl, '.fci-loading-spinner');
});
describe('after build loaded', () => {
beforeEach(() => {
buildSubject.next(mockBuild);
fixture.detectChanges();
});
it('should show artifacts', () => {
const artifactEls = getAllElements(cardEl, 'div.fci-artifact');
expect(artifactEls.length).toBe(2);
expect(artifactEls[0].nativeElement.innerText).toBe('fastlane.log');
expect(artifactEls[1].nativeElement.innerText).toBe('hack.exe');
});
});
});
});
}); | the_stack |
import { expect } from 'chai';
import { hot, cold, expectObservable, expectSubscriptions } from '../helpers/marble-testing';
import { publishBehavior, mergeMapTo, tap, mergeMap, refCount, retry, repeat } from 'rxjs/operators';
import { ConnectableObservable, of, Subscription, Observable, pipe } from 'rxjs';
/** @test {publishBehavior} */
describe('publishBehavior operator', () => {
it('should mirror a simple source Observable', () => {
const source = cold('--1-2---3-4--5-|');
const sourceSubs = '^ !';
const published = source.pipe(publishBehavior('0')) as ConnectableObservable<string>;
const expected = '0-1-2---3-4--5-|';
expectObservable(published).toBe(expected);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
published.connect();
});
it('should return a ConnectableObservable-ish', () => {
const source = of(1).pipe(publishBehavior(1)) as ConnectableObservable<number>;
expect(typeof (<any> source)._subscribe === 'function').to.be.true;
expect(typeof (<any> source).getSubject === 'function').to.be.true;
expect(typeof source.connect === 'function').to.be.true;
expect(typeof source.refCount === 'function').to.be.true;
});
it('should only emit default value if connect is not called, despite subscriptions', () => {
const source = cold('--1-2---3-4--5-|');
const sourceSubs: string[] = [];
const published = source.pipe(publishBehavior('0'));
const expected = '0';
expectObservable(published).toBe(expected);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
});
it('should multicast the same values to multiple observers', () => {
const source = cold('-1-2-3----4-|');
const sourceSubs = '^ !';
const published = source.pipe(publishBehavior('0')) as ConnectableObservable<string>;
const subscriber1 = hot('a| ').pipe(mergeMapTo(published));
const expected1 = '01-2-3----4-|';
const subscriber2 = hot(' b| ').pipe(mergeMapTo(published));
const expected2 = ' 23----4-|';
const subscriber3 = hot(' c| ').pipe(mergeMapTo(published));
const expected3 = ' 3-4-|';
expectObservable(subscriber1).toBe(expected1);
expectObservable(subscriber2).toBe(expected2);
expectObservable(subscriber3).toBe(expected3);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
published.connect();
});
it('should multicast an error from the source to multiple observers', () => {
const source = cold('-1-2-3----4-#');
const sourceSubs = '^ !';
const published = source.pipe(publishBehavior('0')) as ConnectableObservable<string>;
const subscriber1 = hot('a| ').pipe(mergeMapTo(published));
const expected1 = '01-2-3----4-#';
const subscriber2 = hot(' b| ').pipe(mergeMapTo(published));
const expected2 = ' 23----4-#';
const subscriber3 = hot(' c| ').pipe(mergeMapTo(published));
const expected3 = ' 3-4-#';
expectObservable(subscriber1).toBe(expected1);
expectObservable(subscriber2).toBe(expected2);
expectObservable(subscriber3).toBe(expected3);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
published.connect();
});
it('should multicast the same values to multiple observers, ' +
'but is unsubscribed explicitly and early', () => {
const source = cold('-1-2-3----4-|');
const sourceSubs = '^ ! ';
const published = source.pipe(publishBehavior('0')) as ConnectableObservable<string>;
const unsub = ' u ';
const subscriber1 = hot('a| ').pipe(mergeMapTo(published));
const expected1 = '01-2-3---- ';
const subscriber2 = hot(' b| ').pipe(mergeMapTo(published));
const expected2 = ' 23---- ';
const subscriber3 = hot(' c| ').pipe(mergeMapTo(published));
const expected3 = ' 3- ';
expectObservable(subscriber1).toBe(expected1);
expectObservable(subscriber2).toBe(expected2);
expectObservable(subscriber3).toBe(expected3);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
// Set up unsubscription action
let connection: Subscription;
expectObservable(hot(unsub).pipe(tap(() => {
connection.unsubscribe();
}))).toBe(unsub);
connection = published.connect();
});
it('should not break unsubscription chains when result is unsubscribed explicitly', () => {
const source = cold('-1-2-3----4-|');
const sourceSubs = '^ ! ';
const published = source.pipe(
mergeMap((x) => of(x)),
publishBehavior('0')
) as ConnectableObservable<string>;
const subscriber1 = hot('a| ').pipe(mergeMapTo(published));
const expected1 = '01-2-3---- ';
const subscriber2 = hot(' b| ').pipe(mergeMapTo(published));
const expected2 = ' 23---- ';
const subscriber3 = hot(' c| ').pipe(mergeMapTo(published));
const expected3 = ' 3- ';
const unsub = ' u ';
expectObservable(subscriber1).toBe(expected1);
expectObservable(subscriber2).toBe(expected2);
expectObservable(subscriber3).toBe(expected3);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
// Set up unsubscription action
let connection: Subscription;
expectObservable(hot(unsub).pipe(tap(() => {
connection.unsubscribe();
}))).toBe(unsub);
connection = published.connect();
});
describe('with refCount()', () => {
it('should connect when first subscriber subscribes', () => {
const source = cold( '-1-2-3----4-|');
const sourceSubs = ' ^ !';
const replayed = source.pipe(
publishBehavior('0'),
refCount()
);
const subscriber1 = hot(' a| ').pipe(mergeMapTo(replayed));
const expected1 = ' 01-2-3----4-|';
const subscriber2 = hot(' b| ').pipe(mergeMapTo(replayed));
const expected2 = ' 23----4-|';
const subscriber3 = hot(' c| ').pipe(mergeMapTo(replayed));
const expected3 = ' 3-4-|';
expectObservable(subscriber1).toBe(expected1);
expectObservable(subscriber2).toBe(expected2);
expectObservable(subscriber3).toBe(expected3);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
});
it('should disconnect when last subscriber unsubscribes', () => {
const source = cold( '-1-2-3----4-|');
const sourceSubs = ' ^ ! ';
const replayed = source.pipe(
publishBehavior('0'),
refCount()
);
const subscriber1 = hot(' a| ').pipe(mergeMapTo(replayed));
const unsub1 = ' ! ';
const expected1 = ' 01-2-3-- ';
const subscriber2 = hot(' b| ').pipe(mergeMapTo(replayed));
const unsub2 = ' ! ';
const expected2 = ' 23---- ';
expectObservable(subscriber1, unsub1).toBe(expected1);
expectObservable(subscriber2, unsub2).toBe(expected2);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
});
it('should NOT be retryable', () => {
const source = cold('-1-2-3----4-#');
const sourceSubs = '^ !';
const published = source.pipe(
publishBehavior('0'),
refCount(),
retry(3)
);
const subscriber1 = hot('a| ').pipe(mergeMapTo(published));
const expected1 = '01-2-3----4-#';
const subscriber2 = hot(' b| ').pipe(mergeMapTo(published));
const expected2 = ' 23----4-#';
const subscriber3 = hot(' c| ').pipe(mergeMapTo(published));
const expected3 = ' 3-4-#';
expectObservable(subscriber1).toBe(expected1);
expectObservable(subscriber2).toBe(expected2);
expectObservable(subscriber3).toBe(expected3);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
});
it('should NOT be repeatable', () => {
const source = cold('-1-2-3----4-|');
const sourceSubs = '^ !';
const published = source.pipe(
publishBehavior('0'),
refCount(),
repeat(3)
);
const subscriber1 = hot('a| ').pipe(mergeMapTo(published));
const expected1 = '01-2-3----4-|';
const subscriber2 = hot(' b| ').pipe(mergeMapTo(published));
const expected2 = ' 23----4-|';
const subscriber3 = hot(' c| ').pipe(mergeMapTo(published));
const expected3 = ' 3-4-|';
expectObservable(subscriber1).toBe(expected1);
expectObservable(subscriber2).toBe(expected2);
expectObservable(subscriber3).toBe(expected3);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
});
});
it('should emit completed when subscribed after completed', (done) => {
const results1: number[] = [];
const results2: number[] = [];
let subscriptions = 0;
const source = new Observable<number>((observer) => {
subscriptions++;
observer.next(1);
observer.next(2);
observer.next(3);
observer.next(4);
observer.complete();
});
const connectable = source.pipe(publishBehavior(0)) as ConnectableObservable<number>;
connectable.subscribe(function (x) {
results1.push(x);
});
expect(results1).to.deep.equal([0]);
expect(results2).to.deep.equal([]);
connectable.connect();
expect(results1).to.deep.equal([0, 1, 2, 3, 4]);
expect(results2).to.deep.equal([]);
expect(subscriptions).to.equal(1);
connectable.subscribe(function (x) {
results2.push(x);
}, (x) => {
done(new Error('should not be called'));
}, () => {
expect(results2).to.deep.equal([]);
done();
});
});
it('should multicast an empty source', () => {
const source = cold('|');
const sourceSubs = '(^!)';
const published = source.pipe(publishBehavior('0')) as ConnectableObservable<string>;
const expected = '(0|)';
expectObservable(published).toBe(expected);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
published.connect();
});
it('should multicast a never source', () => {
const source = cold('-');
const sourceSubs = '^';
const published = source.pipe(publishBehavior('0')) as ConnectableObservable<string>;
const expected = '0';
expectObservable(published).toBe(expected);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
published.connect();
});
it('should multicast a throw source', () => {
const source = cold('#');
const sourceSubs = '(^!)';
const published = source.pipe(publishBehavior('0')) as ConnectableObservable<string>;
const expected = '(0#)';
expectObservable(published).toBe(expected);
expectSubscriptions(source.subscriptions).toBe(sourceSubs);
published.connect();
});
it('should multicast one observable to multiple observers', (done) => {
const results1: number[] = [];
const results2: number[] = [];
let subscriptions = 0;
const source = new Observable<number>((observer) => {
subscriptions++;
observer.next(1);
observer.next(2);
observer.next(3);
observer.next(4);
});
const connectable = source.pipe(publishBehavior(0)) as ConnectableObservable<number>;
connectable.subscribe((x) => {
results1.push(x);
});
expect(results1).to.deep.equal([0]);
connectable.connect();
expect(results2).to.deep.equal([]);
connectable.subscribe((x) => {
results2.push(x);
});
expect(results1).to.deep.equal([0, 1, 2, 3, 4]);
expect(results2).to.deep.equal([4]);
expect(subscriptions).to.equal(1);
done();
});
it('should follow the RxJS 4 behavior and emit nothing to observer after completed', (done) => {
const results: number[] = [];
const source = new Observable<number>((observer) => {
observer.next(1);
observer.next(2);
observer.next(3);
observer.next(4);
observer.complete();
});
const connectable = source.pipe(publishBehavior(0)) as ConnectableObservable<number>;
connectable.connect();
connectable.subscribe((x) => {
results.push(x);
});
expect(results).to.deep.equal([]);
done();
});
it('should be referentially-transparent', () => {
const source1 = cold('-1-2-3-4-5-|');
const source1Subs = '^ !';
const expected1 = 'x1-2-3-4-5-|';
const source2 = cold('-6-7-8-9-0-|');
const source2Subs = '^ !';
const expected2 = 'x6-7-8-9-0-|';
// Calls to the _operator_ must be referentially-transparent.
const partialPipeLine = pipe(
publishBehavior('x')
);
// The non-referentially-transparent publishing occurs within the _operator function_
// returned by the _operator_ and that happens when the complete pipeline is composed.
const published1 = source1.pipe(partialPipeLine) as ConnectableObservable<any>;
const published2 = source2.pipe(partialPipeLine) as ConnectableObservable<any>;
expectObservable(published1).toBe(expected1);
expectSubscriptions(source1.subscriptions).toBe(source1Subs);
expectObservable(published2).toBe(expected2);
expectSubscriptions(source2.subscriptions).toBe(source2Subs);
published1.connect();
published2.connect();
});
}); | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type PartnerShowsInfiniteScrollGridQueryVariables = {
id: string;
cursor?: string | null | undefined;
count: number;
};
export type PartnerShowsInfiniteScrollGridQueryResponse = {
readonly partner: {
readonly " $fragmentRefs": FragmentRefs<"PartnerShows_partner">;
} | null;
};
export type PartnerShowsInfiniteScrollGridQuery = {
readonly response: PartnerShowsInfiniteScrollGridQueryResponse;
readonly variables: PartnerShowsInfiniteScrollGridQueryVariables;
};
/*
query PartnerShowsInfiniteScrollGridQuery(
$id: String!
$cursor: String
$count: Int!
) {
partner(id: $id) {
...PartnerShows_partner_1G22uz
id
}
}
fragment PartnerShowRailItem_show on Show {
internalID
slug
name
exhibitionPeriod(format: SHORT)
endAt
coverImage {
url
}
images {
url
}
}
fragment PartnerShowsRail_partner on Partner {
internalID
currentAndUpcomingShows: showsConnection(status: CURRENT, sort: END_AT_ASC, first: 6) {
pageInfo {
hasNextPage
startCursor
endCursor
}
edges {
node {
isDisplayable
id
internalID
slug
name
exhibitionPeriod(format: SHORT)
endAt
images {
url
}
partner {
__typename
... on Partner {
name
}
... on Node {
__isNode: __typename
id
}
... on ExternalPartner {
id
}
}
...PartnerShowRailItem_show
__typename
}
cursor
}
}
}
fragment PartnerShows_partner_1G22uz on Partner {
slug
internalID
recentShows: showsConnection(status: CURRENT, first: 10) {
edges {
node {
id
isDisplayable
}
}
}
pastShows: showsConnection(status: CLOSED, sort: END_AT_DESC, first: $count, after: $cursor) {
pageInfo {
hasNextPage
startCursor
endCursor
}
edges {
node {
isDisplayable
id
name
slug
exhibitionPeriod(format: SHORT)
coverImage {
url
aspectRatio
}
href
__typename
}
cursor
}
}
...PartnerShowsRail_partner
}
*/
const node: ConcreteRequest = (function(){
var v0 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "count"
},
v1 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "cursor"
},
v2 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "id"
},
v3 = [
{
"kind": "Variable",
"name": "id",
"variableName": "id"
}
],
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
v6 = {
"kind": "Literal",
"name": "status",
"value": "CURRENT"
},
v7 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v8 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isDisplayable",
"storageKey": null
},
v9 = [
{
"kind": "Variable",
"name": "after",
"variableName": "cursor"
},
{
"kind": "Variable",
"name": "first",
"variableName": "count"
},
{
"kind": "Literal",
"name": "sort",
"value": "END_AT_DESC"
},
{
"kind": "Literal",
"name": "status",
"value": "CLOSED"
}
],
v10 = {
"alias": null,
"args": null,
"concreteType": "PageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasNextPage",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "startCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endCursor",
"storageKey": null
}
],
"storageKey": null
},
v11 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v12 = {
"alias": null,
"args": [
{
"kind": "Literal",
"name": "format",
"value": "SHORT"
}
],
"kind": "ScalarField",
"name": "exhibitionPeriod",
"storageKey": "exhibitionPeriod(format:\"SHORT\")"
},
v13 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "url",
"storageKey": null
},
v14 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v15 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
},
v16 = [
"status",
"sort"
],
v17 = [
{
"kind": "Literal",
"name": "first",
"value": 6
},
{
"kind": "Literal",
"name": "sort",
"value": "END_AT_ASC"
},
(v6/*: any*/)
],
v18 = [
(v13/*: any*/)
],
v19 = [
(v7/*: any*/)
];
return {
"fragment": {
"argumentDefinitions": [
(v0/*: any*/),
(v1/*: any*/),
(v2/*: any*/)
],
"kind": "Fragment",
"metadata": null,
"name": "PartnerShowsInfiniteScrollGridQuery",
"selections": [
{
"alias": null,
"args": (v3/*: any*/),
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
{
"args": [
{
"kind": "Variable",
"name": "count",
"variableName": "count"
},
{
"kind": "Variable",
"name": "cursor",
"variableName": "cursor"
}
],
"kind": "FragmentSpread",
"name": "PartnerShows_partner"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [
(v2/*: any*/),
(v1/*: any*/),
(v0/*: any*/)
],
"kind": "Operation",
"name": "PartnerShowsInfiniteScrollGridQuery",
"selections": [
{
"alias": null,
"args": (v3/*: any*/),
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
(v4/*: any*/),
(v5/*: any*/),
{
"alias": "recentShows",
"args": [
{
"kind": "Literal",
"name": "first",
"value": 10
},
(v6/*: any*/)
],
"concreteType": "ShowConnection",
"kind": "LinkedField",
"name": "showsConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ShowEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Show",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v7/*: any*/),
(v8/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "showsConnection(first:10,status:\"CURRENT\")"
},
{
"alias": "pastShows",
"args": (v9/*: any*/),
"concreteType": "ShowConnection",
"kind": "LinkedField",
"name": "showsConnection",
"plural": false,
"selections": [
(v10/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "ShowEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Show",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v8/*: any*/),
(v7/*: any*/),
(v11/*: any*/),
(v4/*: any*/),
(v12/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "coverImage",
"plural": false,
"selections": [
(v13/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "aspectRatio",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
(v14/*: any*/)
],
"storageKey": null
},
(v15/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": "pastShows",
"args": (v9/*: any*/),
"filters": (v16/*: any*/),
"handle": "connection",
"key": "Partner_pastShows",
"kind": "LinkedHandle",
"name": "showsConnection"
},
{
"alias": "currentAndUpcomingShows",
"args": (v17/*: any*/),
"concreteType": "ShowConnection",
"kind": "LinkedField",
"name": "showsConnection",
"plural": false,
"selections": [
(v10/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "ShowEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Show",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v8/*: any*/),
(v7/*: any*/),
(v5/*: any*/),
(v4/*: any*/),
(v11/*: any*/),
(v12/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endAt",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "images",
"plural": true,
"selections": (v18/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
(v14/*: any*/),
{
"kind": "InlineFragment",
"selections": [
(v11/*: any*/)
],
"type": "Partner",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": (v19/*: any*/),
"type": "Node",
"abstractKey": "__isNode"
},
{
"kind": "InlineFragment",
"selections": (v19/*: any*/),
"type": "ExternalPartner",
"abstractKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "coverImage",
"plural": false,
"selections": (v18/*: any*/),
"storageKey": null
},
(v14/*: any*/)
],
"storageKey": null
},
(v15/*: any*/)
],
"storageKey": null
}
],
"storageKey": "showsConnection(first:6,sort:\"END_AT_ASC\",status:\"CURRENT\")"
},
{
"alias": "currentAndUpcomingShows",
"args": (v17/*: any*/),
"filters": (v16/*: any*/),
"handle": "connection",
"key": "Partner_currentAndUpcomingShows",
"kind": "LinkedHandle",
"name": "showsConnection"
},
(v7/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "4d4d134ac1b87227a626f9b30ac03904",
"metadata": {},
"name": "PartnerShowsInfiniteScrollGridQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = '5693725793e322d2ab9fa67980502e06';
export default node; | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://spanner.googleapis.com/$discovery/rest?version=v1
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Cloud Spanner API v1 */
function load(name: "spanner", version: "v1"): PromiseLike<void>;
function load(name: "spanner", version: "v1", callback: () => any): void;
const projects: spanner.ProjectsResource;
namespace spanner {
interface BeginTransactionRequest {
/** Required. Options for the new transaction. */
options?: TransactionOptions;
}
interface Binding {
/**
* Specifies the identities requesting access for a Cloud Platform resource.
* `members` can have the following values:
*
* * `allUsers`: A special identifier that represents anyone who is
* on the internet; with or without a Google account.
*
* * `allAuthenticatedUsers`: A special identifier that represents anyone
* who is authenticated with a Google account or a service account.
*
* * `user:{emailid}`: An email address that represents a specific Google
* account. For example, `alice@gmail.com` or `joe@example.com`.
*
*
* * `serviceAccount:{emailid}`: An email address that represents a service
* account. For example, `my-other-app@appspot.gserviceaccount.com`.
*
* * `group:{emailid}`: An email address that represents a Google group.
* For example, `admins@example.com`.
*
*
* * `domain:{domain}`: A Google Apps domain name that represents all the
* users of that domain. For example, `google.com` or `example.com`.
*/
members?: string[];
/**
* Role that is assigned to `members`.
* For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
* Required
*/
role?: string;
}
interface ChildLink {
/** The node to which the link points. */
childIndex?: number;
/**
* The type of the link. For example, in Hash Joins this could be used to
* distinguish between the build child and the probe child, or in the case
* of the child being an output variable, to represent the tag associated
* with the output variable.
*/
type?: string;
/**
* Only present if the child node is SCALAR and corresponds
* to an output variable of the parent node. The field carries the name of
* the output variable.
* For example, a `TableScan` operator that reads rows from a table will
* have child links to the `SCALAR` nodes representing the output variables
* created for each column that is read by the operator. The corresponding
* `variable` fields will be set to the variable names assigned to the
* columns.
*/
variable?: string;
}
interface CommitRequest {
/**
* The mutations to be executed when this transaction commits. All
* mutations are applied atomically, in the order they appear in
* this list.
*/
mutations?: Mutation[];
/**
* Execute mutations in a temporary transaction. Note that unlike
* commit of a previously-started transaction, commit with a
* temporary transaction is non-idempotent. That is, if the
* `CommitRequest` is sent to Cloud Spanner more than once (for
* instance, due to retries in the application, or in the
* transport library), it is possible that the mutations are
* executed more than once. If this is undesirable, use
* BeginTransaction and
* Commit instead.
*/
singleUseTransaction?: TransactionOptions;
/** Commit a previously-started transaction. */
transactionId?: string;
}
interface CommitResponse {
/** The Cloud Spanner timestamp at which the transaction committed. */
commitTimestamp?: string;
}
interface CreateDatabaseMetadata {
/** The database being created. */
database?: string;
}
interface CreateDatabaseRequest {
/**
* Required. A `CREATE DATABASE` statement, which specifies the ID of the
* new database. The database ID must conform to the regular expression
* `a-z*[a-z0-9]` and be between 2 and 30 characters in length.
* If the database ID is a reserved word or if it contains a hyphen, the
* database ID must be enclosed in backticks (`` ` ``).
*/
createStatement?: string;
/**
* An optional list of DDL statements to run inside the newly created
* database. Statements can create tables, indexes, etc. These
* statements execute atomically with the creation of the database:
* if there is an error in any statement, the database is not created.
*/
extraStatements?: string[];
}
interface CreateInstanceMetadata {
/**
* The time at which this operation was cancelled. If set, this operation is
* in the process of undoing itself (which is guaranteed to succeed) and
* cannot be cancelled again.
*/
cancelTime?: string;
/** The time at which this operation failed or was completed successfully. */
endTime?: string;
/** The instance being created. */
instance?: Instance;
/**
* The time at which the
* CreateInstance request was
* received.
*/
startTime?: string;
}
interface CreateInstanceRequest {
/**
* Required. The instance to create. The name may be omitted, but if
* specified must be `<parent>/instances/<instance_id>`.
*/
instance?: Instance;
/**
* Required. The ID of the instance to create. Valid identifiers are of the
* form `a-z*[a-z0-9]` and must be between 6 and 30 characters in
* length.
*/
instanceId?: string;
}
interface CreateSessionRequest {
/** The session to create. */
session?: Session;
}
interface Database {
/**
* Required. The name of the database. Values are of the form
* `projects/<project>/instances/<instance>/databases/<database>`,
* where `<database>` is as specified in the `CREATE DATABASE`
* statement. This name can be passed to other API methods to
* identify the database.
*/
name?: string;
/** Output only. The current database state. */
state?: string;
}
interface Delete {
/** Required. The primary keys of the rows within table to delete. */
keySet?: KeySet;
/** Required. The table whose rows will be deleted. */
table?: string;
}
interface ExecuteSqlRequest {
/**
* It is not always possible for Cloud Spanner to infer the right SQL type
* from a JSON value. For example, values of type `BYTES` and values
* of type `STRING` both appear in params as JSON strings.
*
* In these cases, `param_types` can be used to specify the exact
* SQL type for some or all of the SQL query parameters. See the
* definition of Type for more information
* about SQL types.
*/
paramTypes?: Record<string, Type>;
/**
* The SQL query string can contain parameter placeholders. A parameter
* placeholder consists of `'@'` followed by the parameter
* name. Parameter names consist of any combination of letters,
* numbers, and underscores.
*
* Parameters can appear anywhere that a literal value is expected. The same
* parameter name can be used more than once, for example:
* `"WHERE id > @msg_id AND id < @msg_id + 100"`
*
* It is an error to execute an SQL query with unbound parameters.
*
* Parameter values are specified using `params`, which is a JSON
* object whose keys are parameter names, and whose values are the
* corresponding parameter values.
*/
params?: Record<string, any>;
/**
* Used to control the amount of debugging information returned in
* ResultSetStats.
*/
queryMode?: string;
/**
* If this request is resuming a previously interrupted SQL query
* execution, `resume_token` should be copied from the last
* PartialResultSet yielded before the interruption. Doing this
* enables the new SQL query execution to resume where the last one left
* off. The rest of the request parameters must exactly match the
* request that yielded this token.
*/
resumeToken?: string;
/** Required. The SQL query string. */
sql?: string;
/**
* The transaction to use. If none is provided, the default is a
* temporary read-only transaction with strong concurrency.
*/
transaction?: TransactionSelector;
}
interface Field {
/**
* The name of the field. For reads, this is the column name. For
* SQL queries, it is the column alias (e.g., `"Word"` in the
* query `"SELECT 'hello' AS Word"`), or the column name (e.g.,
* `"ColName"` in the query `"SELECT ColName FROM Table"`). Some
* columns might have an empty name (e.g., !"SELECT
* UPPER(ColName)"`). Note that a query result can contain
* multiple fields with the same name.
*/
name?: string;
/** The type of the field. */
type?: Type;
}
interface GetDatabaseDdlResponse {
/**
* A list of formatted DDL statements defining the schema of the database
* specified in the request.
*/
statements?: string[];
}
interface Instance {
/**
* Required. The name of the instance's configuration. Values are of the form
* `projects/<project>/instanceConfigs/<configuration>`. See
* also InstanceConfig and
* ListInstanceConfigs.
*/
config?: string;
/**
* Required. The descriptive name for this instance as it appears in UIs.
* Must be unique per project and between 4 and 30 characters in length.
*/
displayName?: string;
/**
* Cloud Labels are a flexible and lightweight mechanism for organizing cloud
* resources into groups that reflect a customer's organizational needs and
* deployment strategies. Cloud Labels can be used to filter collections of
* resources. They can be used to control how resource metrics are aggregated.
* And they can be used as arguments to policy management rules (e.g. route,
* firewall, load balancing, etc.).
*
* * Label keys must be between 1 and 63 characters long and must conform to
* the following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`.
* * Label values must be between 0 and 63 characters long and must conform
* to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`.
* * No more than 64 labels can be associated with a given resource.
*
* See https://goo.gl/xmQnxf for more information on and examples of labels.
*
* If you plan to use labels in your own code, please note that additional
* characters may be allowed in the future. And so you are advised to use an
* internal label representation, such as JSON, which doesn't rely upon
* specific characters being disallowed. For example, representing labels
* as the string: name + "_" + value would prove problematic if we were to
* allow "_" in a future release.
*/
labels?: Record<string, string>;
/**
* Required. A unique identifier for the instance, which cannot be changed
* after the instance is created. Values are of the form
* `projects/<project>/instances/a-z*[a-z0-9]`. The final
* segment of the name must be between 6 and 30 characters in length.
*/
name?: string;
/**
* Required. The number of nodes allocated to this instance. This may be zero
* in API responses for instances that are not yet in state `READY`.
*
* Each Spanner node can provide up to 10,000 QPS of reads or 2000 QPS of
* writes (writing single rows at 1KB data per row), and 2 TiB storage.
*
* For optimal performance, we recommend provisioning enough nodes to keep
* overall CPU utilization under 75%.
*
* A minimum of 3 nodes is recommended for production environments. This
* minimum is required for SLAs to apply to your instance.
*
* Note that Cloud Spanner performance is highly dependent on workload, schema
* design, and dataset characteristics. The performance numbers above are
* estimates, and assume [best practices](https://cloud.google.com/spanner/docs/bulk-loading)
* are followed.
*/
nodeCount?: number;
/**
* Output only. The current instance state. For
* CreateInstance, the state must be
* either omitted or set to `CREATING`. For
* UpdateInstance, the state must be
* either omitted or set to `READY`.
*/
state?: string;
}
interface InstanceConfig {
/** The name of this instance configuration as it appears in UIs. */
displayName?: string;
/**
* A unique identifier for the instance configuration. Values
* are of the form
* `projects/<project>/instanceConfigs/a-z*`
*/
name?: string;
}
interface KeyRange {
/**
* If the end is closed, then the range includes all rows whose
* first `len(end_closed)` key columns exactly match `end_closed`.
*/
endClosed?: any[];
/**
* If the end is open, then the range excludes rows whose first
* `len(end_open)` key columns exactly match `end_open`.
*/
endOpen?: any[];
/**
* If the start is closed, then the range includes all rows whose
* first `len(start_closed)` key columns exactly match `start_closed`.
*/
startClosed?: any[];
/**
* If the start is open, then the range excludes rows whose first
* `len(start_open)` key columns exactly match `start_open`.
*/
startOpen?: any[];
}
interface KeySet {
/**
* For convenience `all` can be set to `true` to indicate that this
* `KeySet` matches all keys in the table or index. Note that any keys
* specified in `keys` or `ranges` are only yielded once.
*/
all?: boolean;
/**
* A list of specific keys. Entries in `keys` should have exactly as
* many elements as there are columns in the primary or index key
* with which this `KeySet` is used. Individual key values are
* encoded as described here.
*/
keys?: any[][];
/**
* A list of key ranges. See KeyRange for more information about
* key range specifications.
*/
ranges?: KeyRange[];
}
interface ListDatabasesResponse {
/** Databases that matched the request. */
databases?: Database[];
/**
* `next_page_token` can be sent in a subsequent
* ListDatabases call to fetch more
* of the matching databases.
*/
nextPageToken?: string;
}
interface ListInstanceConfigsResponse {
/** The list of requested instance configurations. */
instanceConfigs?: InstanceConfig[];
/**
* `next_page_token` can be sent in a subsequent
* ListInstanceConfigs call to
* fetch more of the matching instance configurations.
*/
nextPageToken?: string;
}
interface ListInstancesResponse {
/** The list of requested instances. */
instances?: Instance[];
/**
* `next_page_token` can be sent in a subsequent
* ListInstances call to fetch more
* of the matching instances.
*/
nextPageToken?: string;
}
interface ListOperationsResponse {
/** The standard List next-page token. */
nextPageToken?: string;
/** A list of operations that matches the specified filter in the request. */
operations?: Operation[];
}
interface ListSessionsResponse {
/**
* `next_page_token` can be sent in a subsequent
* ListSessions call to fetch more of the matching
* sessions.
*/
nextPageToken?: string;
/** The list of requested sessions. */
sessions?: Session[];
}
interface Mutation {
/**
* Delete rows from a table. Succeeds whether or not the named
* rows were present.
*/
delete?: Delete;
/**
* Insert new rows in a table. If any of the rows already exist,
* the write or transaction fails with error `ALREADY_EXISTS`.
*/
insert?: Write;
/**
* Like insert, except that if the row already exists, then
* its column values are overwritten with the ones provided. Any
* column values not explicitly written are preserved.
*/
insertOrUpdate?: Write;
/**
* Like insert, except that if the row already exists, it is
* deleted, and the column values provided are inserted
* instead. Unlike insert_or_update, this means any values not
* explicitly written become `NULL`.
*/
replace?: Write;
/**
* Update existing rows in a table. If any of the rows does not
* already exist, the transaction fails with error `NOT_FOUND`.
*/
update?: Write;
}
interface Operation {
/**
* If the value is `false`, it means the operation is still in progress.
* If `true`, the operation is completed, and either `error` or `response` is
* available.
*/
done?: boolean;
/** The error result of the operation in case of failure or cancellation. */
error?: Status;
/**
* Service-specific metadata associated with the operation. It typically
* contains progress information and common metadata such as create time.
* Some services might not provide such metadata. Any method that returns a
* long-running operation should document the metadata type, if any.
*/
metadata?: Record<string, any>;
/**
* The server-assigned name, which is only unique within the same service that
* originally returns it. If you use the default HTTP mapping, the
* `name` should have the format of `operations/some/unique/name`.
*/
name?: string;
/**
* The normal response of the operation in case of success. If the original
* method returns no data on success, such as `Delete`, the response is
* `google.protobuf.Empty`. If the original method is standard
* `Get`/`Create`/`Update`, the response should be the resource. For other
* methods, the response should have the type `XxxResponse`, where `Xxx`
* is the original method name. For example, if the original method name
* is `TakeSnapshot()`, the inferred response type is
* `TakeSnapshotResponse`.
*/
response?: Record<string, any>;
}
interface PartialResultSet {
/**
* If true, then the final value in values is chunked, and must
* be combined with more values from subsequent `PartialResultSet`s
* to obtain a complete field value.
*/
chunkedValue?: boolean;
/**
* Metadata about the result set, such as row type information.
* Only present in the first response.
*/
metadata?: ResultSetMetadata;
/**
* Streaming calls might be interrupted for a variety of reasons, such
* as TCP connection loss. If this occurs, the stream of results can
* be resumed by re-sending the original request and including
* `resume_token`. Note that executing any other transaction in the
* same session invalidates the token.
*/
resumeToken?: string;
/**
* Query plan and execution statistics for the query that produced this
* streaming result set. These can be requested by setting
* ExecuteSqlRequest.query_mode and are sent
* only once with the last response in the stream.
*/
stats?: ResultSetStats;
/**
* A streamed result set consists of a stream of values, which might
* be split into many `PartialResultSet` messages to accommodate
* large rows and/or large values. Every N complete values defines a
* row, where N is equal to the number of entries in
* metadata.row_type.fields.
*
* Most values are encoded based on type as described
* here.
*
* It is possible that the last value in values is "chunked",
* meaning that the rest of the value is sent in subsequent
* `PartialResultSet`(s). This is denoted by the chunked_value
* field. Two or more chunked values can be merged to form a
* complete value as follows:
*
* * `bool/number/null`: cannot be chunked
* * `string`: concatenate the strings
* * `list`: concatenate the lists. If the last element in a list is a
* `string`, `list`, or `object`, merge it with the first element in
* the next list by applying these rules recursively.
* * `object`: concatenate the (field name, field value) pairs. If a
* field name is duplicated, then apply these rules recursively
* to merge the field values.
*
* Some examples of merging:
*
* # Strings are concatenated.
* "foo", "bar" => "foobar"
*
* # Lists of non-strings are concatenated.
* [2, 3], [4] => [2, 3, 4]
*
* # Lists are concatenated, but the last and first elements are merged
* # because they are strings.
* ["a", "b"], ["c", "d"] => ["a", "bc", "d"]
*
* # Lists are concatenated, but the last and first elements are merged
* # because they are lists. Recursively, the last and first elements
* # of the inner lists are merged because they are strings.
* ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"]
*
* # Non-overlapping object fields are combined.
* {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"}
*
* # Overlapping object fields are merged.
* {"a": "1"}, {"a": "2"} => {"a": "12"}
*
* # Examples of merging objects containing lists of strings.
* {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]}
*
* For a more complete example, suppose a streaming SQL query is
* yielding a result set whose rows contain a single string
* field. The following `PartialResultSet`s might be yielded:
*
* {
* "metadata": { ... }
* "values": ["Hello", "W"]
* "chunked_value": true
* "resume_token": "Af65..."
* }
* {
* "values": ["orl"]
* "chunked_value": true
* "resume_token": "Bqp2..."
* }
* {
* "values": ["d"]
* "resume_token": "Zx1B..."
* }
*
* This sequence of `PartialResultSet`s encodes two rows, one
* containing the field value `"Hello"`, and a second containing the
* field value `"World" = "W" + "orl" + "d"`.
*/
values?: any[];
}
interface PlanNode {
/** List of child node `index`es and their relationship to this parent. */
childLinks?: ChildLink[];
/** The display name for the node. */
displayName?: string;
/**
* The execution statistics associated with the node, contained in a group of
* key-value pairs. Only present if the plan was returned as a result of a
* profile query. For example, number of executions, number of rows/time per
* execution etc.
*/
executionStats?: Record<string, any>;
/** The `PlanNode`'s index in node list. */
index?: number;
/**
* Used to determine the type of node. May be needed for visualizing
* different kinds of nodes differently. For example, If the node is a
* SCALAR node, it will have a condensed representation
* which can be used to directly embed a description of the node in its
* parent.
*/
kind?: string;
/**
* Attributes relevant to the node contained in a group of key-value pairs.
* For example, a Parameter Reference node could have the following
* information in its metadata:
*
* {
* "parameter_reference": "param1",
* "parameter_type": "array"
* }
*/
metadata?: Record<string, any>;
/** Condensed representation for SCALAR nodes. */
shortRepresentation?: ShortRepresentation;
}
interface Policy {
/**
* Associates a list of `members` to a `role`.
* `bindings` with no members will result in an error.
*/
bindings?: Binding[];
/**
* `etag` is used for optimistic concurrency control as a way to help
* prevent simultaneous updates of a policy from overwriting each other.
* It is strongly suggested that systems make use of the `etag` in the
* read-modify-write cycle to perform policy updates in order to avoid race
* conditions: An `etag` is returned in the response to `getIamPolicy`, and
* systems are expected to put that etag in the request to `setIamPolicy` to
* ensure that their change will be applied to the same version of the policy.
*
* If no `etag` is provided in the call to `setIamPolicy`, then the existing
* policy is overwritten blindly.
*/
etag?: string;
/** Version of the `Policy`. The default version is 0. */
version?: number;
}
interface QueryPlan {
/**
* The nodes in the query plan. Plan nodes are returned in pre-order starting
* with the plan root. Each PlanNode's `id` corresponds to its index in
* `plan_nodes`.
*/
planNodes?: PlanNode[];
}
interface ReadOnly {
/**
* Executes all reads at a timestamp that is `exact_staleness`
* old. The timestamp is chosen soon after the read is started.
*
* Guarantees that all writes that have committed more than the
* specified number of seconds ago are visible. Because Cloud Spanner
* chooses the exact timestamp, this mode works even if the client's
* local clock is substantially skewed from Cloud Spanner commit
* timestamps.
*
* Useful for reading at nearby replicas without the distributed
* timestamp negotiation overhead of `max_staleness`.
*/
exactStaleness?: string;
/**
* Read data at a timestamp >= `NOW - max_staleness`
* seconds. Guarantees that all writes that have committed more
* than the specified number of seconds ago are visible. Because
* Cloud Spanner chooses the exact timestamp, this mode works even if
* the client's local clock is substantially skewed from Cloud Spanner
* commit timestamps.
*
* Useful for reading the freshest data available at a nearby
* replica, while bounding the possible staleness if the local
* replica has fallen behind.
*
* Note that this option can only be used in single-use
* transactions.
*/
maxStaleness?: string;
/**
* Executes all reads at a timestamp >= `min_read_timestamp`.
*
* This is useful for requesting fresher data than some previous
* read, or data that is fresh enough to observe the effects of some
* previously committed transaction whose timestamp is known.
*
* Note that this option can only be used in single-use transactions.
*/
minReadTimestamp?: string;
/**
* Executes all reads at the given timestamp. Unlike other modes,
* reads at a specific timestamp are repeatable; the same read at
* the same timestamp always returns the same data. If the
* timestamp is in the future, the read will block until the
* specified timestamp, modulo the read's deadline.
*
* Useful for large scale consistent reads such as mapreduces, or
* for coordinating many reads against a consistent snapshot of the
* data.
*/
readTimestamp?: string;
/**
* If true, the Cloud Spanner-selected read timestamp is included in
* the Transaction message that describes the transaction.
*/
returnReadTimestamp?: boolean;
/**
* Read at a timestamp where all previously committed transactions
* are visible.
*/
strong?: boolean;
}
interface ReadRequest {
/**
* The columns of table to be returned for each row matching
* this request.
*/
columns?: string[];
/**
* If non-empty, the name of an index on table. This index is
* used instead of the table primary key when interpreting key_set
* and sorting result rows. See key_set for further information.
*/
index?: string;
/**
* Required. `key_set` identifies the rows to be yielded. `key_set` names the
* primary keys of the rows in table to be yielded, unless index
* is present. If index is present, then key_set instead names
* index keys in index.
*
* Rows are yielded in table primary key order (if index is empty)
* or index key order (if index is non-empty).
*
* It is not an error for the `key_set` to name rows that do not
* exist in the database. Read yields nothing for nonexistent rows.
*/
keySet?: KeySet;
/**
* If greater than zero, only the first `limit` rows are yielded. If `limit`
* is zero, the default is no limit.
* A limit cannot be specified if partition_token is set.
*/
limit?: string;
/**
* If this request is resuming a previously interrupted read,
* `resume_token` should be copied from the last
* PartialResultSet yielded before the interruption. Doing this
* enables the new read to resume where the last read left off. The
* rest of the request parameters must exactly match the request
* that yielded this token.
*/
resumeToken?: string;
/** Required. The name of the table in the database to be read. */
table?: string;
/**
* The transaction to use. If none is provided, the default is a
* temporary read-only transaction with strong concurrency.
*/
transaction?: TransactionSelector;
}
interface ResultSet {
/** Metadata about the result set, such as row type information. */
metadata?: ResultSetMetadata;
/**
* Each element in `rows` is a row whose format is defined by
* metadata.row_type. The ith element
* in each row matches the ith field in
* metadata.row_type. Elements are
* encoded based on type as described
* here.
*/
rows?: any[][];
/**
* Query plan and execution statistics for the query that produced this
* result set. These can be requested by setting
* ExecuteSqlRequest.query_mode.
*/
stats?: ResultSetStats;
}
interface ResultSetMetadata {
/**
* Indicates the field names and types for the rows in the result
* set. For example, a SQL query like `"SELECT UserId, UserName FROM
* Users"` could return a `row_type` value like:
*
* "fields": [
* { "name": "UserId", "type": { "code": "INT64" } },
* { "name": "UserName", "type": { "code": "STRING" } },
* ]
*/
rowType?: StructType;
/**
* If the read or SQL query began a transaction as a side-effect, the
* information about the new transaction is yielded here.
*/
transaction?: Transaction;
}
interface ResultSetStats {
/** QueryPlan for the query associated with this result. */
queryPlan?: QueryPlan;
/**
* Aggregated statistics from the execution of the query. Only present when
* the query is profiled. For example, a query could return the statistics as
* follows:
*
* {
* "rows_returned": "3",
* "elapsed_time": "1.22 secs",
* "cpu_time": "1.19 secs"
* }
*/
queryStats?: Record<string, any>;
}
interface RollbackRequest {
/** Required. The transaction to roll back. */
transactionId?: string;
}
interface Session {
/**
* Output only. The approximate timestamp when the session is last used. It is
* typically earlier than the actual last use time.
*/
approximateLastUseTime?: string;
/** Output only. The timestamp when the session is created. */
createTime?: string;
/**
* The labels for the session.
*
* * Label keys must be between 1 and 63 characters long and must conform to
* the following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`.
* * Label values must be between 0 and 63 characters long and must conform
* to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`.
* * No more than 20 labels can be associated with a given session.
*/
labels?: Record<string, string>;
/** The name of the session. */
name?: string;
}
interface SetIamPolicyRequest {
/**
* REQUIRED: The complete policy to be applied to the `resource`. The size of
* the policy is limited to a few 10s of KB. An empty policy is a
* valid policy but certain Cloud Platform services (such as Projects)
* might reject them.
*/
policy?: Policy;
}
interface ShortRepresentation {
/** A string representation of the expression subtree rooted at this node. */
description?: string;
/**
* A mapping of (subquery variable name) -> (subquery node id) for cases
* where the `description` string of this node references a `SCALAR`
* subquery contained in the expression subtree rooted at this node. The
* referenced `SCALAR` subquery may not necessarily be a direct child of
* this node.
*/
subqueries?: Record<string, number>;
}
interface Status {
/** The status code, which should be an enum value of google.rpc.Code. */
code?: number;
/**
* A list of messages that carry the error details. There is a common set of
* message types for APIs to use.
*/
details?: Array<Record<string, any>>;
/**
* A developer-facing error message, which should be in English. Any
* user-facing error message should be localized and sent in the
* google.rpc.Status.details field, or localized by the client.
*/
message?: string;
}
interface StructType {
/**
* The list of fields that make up this struct. Order is
* significant, because values of this struct type are represented as
* lists, where the order of field values matches the order of
* fields in the StructType. In turn, the order of fields
* matches the order of columns in a read request, or the order of
* fields in the `SELECT` clause of a query.
*/
fields?: Field[];
}
interface TestIamPermissionsRequest {
/**
* REQUIRED: The set of permissions to check for 'resource'.
* Permissions with wildcards (such as '*', 'spanner.*', 'spanner.instances.*') are not allowed.
*/
permissions?: string[];
}
interface TestIamPermissionsResponse {
/**
* A subset of `TestPermissionsRequest.permissions` that the caller is
* allowed.
*/
permissions?: string[];
}
interface Transaction {
/**
* `id` may be used to identify the transaction in subsequent
* Read,
* ExecuteSql,
* Commit, or
* Rollback calls.
*
* Single-use read-only transactions do not have IDs, because
* single-use transactions do not support multiple requests.
*/
id?: string;
/**
* For snapshot read-only transactions, the read timestamp chosen
* for the transaction. Not returned by default: see
* TransactionOptions.ReadOnly.return_read_timestamp.
*/
readTimestamp?: string;
}
interface TransactionOptions {
/**
* Transaction will not write.
*
* Authorization to begin a read-only transaction requires
* `spanner.databases.beginReadOnlyTransaction` permission
* on the `session` resource.
*/
readOnly?: ReadOnly;
/**
* Transaction may write.
*
* Authorization to begin a read-write transaction requires
* `spanner.databases.beginOrRollbackReadWriteTransaction` permission
* on the `session` resource.
*/
readWrite?: any;
}
interface TransactionSelector {
/**
* Begin a new transaction and execute this read or SQL query in
* it. The transaction ID of the new transaction is returned in
* ResultSetMetadata.transaction, which is a Transaction.
*/
begin?: TransactionOptions;
/** Execute the read or SQL query in a previously-started transaction. */
id?: string;
/**
* Execute the read or SQL query in a temporary transaction.
* This is the most efficient way to execute a transaction that
* consists of a single SQL query.
*/
singleUse?: TransactionOptions;
}
interface Type {
/**
* If code == ARRAY, then `array_element_type`
* is the type of the array elements.
*/
arrayElementType?: Type;
/** Required. The TypeCode for this type. */
code?: string;
/**
* If code == STRUCT, then `struct_type`
* provides type information for the struct's fields.
*/
structType?: StructType;
}
interface UpdateDatabaseDdlMetadata {
/**
* Reports the commit timestamps of all statements that have
* succeeded so far, where `commit_timestamps[i]` is the commit
* timestamp for the statement `statements[i]`.
*/
commitTimestamps?: string[];
/** The database being modified. */
database?: string;
/**
* For an update this list contains all the statements. For an
* individual statement, this list contains only that statement.
*/
statements?: string[];
}
interface UpdateDatabaseDdlRequest {
/**
* If empty, the new update request is assigned an
* automatically-generated operation ID. Otherwise, `operation_id`
* is used to construct the name of the resulting
* Operation.
*
* Specifying an explicit operation ID simplifies determining
* whether the statements were executed in the event that the
* UpdateDatabaseDdl call is replayed,
* or the return value is otherwise lost: the database and
* `operation_id` fields can be combined to form the
* name of the resulting
* longrunning.Operation: `<database>/operations/<operation_id>`.
*
* `operation_id` should be unique within the database, and must be
* a valid identifier: `a-z*`. Note that
* automatically-generated operation IDs always begin with an
* underscore. If the named operation already exists,
* UpdateDatabaseDdl returns
* `ALREADY_EXISTS`.
*/
operationId?: string;
/** DDL statements to be applied to the database. */
statements?: string[];
}
interface UpdateInstanceMetadata {
/**
* The time at which this operation was cancelled. If set, this operation is
* in the process of undoing itself (which is guaranteed to succeed) and
* cannot be cancelled again.
*/
cancelTime?: string;
/** The time at which this operation failed or was completed successfully. */
endTime?: string;
/** The desired end state of the update. */
instance?: Instance;
/**
* The time at which UpdateInstance
* request was received.
*/
startTime?: string;
}
interface UpdateInstanceRequest {
/**
* Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated.
* The field mask must always be specified; this prevents any future fields in
* [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know
* about them.
*/
fieldMask?: string;
/**
* Required. The instance to update, which must always include the instance
* name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field_mask] need be included.
*/
instance?: Instance;
}
interface Write {
/**
* The names of the columns in table to be written.
*
* The list of columns must contain enough columns to allow
* Cloud Spanner to derive values for all primary key columns in the
* row(s) to be modified.
*/
columns?: string[];
/** Required. The table whose rows will be written. */
table?: string;
/**
* The values to be written. `values` can contain more than one
* list of values. If it does, then multiple rows are written, one
* for each entry in `values`. Each list in `values` must have
* exactly as many entries as there are entries in columns
* above. Sending multiple lists is equivalent to sending multiple
* `Mutation`s, each containing one `values` entry and repeating
* table and columns. Individual values in each list are
* encoded as described here.
*/
values?: any[][];
}
interface InstanceConfigsResource {
/** Gets information about a particular instance configuration. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Required. The name of the requested instance configuration. Values are of
* the form `projects/<project>/instanceConfigs/<config>`.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<InstanceConfig>;
/** Lists the supported instance configurations for a given project. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Number of instance configurations to be returned in the response. If 0 or
* less, defaults to the server's maximum allowed page size.
*/
pageSize?: number;
/**
* If non-empty, `page_token` should contain a
* next_page_token
* from a previous ListInstanceConfigsResponse.
*/
pageToken?: string;
/**
* Required. The name of the project for which a list of supported instance
* configurations is requested. Values are of the form
* `projects/<project>`.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListInstanceConfigsResponse>;
}
interface OperationsResource {
/**
* Starts asynchronous cancellation on a long-running operation. The server
* makes a best effort to cancel the operation, but success is not
* guaranteed. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`. Clients can use
* Operations.GetOperation or
* other methods to check whether the cancellation succeeded or whether the
* operation completed despite cancellation. On successful cancellation,
* the operation is not deleted; instead, it becomes an operation with
* an Operation.error value with a google.rpc.Status.code of 1,
* corresponding to `Code.CANCELLED`.
*/
cancel(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be cancelled. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Deletes a long-running operation. This method indicates that the client is
* no longer interested in the operation result. It does not cancel the
* operation. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`.
*/
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be deleted. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Gets the latest state of a long-running operation. Clients can use this
* method to poll the operation result at intervals as recommended by the API
* service.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/**
* Lists operations that match the specified filter in the request. If the
* server doesn't support this method, it returns `UNIMPLEMENTED`.
*
* NOTE: the `name` binding allows API services to override the binding
* to use different resource name schemes, such as `users/*/operations`. To
* override the binding, API services can add a binding such as
* `"/v1/{name=users/*}/operations"` to their service configuration.
* For backwards compatibility, the default name includes the operations
* collection id, however overriding users must ensure the name binding
* is the parent resource, without the operations collection id.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The standard list filter. */
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation's parent resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The standard list page size. */
pageSize?: number;
/** The standard list page token. */
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListOperationsResponse>;
}
interface SessionsResource {
/**
* Begins a new transaction. This step can often be skipped:
* Read, ExecuteSql and
* Commit can begin a new transaction as a
* side-effect.
*/
beginTransaction(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The session in which the transaction runs. */
session: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Transaction>;
/**
* Commits a transaction. The request includes the mutations to be
* applied to rows in the database.
*
* `Commit` might return an `ABORTED` error. This can occur at any time;
* commonly, the cause is conflicts with concurrent
* transactions. However, it can also happen for a variety of other
* reasons. If `Commit` returns `ABORTED`, the caller should re-attempt
* the transaction from the beginning, re-using the same session.
*/
commit(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The session in which the transaction to be committed is running. */
session: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CommitResponse>;
/**
* Creates a new session. A session can be used to perform
* transactions that read and/or modify data in a Cloud Spanner database.
* Sessions are meant to be reused for many consecutive
* transactions.
*
* Sessions can only execute one transaction at a time. To execute
* multiple concurrent read-write/write-only transactions, create
* multiple sessions. Note that standalone reads and queries use a
* transaction internally, and count toward the one transaction
* limit.
*
* Cloud Spanner limits the number of sessions that can exist at any given
* time; thus, it is a good idea to delete idle and/or unneeded sessions.
* Aside from explicit deletes, Cloud Spanner can delete sessions for which no
* operations are sent for more than an hour. If a session is deleted,
* requests to it return `NOT_FOUND`.
*
* Idle sessions can be kept alive by sending a trivial SQL query
* periodically, e.g., `"SELECT 1"`.
*/
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Required. The database in which the new session is created. */
database: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Session>;
/** Ends a session, releasing server resources associated with it. */
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Required. The name of the session to delete. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Executes an SQL query, returning all rows in a single reply. This
* method cannot be used to return a result set larger than 10 MiB;
* if the query yields more data than that, the query fails with
* a `FAILED_PRECONDITION` error.
*
* Queries inside read-write transactions might return `ABORTED`. If
* this occurs, the application should restart the transaction from
* the beginning. See Transaction for more details.
*
* Larger result sets can be fetched in streaming fashion by calling
* ExecuteStreamingSql instead.
*/
executeSql(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The session in which the SQL query should be performed. */
session: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ResultSet>;
/**
* Like ExecuteSql, except returns the result
* set as a stream. Unlike ExecuteSql, there
* is no limit on the size of the returned result set. However, no
* individual row in the result set can exceed 100 MiB, and no
* column value can exceed 10 MiB.
*/
executeStreamingSql(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The session in which the SQL query should be performed. */
session: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<PartialResultSet>;
/**
* Gets a session. Returns `NOT_FOUND` if the session does not exist.
* This is mainly useful for determining whether a session is still
* alive.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Required. The name of the session to retrieve. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Session>;
/** Lists all sessions in a given database. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Required. The database in which to list sessions. */
database: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* An expression for filtering the results of the request. Filter rules are
* case insensitive. The fields eligible for filtering are:
*
* * labels.key where key is the name of a label
*
* Some examples of using filters are:
*
* * labels.env:* --> The session has the label "env".
* * labels.env:dev --> The session has the label "env" and the value of
* the label contains the string "dev".
*/
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Number of sessions to be returned in the response. If 0 or less, defaults
* to the server's maximum allowed page size.
*/
pageSize?: number;
/**
* If non-empty, `page_token` should contain a
* next_page_token from a previous
* ListSessionsResponse.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListSessionsResponse>;
/**
* Reads rows from the database using key lookups and scans, as a
* simple key/value style alternative to
* ExecuteSql. This method cannot be used to
* return a result set larger than 10 MiB; if the read matches more
* data than that, the read fails with a `FAILED_PRECONDITION`
* error.
*
* Reads inside read-write transactions might return `ABORTED`. If
* this occurs, the application should restart the transaction from
* the beginning. See Transaction for more details.
*
* Larger result sets can be yielded in streaming fashion by calling
* StreamingRead instead.
*/
read(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The session in which the read should be performed. */
session: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ResultSet>;
/**
* Rolls back a transaction, releasing any locks it holds. It is a good
* idea to call this for any transaction that includes one or more
* Read or ExecuteSql requests and
* ultimately decides not to commit.
*
* `Rollback` returns `OK` if it successfully aborts the transaction, the
* transaction was already aborted, or the transaction is not
* found. `Rollback` never returns `ABORTED`.
*/
rollback(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The session in which the transaction to roll back is running. */
session: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Like Read, except returns the result set as a
* stream. Unlike Read, there is no limit on the
* size of the returned result set. However, no individual row in
* the result set can exceed 100 MiB, and no column value can exceed
* 10 MiB.
*/
streamingRead(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required. The session in which the read should be performed. */
session: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<PartialResultSet>;
}
interface DatabasesResource {
/**
* Creates a new Cloud Spanner database and starts to prepare it for serving.
* The returned long-running operation will
* have a name of the format `<database_name>/operations/<operation_id>` and
* can be used to track preparation of the database. The
* metadata field type is
* CreateDatabaseMetadata. The
* response field type is
* Database, if successful.
*/
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Required. The name of the instance that will serve the new database.
* Values are of the form `projects/<project>/instances/<instance>`.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/** Drops (aka deletes) a Cloud Spanner database. */
dropDatabase(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Required. The database to be dropped. */
database: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** Gets the state of a Cloud Spanner database. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Required. The name of the requested database. Values are of the form
* `projects/<project>/instances/<instance>/databases/<database>`.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Database>;
/**
* Returns the schema of a Cloud Spanner database as a list of formatted
* DDL statements. This method does not show pending schema updates, those may
* be queried using the Operations API.
*/
getDdl(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Required. The database whose schema we wish to get. */
database: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<GetDatabaseDdlResponse>;
/**
* Gets the access control policy for a database resource. Returns an empty
* policy if a database exists but does not have a policy set.
*
* Authorization requires `spanner.databases.getIamPolicy` permission on
* resource.
*/
getIamPolicy(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The Cloud Spanner resource for which the policy is being retrieved. The format is `projects/<project ID>/instances/<instance ID>` for
* instance resources and `projects/<project ID>/instances/<instance ID>/databases/<database ID>` for database resources.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
/** Lists Cloud Spanner databases. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Number of databases to be returned in the response. If 0 or less,
* defaults to the server's maximum allowed page size.
*/
pageSize?: number;
/**
* If non-empty, `page_token` should contain a
* next_page_token from a
* previous ListDatabasesResponse.
*/
pageToken?: string;
/**
* Required. The instance whose databases should be listed.
* Values are of the form `projects/<project>/instances/<instance>`.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListDatabasesResponse>;
/**
* Sets the access control policy on a database resource. Replaces any
* existing policy.
*
* Authorization requires `spanner.databases.setIamPolicy` permission on
* resource.
*/
setIamPolicy(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The Cloud Spanner resource for which the policy is being set. The format is `projects/<project ID>/instances/<instance ID>` for instance
* resources and `projects/<project ID>/instances/<instance ID>/databases/<database ID>` for databases resources.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
/**
* Returns permissions that the caller has on the specified database resource.
*
* Attempting this RPC on a non-existent Cloud Spanner database will result in
* a NOT_FOUND error if the user has `spanner.databases.list` permission on
* the containing Cloud Spanner instance. Otherwise returns an empty set of
* permissions.
*/
testIamPermissions(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The Cloud Spanner resource for which permissions are being tested. The format is `projects/<project ID>/instances/<instance ID>` for instance
* resources and `projects/<project ID>/instances/<instance ID>/databases/<database ID>` for database resources.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TestIamPermissionsResponse>;
/**
* Updates the schema of a Cloud Spanner database by
* creating/altering/dropping tables, columns, indexes, etc. The returned
* long-running operation will have a name of
* the format `<database_name>/operations/<operation_id>` and can be used to
* track execution of the schema change(s). The
* metadata field type is
* UpdateDatabaseDdlMetadata. The operation has no response.
*/
updateDdl(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Required. The database to update. */
database: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
operations: OperationsResource;
sessions: SessionsResource;
}
interface OperationsResource {
/**
* Starts asynchronous cancellation on a long-running operation. The server
* makes a best effort to cancel the operation, but success is not
* guaranteed. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`. Clients can use
* Operations.GetOperation or
* other methods to check whether the cancellation succeeded or whether the
* operation completed despite cancellation. On successful cancellation,
* the operation is not deleted; instead, it becomes an operation with
* an Operation.error value with a google.rpc.Status.code of 1,
* corresponding to `Code.CANCELLED`.
*/
cancel(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be cancelled. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Deletes a long-running operation. This method indicates that the client is
* no longer interested in the operation result. It does not cancel the
* operation. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`.
*/
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be deleted. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Gets the latest state of a long-running operation. Clients can use this
* method to poll the operation result at intervals as recommended by the API
* service.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/**
* Lists operations that match the specified filter in the request. If the
* server doesn't support this method, it returns `UNIMPLEMENTED`.
*
* NOTE: the `name` binding allows API services to override the binding
* to use different resource name schemes, such as `users/*/operations`. To
* override the binding, API services can add a binding such as
* `"/v1/{name=users/*}/operations"` to their service configuration.
* For backwards compatibility, the default name includes the operations
* collection id, however overriding users must ensure the name binding
* is the parent resource, without the operations collection id.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The standard list filter. */
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation's parent resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The standard list page size. */
pageSize?: number;
/** The standard list page token. */
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListOperationsResponse>;
}
interface InstancesResource {
/**
* Creates an instance and begins preparing it to begin serving. The
* returned long-running operation
* can be used to track the progress of preparing the new
* instance. The instance name is assigned by the caller. If the
* named instance already exists, `CreateInstance` returns
* `ALREADY_EXISTS`.
*
* Immediately upon completion of this request:
*
* * The instance is readable via the API, with all requested attributes
* but no allocated resources. Its state is `CREATING`.
*
* Until completion of the returned operation:
*
* * Cancelling the operation renders the instance immediately unreadable
* via the API.
* * The instance can be deleted.
* * All other attempts to modify the instance are rejected.
*
* Upon completion of the returned operation:
*
* * Billing for all successfully-allocated resources begins (some types
* may have lower than the requested levels).
* * Databases can be created in the instance.
* * The instance's allocated resource levels are readable via the API.
* * The instance's state becomes `READY`.
*
* The returned long-running operation will
* have a name of the format `<instance_name>/operations/<operation_id>` and
* can be used to track creation of the instance. The
* metadata field type is
* CreateInstanceMetadata.
* The response field type is
* Instance, if successful.
*/
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Required. The name of the project in which to create the instance. Values
* are of the form `projects/<project>`.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/**
* Deletes an instance.
*
* Immediately upon completion of the request:
*
* * Billing ceases for all of the instance's reserved resources.
*
* Soon afterward:
*
* * The instance and *all of its databases* immediately and
* irrevocably disappear from the API. All data in the databases
* is permanently deleted.
*/
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Required. The name of the instance to be deleted. Values are of the form
* `projects/<project>/instances/<instance>`
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** Gets information about a particular instance. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Required. The name of the requested instance. Values are of the form
* `projects/<project>/instances/<instance>`.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Instance>;
/**
* Gets the access control policy for an instance resource. Returns an empty
* policy if an instance exists but does not have a policy set.
*
* Authorization requires `spanner.instances.getIamPolicy` on
* resource.
*/
getIamPolicy(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The Cloud Spanner resource for which the policy is being retrieved. The format is `projects/<project ID>/instances/<instance ID>` for
* instance resources and `projects/<project ID>/instances/<instance ID>/databases/<database ID>` for database resources.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
/** Lists all instances in the given project. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* An expression for filtering the results of the request. Filter rules are
* case insensitive. The fields eligible for filtering are:
*
* * name
* * display_name
* * labels.key where key is the name of a label
*
* Some examples of using filters are:
*
* * name:* --> The instance has a name.
* * name:Howl --> The instance's name contains the string "howl".
* * name:HOWL --> Equivalent to above.
* * NAME:howl --> Equivalent to above.
* * labels.env:* --> The instance has the label "env".
* * labels.env:dev --> The instance has the label "env" and the value of
* the label contains the string "dev".
* * name:howl labels.env:dev --> The instance's name contains "howl" and
* it has the label "env" with its value
* containing "dev".
*/
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Number of instances to be returned in the response. If 0 or less, defaults
* to the server's maximum allowed page size.
*/
pageSize?: number;
/**
* If non-empty, `page_token` should contain a
* next_page_token from a
* previous ListInstancesResponse.
*/
pageToken?: string;
/**
* Required. The name of the project for which a list of instances is
* requested. Values are of the form `projects/<project>`.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListInstancesResponse>;
/**
* Updates an instance, and begins allocating or releasing resources
* as requested. The returned long-running
* operation can be used to track the
* progress of updating the instance. If the named instance does not
* exist, returns `NOT_FOUND`.
*
* Immediately upon completion of this request:
*
* * For resource types for which a decrease in the instance's allocation
* has been requested, billing is based on the newly-requested level.
*
* Until completion of the returned operation:
*
* * Cancelling the operation sets its metadata's
* cancel_time, and begins
* restoring resources to their pre-request values. The operation
* is guaranteed to succeed at undoing all resource changes,
* after which point it terminates with a `CANCELLED` status.
* * All other attempts to modify the instance are rejected.
* * Reading the instance via the API continues to give the pre-request
* resource levels.
*
* Upon completion of the returned operation:
*
* * Billing begins for all successfully-allocated resources (some types
* may have lower than the requested levels).
* * All newly-reserved resources are available for serving the instance's
* tables.
* * The instance's new resource levels are readable via the API.
*
* The returned long-running operation will
* have a name of the format `<instance_name>/operations/<operation_id>` and
* can be used to track the instance modification. The
* metadata field type is
* UpdateInstanceMetadata.
* The response field type is
* Instance, if successful.
*
* Authorization requires `spanner.instances.update` permission on
* resource name.
*/
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Required. A unique identifier for the instance, which cannot be changed
* after the instance is created. Values are of the form
* `projects/<project>/instances/a-z*[a-z0-9]`. The final
* segment of the name must be between 6 and 30 characters in length.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/**
* Sets the access control policy on an instance resource. Replaces any
* existing policy.
*
* Authorization requires `spanner.instances.setIamPolicy` on
* resource.
*/
setIamPolicy(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The Cloud Spanner resource for which the policy is being set. The format is `projects/<project ID>/instances/<instance ID>` for instance
* resources and `projects/<project ID>/instances/<instance ID>/databases/<database ID>` for databases resources.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
/**
* Returns permissions that the caller has on the specified instance resource.
*
* Attempting this RPC on a non-existent Cloud Spanner instance resource will
* result in a NOT_FOUND error if the user has `spanner.instances.list`
* permission on the containing Google Cloud Project. Otherwise returns an
* empty set of permissions.
*/
testIamPermissions(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The Cloud Spanner resource for which permissions are being tested. The format is `projects/<project ID>/instances/<instance ID>` for instance
* resources and `projects/<project ID>/instances/<instance ID>/databases/<database ID>` for database resources.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TestIamPermissionsResponse>;
databases: DatabasesResource;
operations: OperationsResource;
}
interface ProjectsResource {
instanceConfigs: InstanceConfigsResource;
instances: InstancesResource;
}
}
} | the_stack |
import { mention } from "../utils/mention"
import { RegExpValidator } from "regexpp"
import type { CharacterClassElement, Element } from "regexpp/ast"
import type { RegExpVisitor } from "regexpp/visitor"
import type { RegExpContext } from "../utils"
import {
isOctalEscape,
createRule,
defineRegexpVisitor,
isEscapeSequence,
} from "../utils"
const validator = new RegExpValidator({ strict: true, ecmaVersion: 2020 })
/**
* Check syntax error in a given pattern.
* @returns The syntax error.
*/
function validateRegExpPattern(
pattern: string,
uFlag?: boolean,
): string | null {
try {
validator.validatePattern(pattern, undefined, undefined, uFlag)
return null
} catch (err) {
return err instanceof Error ? err.message : null
}
}
const CHARACTER_CLASS_SYNTAX_CHARACTERS = new Set("\\/()[]{}^$.|-+*?".split(""))
const SYNTAX_CHARACTERS = new Set("\\/()[]{}^$.|+*?".split(""))
export default createRule("strict", {
meta: {
docs: {
description: "disallow not strictly valid regular expressions",
category: "Possible Errors",
recommended: true,
},
fixable: "code",
schema: [],
messages: {
// character escape
invalidControlEscape:
"Invalid or incomplete control escape sequence. Either use a valid control escape sequence or escaping the standalone backslash.",
incompleteEscapeSequence:
"Incomplete escape sequence {{expr}}. Either use a valid escape sequence or remove the useless escaping.",
invalidPropertyEscape:
"Invalid property escape sequence {{expr}}. Either use a valid property escape sequence or remove the useless escaping.",
incompleteBackreference:
"Incomplete backreference {{expr}}. Either use a valid backreference or remove the useless escaping.",
unescapedSourceCharacter: "Unescaped source character {{expr}}.",
octalEscape:
"Invalid legacy octal escape sequence {{expr}}. Use a hexadecimal escape instead.",
uselessEscape:
"Useless identity escapes with non-syntax characters are forbidden.",
// character class
invalidRange:
"Invalid character class range. A character set cannot be the minimum or maximum of a character class range. Either escape the `-` or fix the character class range.",
// assertion
quantifiedAssertion:
"Assertion are not allowed to be quantified directly.",
// validator
regexMessage: "{{message}}.",
// suggestions
hexEscapeSuggestion:
"Replace the octal escape with a hexadecimal escape.",
},
type: "suggestion",
hasSuggestions: true,
},
create(context) {
/**
* Create visitor
*/
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const { node, flags, pattern, getRegexpLocation, fixReplaceNode } =
regexpContext
if (flags.unicode) {
// the Unicode flag enables strict parsing mode automatically
return {}
}
let reported = false
let hasNamedBackreference = false
/** Report */
function report(
messageId: string,
element: Element,
fix?: string | null | { fix: string; messageId: string },
): void {
reported = true
if (fix && typeof fix === "object") {
context.report({
node,
loc: getRegexpLocation(element),
messageId,
data: {
expr: mention(element),
},
suggest: [
{
messageId: fix.messageId,
fix: fixReplaceNode(element, fix.fix),
},
],
})
} else {
context.report({
node,
loc: getRegexpLocation(element),
messageId,
data: {
expr: mention(element),
},
fix: fix ? fixReplaceNode(element, fix) : null,
})
}
}
return {
// eslint-disable-next-line complexity -- x
onCharacterEnter(cNode) {
if (cNode.raw === "\\") {
// e.g. \c5 or \c
report("invalidControlEscape", cNode)
return
}
if (cNode.raw === "\\u" || cNode.raw === "\\x") {
// e.g. \u000;
report("incompleteEscapeSequence", cNode)
return
}
if (cNode.raw === "\\p" || cNode.raw === "\\P") {
// e.g. \p{H} or \p
report("invalidPropertyEscape", cNode)
return
}
if (cNode.value !== 0 && isOctalEscape(cNode.raw)) {
// e.g. \023, \34
// this could be confused with a backreference
// use a suggestion instead of a fix
report("octalEscape", cNode, {
fix: `\\x${cNode.value
.toString(16)
.padStart(2, "0")}`,
messageId: "hexEscapeSuggestion",
})
return
}
const insideCharClass =
cNode.parent.type === "CharacterClass" ||
cNode.parent.type === "CharacterClassRange"
if (!insideCharClass) {
if (cNode.raw === "\\k") {
// e.g. \k<foo or \k
report("incompleteBackreference", cNode)
return
}
if (
cNode.raw === "{" ||
cNode.raw === "}" ||
cNode.raw === "]"
) {
report(
"unescapedSourceCharacter",
cNode,
`\\${cNode.raw}`,
)
return
}
}
if (isEscapeSequence(cNode.raw)) {
// all remaining escape sequences are valid
return
}
if (cNode.raw.startsWith("\\")) {
const identity = cNode.raw.slice(1)
const syntaxChars = insideCharClass
? CHARACTER_CLASS_SYNTAX_CHARACTERS
: SYNTAX_CHARACTERS
if (
cNode.value === identity.charCodeAt(0) &&
!syntaxChars.has(identity)
) {
// e.g. \g or \;
report("uselessEscape", cNode, identity)
}
}
},
onCharacterClassEnter(ccNode) {
for (let i = 0; i < ccNode.elements.length; i++) {
const current = ccNode.elements[i]
if (current.type === "CharacterSet") {
const next: CharacterClassElement | undefined =
ccNode.elements[i + 1]
const nextNext: CharacterClassElement | undefined =
ccNode.elements[i + 2]
if (next && next.raw === "-" && nextNext) {
// e.g. [\w-a]
report("invalidRange", current)
return
}
const prev: CharacterClassElement | undefined =
ccNode.elements[i - 1]
const prevPrev: CharacterClassElement | undefined =
ccNode.elements[i - 2]
if (
prev &&
prev.raw === "-" &&
prevPrev &&
prevPrev.type !== "CharacterClassRange"
) {
// e.g. [a-\w]
report("invalidRange", current)
return
}
}
}
},
onQuantifierEnter(qNode) {
if (qNode.element.type === "Assertion") {
// e.g. \b+
report(
"quantifiedAssertion",
qNode,
`(?:${qNode.element.raw})${qNode.raw.slice(
qNode.element.end - qNode.start,
)}`,
)
}
},
onBackreferenceEnter(bNode) {
if (typeof bNode.ref === "string") {
hasNamedBackreference = true
}
},
onPatternLeave() {
if (hasNamedBackreference) {
// There is a bug in regexpp that causes it throw a
// syntax error for all non-Unicode regexes with named
// backreferences.
// TODO: Remove this workaround when the bug is fixed.
return
}
if (!reported) {
// our own logic couldn't find any problems,
// so let's use a real parser to do the job.
const message = validateRegExpPattern(
pattern,
flags.unicode,
)
if (message) {
context.report({
node,
messageId: "regexMessage",
data: {
message,
},
})
}
}
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
}) | the_stack |
import { browser, protractor } from 'protractor';
import { createApiService,
AppListCloudPage,
LoginPage,
ProcessCloudWidgetPage,
ProcessDefinitionsService,
ProcessInstancesService,
QueryService,
StringUtil,
TaskFormCloudComponent,
TaskHeaderCloudPage,
TasksService,
FormCloudService,
Logger
} from '@alfresco/adf-testing';
import { NavigationBarPage } from '../../core/pages/navigation-bar.page';
import { TasksCloudDemoPage } from './../pages/tasks-cloud-demo.page';
describe('Task form cloud component', () => {
const candidateBaseApp = browser.params.resources.ACTIVITI_CLOUD_APPS.CANDIDATE_BASE_APP.name;
const candidateBaseAppProcesses = browser.params.resources.ACTIVITI_CLOUD_APPS.CANDIDATE_BASE_APP.processes;
const simpleApp = browser.params.resources.ACTIVITI_CLOUD_APPS.SIMPLE_APP.name;
const simpleAppProcess = browser.params.resources.ACTIVITI_CLOUD_APPS.SIMPLE_APP.processes;
const simpleAppForm = browser.params.resources.ACTIVITI_CLOUD_APPS.SIMPLE_APP.forms;
const loginSSOPage = new LoginPage();
const navigationBarPage = new NavigationBarPage();
const appListCloudComponent = new AppListCloudPage();
const tasksCloudDemoPage = new TasksCloudDemoPage();
const editTaskFilter = tasksCloudDemoPage.editTaskFilterCloud;
const taskFilter = tasksCloudDemoPage.taskFilterCloudComponent;
const taskList = tasksCloudDemoPage.taskListCloudComponent();
const taskHeaderCloudPage = new TaskHeaderCloudPage();
const taskFormCloudComponent = new TaskFormCloudComponent();
const widget = new ProcessCloudWidgetPage();
const apiService = createApiService();
const tasksService = new TasksService(apiService);
const queryService = new QueryService(apiService);
const processDefinitionService = new ProcessDefinitionsService(apiService);
const processInstancesService = new ProcessInstancesService(apiService);
const formCloudService = new FormCloudService(apiService);
const completedTaskName = StringUtil.generateRandomString(), assignedTaskName = StringUtil.generateRandomString();
const myTasksFilter = 'my-tasks';
const completedTasksFilter = 'completed-tasks';
const dateFieldId = 'Date0rzbb6';
const defaultDate = '2020-07-09';
const changedDate = '2020-07-10';
const dropdownFieldId = 'DropdownOptions';
let completedTask, createdTask, assigneeTask, toBeCompletedTask, formValidationsTask, formTaskId, assigneeTaskId, assigneeReleaseTask, candidateUsersTask ;
let dateTimerTaskId, dateTimerTask, dateTimerChangedTaskId, dateTimerChangedTask, dropdownOptionsTask;
beforeAll(async () => {
try {
await apiService.loginWithProfile('hrUser');
createdTask = await tasksService.createStandaloneTask(StringUtil.generateRandomString(), candidateBaseApp);
assigneeTask = await tasksService.createStandaloneTask(StringUtil.generateRandomString(), candidateBaseApp);
await tasksService.claimTask(assigneeTask.entry.id, candidateBaseApp);
const formToTestValidationsKey = await formCloudService.getIdByFormName(candidateBaseApp,
browser.params.resources.ACTIVITI_CLOUD_APPS.CANDIDATE_BASE_APP.forms.formtotestvalidations);
formValidationsTask = await tasksService.createStandaloneTaskWithForm(StringUtil.generateRandomString(), candidateBaseApp, formToTestValidationsKey);
await tasksService.claimTask(formValidationsTask.entry.id, candidateBaseApp);
toBeCompletedTask = await tasksService.createStandaloneTask(StringUtil.generateRandomString(), candidateBaseApp);
await tasksService.claimTask(toBeCompletedTask.entry.id, candidateBaseApp);
completedTask = await tasksService.createStandaloneTask(assignedTaskName, candidateBaseApp);
await tasksService.claimTask(completedTask.entry.id, candidateBaseApp);
await tasksService.createAndCompleteTask(completedTaskName, candidateBaseApp);
let processDefinition = await processDefinitionService
.getProcessDefinitionByName(candidateBaseAppProcesses.candidateUserProcess, candidateBaseApp);
const candidateUsersProcessInstance = await processInstancesService.createProcessInstance(processDefinition.entry.key, candidateBaseApp);
const processInstanceTasks = await queryService.getProcessInstanceTasks(candidateUsersProcessInstance.entry.id, candidateBaseApp);
candidateUsersTask = processInstanceTasks.list.entries[0];
await tasksService.claimTask(candidateUsersTask.entry.id, candidateBaseApp);
processDefinition = await processDefinitionService
.getProcessDefinitionByName(candidateBaseAppProcesses.candidateUserProcess, candidateBaseApp);
const formProcess = await processInstancesService.createProcessInstance(processDefinition.entry.key, candidateBaseApp);
const formTasks = await queryService.getProcessInstanceTasks(formProcess.entry.id, candidateBaseApp);
formTaskId = formTasks.list.entries[0].entry.id;
const dropdownOptionsId = await formCloudService.getIdByFormName(simpleApp, simpleAppForm.dropdownWithOptions.name);
dropdownOptionsTask = await tasksService.createStandaloneTaskWithForm(StringUtil.generateRandomString(),
simpleApp, dropdownOptionsId);
await tasksService.claimTask(dropdownOptionsTask.entry.id, simpleApp);
const timerProcessDefinition = await processDefinitionService
.getProcessDefinitionByName(simpleAppProcess.intermediateDateProcessVarTimer, simpleApp);
const dateTimerProcess = await processInstancesService.createProcessInstance(timerProcessDefinition.entry.key, simpleApp);
dateTimerTask = await queryService.getProcessInstanceTasks(dateTimerProcess.entry.id, simpleApp);
dateTimerTaskId = dateTimerTask.list.entries[0].entry.id;
const timerChangedProcessDefinition = await processDefinitionService
.getProcessDefinitionByName(simpleAppProcess.intermediateDateProcessVarTimer, simpleApp);
const dateTimerChangedProcess = await processInstancesService.createProcessInstance(timerChangedProcessDefinition.entry.key, simpleApp);
dateTimerChangedTask = await queryService.getProcessInstanceTasks(dateTimerChangedProcess.entry.id, simpleApp);
dateTimerChangedTaskId = dateTimerChangedTask.list.entries[0].entry.id;
/* cspell: disable-next-line */
const assigneeProcessDefinition = await processDefinitionService.getProcessDefinitionByName(simpleAppProcess.calledprocess, simpleApp);
const assigneeProcess = await processInstancesService.createProcessInstance(assigneeProcessDefinition.entry.key, simpleApp);
assigneeReleaseTask = await queryService.getProcessInstanceTasks(assigneeProcess.entry.id, simpleApp);
assigneeTaskId = assigneeReleaseTask.list.entries[0].entry.id;
await loginSSOPage.loginWithProfile('hrUser');
} catch (error) {
Logger.error('Error in beforeAll: ', error);
}
}, 5 * 60 * 1000);
beforeEach(async () => {
await navigationBarPage.navigateToProcessServicesCloudPage();
await appListCloudComponent.checkApsContainer();
});
afterAll(async () => {
await browser.executeScript('window.sessionStorage.clear();');
await browser.executeScript('window.localStorage.clear();');
});
it('[C310366] Should refresh buttons and form after an action is complete', async () => {
await appListCloudComponent.goToApp(candidateBaseApp);
await taskFilter.clickTaskFilter(myTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await expect(taskFilter.getActiveFilterName()).toBe('My Tasks');
await editTaskFilter.openFilter();
await editTaskFilter.clearAssignee();
await editTaskFilter.setStatusFilterDropDown('Created');
await taskList.checkContentIsDisplayedById(formTaskId);
await taskList.selectRowByTaskId(formTaskId);
await taskFormCloudComponent.checkFormIsReadOnly();
await taskFormCloudComponent.checkClaimButtonIsDisplayed();
await taskFormCloudComponent.checkCompleteButtonIsNotDisplayed();
await taskFormCloudComponent.checkReleaseButtonIsNotDisplayed();
await taskFormCloudComponent.clickClaimButton();
await taskFormCloudComponent.checkFormIsDisplayed();
await taskFormCloudComponent.checkFormIsNotReadOnly();
await taskFormCloudComponent.checkClaimButtonIsNotDisplayed();
await taskFormCloudComponent.checkCompleteButtonIsDisplayed();
await taskFormCloudComponent.checkReleaseButtonIsDisplayed();
await taskFormCloudComponent.clickCompleteButton();
await openTaskByIdFromFilters(completedTasksFilter, formTaskId);
await taskFormCloudComponent.checkFormIsReadOnly();
await taskFormCloudComponent.checkClaimButtonIsNotDisplayed();
await taskFormCloudComponent.checkCompleteButtonIsNotDisplayed();
await taskFormCloudComponent.checkReleaseButtonIsNotDisplayed();
await taskFormCloudComponent.checkCancelButtonIsDisplayed();
});
it('[C306872] Should not be able to Release a process task which has only assignee', async () => {
await appListCloudComponent.goToApp(simpleApp);
await openTaskByIdFromFilters(myTasksFilter, assigneeTaskId);
await expect(await taskHeaderCloudPage.getAssignee()).toEqual(assigneeReleaseTask.list.entries[0].entry.assignee);
await expect(await taskHeaderCloudPage.getStatus()).toEqual('ASSIGNED');
await taskFormCloudComponent.checkReleaseButtonIsNotDisplayed();
});
it('[C310200] Should be able to save a task form', async () => {
const selectedOption = 'option1';
const dropdownId = '#DropdownOptions';
await goToAppOpenDropdownTaskByNameFromFilters(myTasksFilter, dropdownOptionsTask.entry.name);
await widget.dropdown().openDropdown(dropdownId);
await widget.dropdown().selectOption(selectedOption, dropdownId );
await taskFormCloudComponent.checkSaveButtonIsDisplayed();
await taskFormCloudComponent.clickSaveButton();
await navigationBarPage.clickHomeButton();
await navigationBarPage.navigateToProcessServicesCloudPage();
await appListCloudComponent.checkApsContainer();
await goToAppOpenDropdownTaskByNameFromFilters(myTasksFilter, dropdownOptionsTask.entry.name);
await expect(await widget.dropdown().getSelectedOptionText(dropdownFieldId)).toBe(selectedOption);
});
it('[C313200] Should be able to complete a Task form with process date variable mapped to a Date widget in the form', async () => {
await appListCloudComponent.goToApp(simpleApp);
await openTaskByIdFromFilters(myTasksFilter, dateTimerTaskId);
await verifyDateInput(dateFieldId, defaultDate);
await completeTask();
await verifyDateCompletedTask(dateTimerTaskId, defaultDate);
await openTaskByIdFromFilters(myTasksFilter, dateTimerChangedTaskId );
await verifyDateInput(dateFieldId, defaultDate);
await widget.dateWidget().clearDateInput(dateFieldId);
await widget.dateWidget().setDateInput(dateFieldId, changedDate );
await completeTask();
await verifyDateCompletedTask(dateTimerChangedTaskId, changedDate);
});
describe('Candidate Base App', () => {
beforeEach(async () => {
await appListCloudComponent.goToApp(candidateBaseApp);
});
it('[C307032] Should display the appropriate title for the unclaim option of a Task', async () => {
await openTaskByIdFromFilters(myTasksFilter, candidateUsersTask.entry.id);
await expect(await taskFormCloudComponent.getReleaseButtonText()).toBe('RELEASE');
});
it('[C310142] Empty content is displayed when having a task without form', async () => {
await taskFilter.clickTaskFilter(myTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await taskList.checkContentIsDisplayedByName(assigneeTask.entry.name);
await taskList.selectRow(assigneeTask.entry.name);
await taskFormCloudComponent.checkFormIsNotDisplayed();
await expect(await taskFormCloudComponent.getFormTitle()).toBe(assigneeTask.entry.name);
await taskFormCloudComponent.checkFormContentIsEmpty();
await expect(await taskFormCloudComponent.getEmptyFormContentTitle()).toBe(`No form available`);
await expect(await taskFormCloudComponent.getEmptyFormContentSubtitle()).toBe(`Attach a form that can be viewed later`);
});
it('[C310199] Should not be able to complete a task when required field is empty or invalid data is added to a field', async () => {
await taskFilter.clickTaskFilter(myTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await selectTaskByName(formValidationsTask.entry.name);
await taskFormCloudComponent.formFields().checkFormIsDisplayed();
await taskFormCloudComponent.formFields().checkWidgetIsVisible('Text0tma8h');
await taskFormCloudComponent.formFields().checkWidgetIsVisible('Date0m1moq');
await taskFormCloudComponent.formFields().checkWidgetIsVisible('Number0klykr');
await taskFormCloudComponent.formFields().checkWidgetIsVisible('Amount0mtp1h');
await expect(await taskFormCloudComponent.isCompleteButtonEnabled()).toBe(false);
await widget.textWidget().setValue('Text0tma8h', 'Some random text');
await expect(await taskFormCloudComponent.isCompleteButtonEnabled()).toBe(true);
await widget.dateWidget().setDateInput('Date0m1moq', 'invalid date');
await browser.actions().sendKeys(protractor.Key.ENTER).perform();
await expect(await taskFormCloudComponent.isCompleteButtonEnabled()).toBe(false);
await widget.dateWidget().setDateInput('Date0m1moq', '20-10-2018');
await browser.actions().sendKeys(protractor.Key.ENTER).perform();
await expect(await taskFormCloudComponent.isCompleteButtonEnabled()).toBe(true);
await widget.numberWidget().setFieldValue('Number0klykr', 'invalid number');
await expect(await taskFormCloudComponent.isCompleteButtonEnabled()).toBe(false);
await widget.numberWidget().setFieldValue('Number0klykr', '26');
await expect(await taskFormCloudComponent.isCompleteButtonEnabled()).toBe(true);
await widget.amountWidget().setFieldValue('Amount0mtp1h', 'invalid amount');
await expect(await taskFormCloudComponent.isCompleteButtonEnabled()).toBe(false);
await widget.amountWidget().setFieldValue('Amount0mtp1h', '660');
await expect(await taskFormCloudComponent.isCompleteButtonEnabled()).toBe(true);
});
it('[C307093] Complete button is not displayed when the task is already completed', async () => {
await taskFilter.clickTaskFilter(completedTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await expect(await taskFilter.getActiveFilterName()).toBe('Completed Tasks');
await taskList.checkContentIsDisplayedByName(completedTaskName);
await taskList.selectRow(completedTaskName);
await taskHeaderCloudPage.checkTaskPropertyListIsDisplayed();
await taskFormCloudComponent.checkCompleteButtonIsNotDisplayed();
});
it('[C307095] Task can not be completed by owner user', async () => {
await taskFilter.clickTaskFilter(myTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await expect(await taskFilter.getActiveFilterName()).toBe('My Tasks');
await editTaskFilter.openFilter();
await editTaskFilter.clearAssignee();
await editTaskFilter.setStatusFilterDropDown('Created');
await selectTaskByName(createdTask.entry.name);
await taskFormCloudComponent.checkCompleteButtonIsNotDisplayed();
});
it('[C307110] Task list is displayed after clicking on Cancel button', async () => {
await taskFilter.clickTaskFilter(myTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await expect(await taskFilter.getActiveFilterName()).toBe('My Tasks');
await selectTaskByName(assigneeTask.entry.name);
await taskFormCloudComponent.clickCancelButton();
await expect(await taskFilter.getActiveFilterName()).toBe('My Tasks');
await taskList.checkContentIsDisplayedByName(assigneeTask.entry.name);
});
it('[C307094] Standalone Task can be completed by a user that is owner and assignee', async () => {
await taskFilter.clickTaskFilter(myTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await expect(await taskFilter.getActiveFilterName()).toBe('My Tasks');
await selectTaskByName(toBeCompletedTask.entry.name);
await completeTask();
await taskList.checkContentIsNotDisplayedByName(toBeCompletedTask.entry.name);
await taskFilter.clickTaskFilter(completedTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await taskList.checkContentIsDisplayedByName(toBeCompletedTask.entry.name);
await taskFormCloudComponent.checkCompleteButtonIsNotDisplayed();
});
it('[C307111] Task of a process can be completed by a user that is owner and assignee', async () => {
await taskFilter.clickTaskFilter(myTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await expect(await taskFilter.getActiveFilterName()).toBe('My Tasks');
await selectTaskByName(completedTask.entry.name);
await completeTask();
await taskList.checkContentIsNotDisplayedByName(completedTask.entry.name);
await taskFilter.clickTaskFilter(completedTasksFilter);
await taskList.getDataTable().waitTillContentLoaded();
await taskList.checkContentIsDisplayedByName(completedTask.entry.name);
await taskFormCloudComponent.checkCompleteButtonIsNotDisplayed();
});
});
async function openTaskByIdFromFilters(filterName: string, taskId: string): Promise<void> {
await taskFilter.clickTaskFilter(filterName);
await taskList.getDataTable().waitTillContentLoaded();
await taskList.checkContentIsDisplayedById(taskId);
await taskList.selectRowByTaskId(taskId);
}
async function verifyDateInput(widgetId: string, input: string): Promise<void> {
await widget.dateWidget().checkWidgetIsVisible(widgetId);
await expect(await widget.dateWidget().getDateInput(widgetId)).toBe(input);
}
async function selectTaskByName(taskName: string): Promise<void> {
await taskList.checkContentIsDisplayedByName(taskName);
await taskList.selectRow(taskName);
await taskHeaderCloudPage.checkTaskPropertyListIsDisplayed();
}
async function verifyDateCompletedTask(taskId: string, input: string): Promise<void> {
await openTaskByIdFromFilters(completedTasksFilter, taskId );
await taskFormCloudComponent.checkFormIsReadOnly();
await verifyDateInput(dateFieldId, input);
await taskFormCloudComponent.clickCancelButton();
}
async function goToAppOpenDropdownTaskByNameFromFilters(filterName: string, taskName: string): Promise<void> {
await appListCloudComponent.goToApp(simpleApp);
await taskFilter.clickTaskFilter(filterName);
await taskList.getDataTable().waitTillContentLoaded();
await taskList.checkContentIsDisplayedByName(taskName);
await taskList.selectRow(taskName);
await taskHeaderCloudPage.checkTaskPropertyListIsDisplayed();
await widget.dropdown().isWidgetVisible(dropdownFieldId);
}
async function completeTask(): Promise<void> {
await taskFormCloudComponent.checkCompleteButtonIsDisplayed();
await taskFormCloudComponent.clickCompleteButton();
}
}); | the_stack |
import {
html,
SpectrumElement,
CSSResultArray,
TemplateResult,
property,
PropertyValues,
query,
} from '@spectrum-web-components/base';
import {
MenuItem,
MenuItemAddedOrUpdatedEvent,
MenuItemRemovedEvent,
} from './MenuItem.js';
import menuStyles from './menu.css.js';
export interface MenuChildItem {
menuItem: MenuItem;
managed: boolean;
active: boolean;
focusable: boolean;
focusRoot: Menu;
}
type SelectsType = 'none' | 'ignore' | 'inherit' | 'multiple' | 'single';
type RoleType = 'group' | 'menu' | 'listbox' | 'none';
function elementIsOrContains(
el: Node,
isOrContains: Node | undefined | null
): boolean {
return !!isOrContains && (el === isOrContains || el.contains(isOrContains));
}
/**
* Spectrum Menu Component
* @element sp-menu
*
* @slot - menu items to be listed in the menu
* @fires change - Announces that the `value` of the element has changed
* @attr selects - whether the element has a specific selection algorithm that it applies
* to its item descendants. `single` allows only one descendent to be selected at a time.
* `multiple` allows many descendants to be selected. `inherit` will be applied dynamically
* when an ancestor of this element is actively managing the selection of its descendents.
* When the `selects` attribute is not present a `value` will not be maintained and the Menu
* Item children of this Menu will not have their `selected` state managed.
*/
export class Menu extends SpectrumElement {
public static get styles(): CSSResultArray {
return [menuStyles];
}
@property({ type: String, reflect: true })
public label = '';
@property({ type: String, reflect: true })
public selects: undefined | 'inherit' | 'single' | 'multiple';
@property({ type: String })
public value = '';
// For the multiple select case, we'll join the value strings together
// for the value property with this separator
@property({ type: String, attribute: 'value-separator' })
public valueSeparator = ',';
// TODO: which of these to keep?
// TODO: allow setting this in the API to change the values
@property({ attribute: false })
public selected = [] as string[];
@property({ attribute: false })
public selectedItems = [] as MenuItem[];
@query('slot:not([name])')
public menuSlot!: HTMLSlotElement;
private childItemSet = new Set<MenuItem>();
public focusedItemIndex = 0;
public focusInItemIndex = 0;
private selectedItemsMap = new Map() as Map<MenuItem, boolean>;
public get childItems(): MenuItem[] {
if (!this.cachedChildItems) {
this.cachedChildItems = this.updateCachedMenuItems();
}
return this.cachedChildItems;
}
private cachedChildItems: MenuItem[] | undefined;
private updateCachedMenuItems(): MenuItem[] {
this.cachedChildItems = [];
const slotElements = this.menuSlot.assignedElements({ flatten: true });
for (const slotElement of slotElements) {
const childMenuItems: MenuItem[] =
slotElement instanceof MenuItem
? [slotElement as MenuItem]
: ([...slotElement.querySelectorAll(`*`)] as MenuItem[]);
for (const childMenuItem of childMenuItems) {
if (this.childItemSet.has(childMenuItem)) {
this.cachedChildItems.push(childMenuItem);
}
}
}
return this.cachedChildItems;
}
/**
* Hide this getter from web-component-analyzer until
* https://github.com/runem/web-component-analyzer/issues/131
* has been addressed.
*
* @private
*/
public get childRole(): string {
if (this.resolvedRole === 'listbox') {
return 'option';
}
switch (this.resolvedSelects) {
case 'single':
return 'menuitemradio';
case 'multiple':
return 'menuitemcheckbox';
default:
return 'menuitem';
}
}
protected get ownRole(): string {
return 'menu';
}
private resolvedSelects?: SelectsType;
private resolvedRole?: RoleType;
/**
* When a descendant `<sp-menu-item>` element is added or updated it will dispatch
* this event to announce its presence in the DOM. During the capture phase the first
* Menu based element that the event encounters will manage the focus state of the
* dispatching `<sp-menu-item>` element.
* @param event
*/
private onFocusableItemAddedOrUpdated(
event: MenuItemAddedOrUpdatedEvent
): void {
if (event.item.menuData.focusRoot) {
// Only have one tab stop per Menu tree
this.tabIndex = -1;
}
event.focusRoot = this;
this.addChildItem(event.item);
if (this.selects === 'inherit') {
this.resolvedSelects = 'inherit';
this.resolvedRole = (event.currentAncestorWithSelects?.getAttribute(
'role'
) ||
this.getAttribute('role') ||
undefined) as RoleType;
} else if (this.selects) {
this.resolvedRole = (this.getAttribute('role') ||
undefined) as RoleType;
this.resolvedSelects = this.selects;
event.currentAncestorWithSelects = this;
} else {
this.resolvedRole = (this.getAttribute('role') ||
undefined) as RoleType;
this.resolvedSelects =
this.resolvedRole === 'none' ? 'ignore' : 'none';
}
}
/**
* When a descendant `<sp-menu-item>` element is added or updated it will dispatch
* this event to announce its presence in the DOM. During the bubble phase the first
* Menu based element that the event encounters that does not inherit selection will
* manage the selection state of the dispatching `<sp-menu-item>` element.
* @param event
*/
private onSelectableItemAddedOrUpdated(
event: MenuItemAddedOrUpdatedEvent
): void {
const selects =
this.resolvedSelects === 'single' ||
this.resolvedSelects === 'multiple';
if (
(selects || (!this.selects && this.resolvedSelects !== 'ignore')) &&
!event.item.menuData.selectionRoot
) {
event.item.setRole(this.childRole);
event.selectionRoot = this;
}
}
private addChildItem(item: MenuItem): void {
this.childItemSet.add(item);
this.handleItemsChanged();
}
private async removeChildItem(event: MenuItemRemovedEvent): Promise<void> {
this.childItemSet.delete(event.item);
this.cachedChildItems = undefined;
if (event.item.focused) {
this.handleItemsChanged();
await this.updateComplete;
this.focus();
}
}
public constructor() {
super();
this.addEventListener(
'sp-menu-item-added-or-updated',
this.onSelectableItemAddedOrUpdated
);
this.addEventListener(
'sp-menu-item-added-or-updated',
this.onFocusableItemAddedOrUpdated,
{
capture: true,
}
);
this.addEventListener('sp-menu-item-removed', this.removeChildItem);
this.addEventListener('click', this.onClick);
this.addEventListener('focusin', this.handleFocusin);
}
public focus({ preventScroll }: FocusOptions = {}): void {
if (
!this.childItems.length ||
this.childItems.every((childItem) => childItem.disabled)
) {
return;
}
if (
this.childItems.some(
(childItem) => childItem.menuData.focusRoot !== this
)
) {
super.focus({ preventScroll });
return;
}
this.focusMenuItemByOffset(0);
super.focus({ preventScroll });
const selectedItem = this.querySelector('[selected]');
if (selectedItem && !preventScroll) {
selectedItem.scrollIntoView({ block: 'nearest' });
}
}
private onClick(event: Event): void {
if (event.defaultPrevented) {
return;
}
const path = event.composedPath();
const target = path.find((el) => {
/* c8 ignore next 3 */
if (!(el instanceof Element)) {
return false;
}
return el.getAttribute('role') === this.childRole;
}) as MenuItem;
if (target?.href && target.href.length) {
return;
}
if (target?.menuData.selectionRoot === this) {
event.preventDefault();
this.selectOrToggleItem(target);
} else {
return;
}
this.prepareToCleanUp();
}
public handleFocusin(event: FocusEvent): void {
const isOrContainsRelatedTarget = elementIsOrContains(
this,
event.relatedTarget as Node
);
if (
isOrContainsRelatedTarget ||
this.childItems.some(
(childItem) => childItem.menuData.focusRoot !== this
)
) {
return;
}
const activeElement = (this.getRootNode() as Document).activeElement as
| MenuItem
| Menu;
const selectionRoot =
this.childItems[this.focusedItemIndex]?.menuData.selectionRoot ||
this;
if (activeElement !== selectionRoot || !isOrContainsRelatedTarget) {
selectionRoot.focus({ preventScroll: true });
if (activeElement && this.focusedItemIndex === 0) {
const offset = this.childItems.findIndex(
(childItem) => childItem === activeElement
);
if (offset > 0) {
this.focusMenuItemByOffset(offset);
}
}
}
this.startListeningToKeyboard();
}
public startListeningToKeyboard(): void {
this.addEventListener('keydown', this.handleKeydown);
this.addEventListener('focusout', this.handleFocusout);
}
public handleFocusout(event: FocusEvent): void {
if (elementIsOrContains(this, event.relatedTarget as Node)) {
(event.composedPath()[0] as MenuItem).focused = false;
return;
}
this.stopListeningToKeyboard();
if (
event.target === this &&
this.childItems.some(
(childItem) => childItem.menuData.focusRoot === this
)
) {
const focusedItem = this.childItems[this.focusedItemIndex];
if (focusedItem) {
focusedItem.focused = false;
}
}
this.removeAttribute('aria-activedescendant');
}
public stopListeningToKeyboard(): void {
this.removeEventListener('keydown', this.handleKeydown);
this.removeEventListener('focusout', this.handleFocusout);
}
public async selectOrToggleItem(targetItem: MenuItem): Promise<void> {
const resolvedSelects = this.resolvedSelects;
const oldSelectedItemsMap = new Map(this.selectedItemsMap);
const oldSelected = this.selected.slice();
const oldSelectedItems = this.selectedItems.slice();
const oldValue = this.value;
this.childItems[this.focusedItemIndex].focused = false;
this.focusedItemIndex = this.childItems.indexOf(targetItem);
this.forwardFocusVisibleToItem(targetItem);
if (resolvedSelects === 'multiple') {
if (this.selectedItemsMap.has(targetItem)) {
this.selectedItemsMap.delete(targetItem);
} else {
this.selectedItemsMap.set(targetItem, true);
}
// Match HTML select and set the first selected
// item as the value. Also set the selected array
// in the order of the menu items.
const selected: string[] = [];
const selectedItems: MenuItem[] = [];
this.childItemSet.forEach((childItem) => {
if (childItem.menuData.selectionRoot !== this) return;
if (this.selectedItemsMap.has(childItem)) {
selected.push(childItem.value);
selectedItems.push(childItem);
}
});
this.selected = selected;
this.selectedItems = selectedItems;
this.value = this.selected.join(this.valueSeparator);
} else {
this.selectedItemsMap.clear();
this.selectedItemsMap.set(targetItem, true);
this.value = targetItem.value;
this.selected = [targetItem.value];
this.selectedItems = [targetItem];
}
await this.updateComplete;
const applyDefault = this.dispatchEvent(
new Event('change', {
cancelable: true,
bubbles: true,
composed: true,
})
);
if (!applyDefault) {
// Cancel the event & don't apply the selection
this.selected = oldSelected;
this.selectedItems = oldSelectedItems;
this.selectedItemsMap = oldSelectedItemsMap;
this.value = oldValue;
return;
}
// Apply the selection changes to the menu items
if (resolvedSelects === 'single') {
for (const oldItem of oldSelectedItemsMap.keys()) {
if (oldItem !== targetItem) {
oldItem.selected = false;
}
}
targetItem.selected = true;
} else if (resolvedSelects === 'multiple') {
targetItem.selected = !targetItem.selected;
}
}
public handleKeydown(event: KeyboardEvent): void {
const { code } = event;
if (code === 'Tab') {
this.prepareToCleanUp();
return;
}
if (code === 'Space' || code === 'Enter') {
this.childItems[this.focusedItemIndex]?.click();
return;
}
if (code !== 'ArrowDown' && code !== 'ArrowUp') {
return;
}
const lastFocusedItem = this.childItems[this.focusedItemIndex];
const direction = code === 'ArrowDown' ? 1 : -1;
const itemToFocus = this.focusMenuItemByOffset(direction);
if (itemToFocus === lastFocusedItem) {
return;
}
event.preventDefault();
itemToFocus.scrollIntoView({ block: 'nearest' });
}
public focusMenuItemByOffset(offset: number): MenuItem {
const step = offset || 1;
const focusedItem = this.childItems[this.focusedItemIndex];
focusedItem.focused = false;
this.focusedItemIndex =
(this.childItems.length + this.focusedItemIndex + offset) %
this.childItems.length;
let itemToFocus = this.childItems[this.focusedItemIndex];
let availableItems = this.childItems.length;
// cycle through the available items in the directions of the offset to find the next non-disabled item
while (itemToFocus.disabled && availableItems) {
availableItems -= 1;
this.focusedItemIndex =
(this.childItems.length + this.focusedItemIndex + step) %
this.childItems.length;
itemToFocus = this.childItems[this.focusedItemIndex];
}
// if there are no non-disabled items, skip the work to focus a child
if (!itemToFocus?.disabled) {
this.forwardFocusVisibleToItem(itemToFocus);
}
return itemToFocus;
}
private prepareToCleanUp(): void {
document.addEventListener(
'focusout',
() => {
requestAnimationFrame(() => {
const focusedItem = this.childItems[this.focusedItemIndex];
if (focusedItem) {
focusedItem.focused = false;
this.updateSelectedItemIndex();
}
});
},
{ once: true }
);
}
public updateSelectedItemIndex(): void {
let firstOrFirstSelectedIndex = 0;
const selectedItemsMap = new Map<MenuItem, boolean>();
const selected: string[] = [];
const selectedItems: MenuItem[] = [];
let itemIndex = this.childItems.length;
while (itemIndex) {
itemIndex -= 1;
const childItem = this.childItems[itemIndex];
if (childItem.menuData.selectionRoot === this) {
if (childItem.selected) {
firstOrFirstSelectedIndex = itemIndex;
selectedItemsMap.set(childItem, true);
selected.unshift(childItem.value);
selectedItems.unshift(childItem);
}
// Remove "focused" from non-"selected" items ONLY
// Preserve "focused" on index===0 when no selection
if (itemIndex !== firstOrFirstSelectedIndex) {
childItem.focused = false;
}
}
}
selectedItems.map((item, i) => {
// When there is more than one "selected" item,
// ensure only the first one can be "focused"
if (i > 0) {
item.focused = false;
}
});
this.selectedItemsMap = selectedItemsMap;
this.selected = selected;
this.selectedItems = selectedItems;
this.value = this.selected.join(this.valueSeparator);
this.focusedItemIndex = firstOrFirstSelectedIndex;
this.focusInItemIndex = firstOrFirstSelectedIndex;
}
private _willUpdateItems = false;
private handleItemsChanged(): void {
this.cachedChildItems = undefined;
if (!this._willUpdateItems) {
/* c8 ignore next 3 */
let resolve = (): void => {
return;
};
this.cacheUpdated = new Promise((res) => (resolve = res));
this._willUpdateItems = true;
// Debounce the update so we only update once
// if multiple items have changed
window.requestAnimationFrame(() => {
if (this.cachedChildItems === undefined) {
this.updateSelectedItemIndex();
this.updateItemFocus();
}
this._willUpdateItems = false;
resolve();
});
}
}
private updateItemFocus(): void {
if (this.childItems.length == 0) {
return;
}
const focusInItem = this.childItems[this.focusInItemIndex];
if (
(this.getRootNode() as Document).activeElement ===
focusInItem.menuData.focusRoot
) {
this.forwardFocusVisibleToItem(focusInItem);
}
}
private forwardFocusVisibleToItem(item: MenuItem): void {
if (item.menuData.focusRoot !== this) {
return;
}
const activeElement = (this.getRootNode() as Document).activeElement as
| MenuItem
| Menu;
let shouldFocus = false;
try {
// Browsers without support for the `:focus-visible`
// selector will throw on the following test (Safari, older things).
// Some won't throw, but will be focusing item rather than the menu and
// will rely on the polyfill to know whether focus is "visible" or not.
shouldFocus =
activeElement.matches(':focus-visible') ||
activeElement.matches('.focus-visible');
} catch (error) {
shouldFocus = activeElement.matches('.focus-visible');
}
item.focused = shouldFocus;
this.setAttribute('aria-activedescendant', item.id);
if (
item.menuData.selectionRoot &&
item.menuData.selectionRoot !== this
) {
item.menuData.selectionRoot.focus();
}
}
public render(): TemplateResult {
return html`
<slot></slot>
`;
}
private _notFirstUpdated = false;
protected firstUpdated(changed: PropertyValues): void {
super.firstUpdated(changed);
if (!this.hasAttribute('tabindex')) {
const role = this.getAttribute('role');
if (role === 'group') {
this.tabIndex = -1;
} else if (role !== 'none') {
this.tabIndex = 0;
}
}
const updates: Promise<unknown>[] = [
new Promise((res) => requestAnimationFrame(() => res(true))),
];
[...this.children].forEach((item) => {
if ((item as MenuItem).localName === 'sp-menu-item') {
updates.push((item as MenuItem).updateComplete);
}
});
this.childItemsUpdated = Promise.all(updates);
}
protected updated(changes: PropertyValues<this>): void {
super.updated(changes);
if (changes.has('selects') && this._notFirstUpdated) {
this.selectsChanged();
}
if (changes.has('label')) {
if (this.label) {
this.setAttribute('aria-label', this.label);
} else {
this.removeAttribute('aria-label');
}
}
this._notFirstUpdated = true;
}
protected selectsChanged(): void {
const updates: Promise<unknown>[] = [
new Promise((res) => requestAnimationFrame(() => res(true))),
];
this.childItemSet.forEach((childItem) => {
updates.push(childItem.triggerUpdate());
});
this.childItemsUpdated = Promise.all(updates);
}
public connectedCallback(): void {
super.connectedCallback();
if (!this.hasAttribute('role')) {
this.setAttribute('role', this.ownRole);
}
this.updateComplete.then(() => this.updateItemFocus());
}
protected childItemsUpdated!: Promise<unknown[]>;
protected cacheUpdated = Promise.resolve();
protected async _getUpdateComplete(): Promise<boolean> {
const complete = (await super._getUpdateComplete()) as boolean;
await this.childItemsUpdated;
await this.cacheUpdated;
return complete;
}
} | the_stack |
import {handler, gen_handler} from "../util"
export class loader_mgr
{
private static inst:loader_mgr;
private _loadedRes:Map<string, boolean>;
private _loadedExternalUrls:Map<string, boolean>;
private constructor()
{
this._loadedRes = new Map();
this._loadedExternalUrls = new Map();
}
static get_inst():loader_mgr
{
if(!this.inst)
{
this.inst = new loader_mgr();
}
return this.inst;
}
setExternalSprite(sprite:cc.Sprite, url:string, reActive = false)
{
this.loadExternalAsset(url, gen_handler((tex:cc.Texture2D) => {
if(!sprite || !cc.isValid(sprite.node))
{
cc.loader.release(url);
return;
}
if(reActive)
{
sprite.node.active = true;
}
sprite.spriteFrame = new cc.SpriteFrame(tex);
}));
}
setExternalSpriteFrame(sprite:cc.Sprite, frame:cc.SpriteFrame, url:string, reActive = false)
{
this.loadExternalAsset(url, gen_handler((tex:cc.Texture2D) => {
if(!sprite || !cc.isValid(sprite.node))
{
cc.loader.release(url);
return;
}
if(reActive)
{
sprite.node.active = true;
}
if(cc.isValid(frame))
{
frame.setTexture(tex);
sprite.spriteFrame = frame;
}
}));
}
setSprite(sprite:cc.Sprite, url:string, reActive = false)
{
this.loadRes(url, gen_handler((tex:cc.Texture2D) => {
if(!sprite || !cc.isValid(sprite.node))
{
cc.loader.release(url);
return;
}
if(reActive)
{
sprite.node.active = true;
}
sprite.spriteFrame = new cc.SpriteFrame(tex);
}));
}
setSpriteFrame(sprite:cc.Sprite, frame:cc.SpriteFrame, url:string, reActive = false)
{
this.loadRes(url, gen_handler((tex:cc.Texture2D) => {
if(!sprite || !cc.isValid(sprite.node))
{
cc.loader.release(url);
return;
}
if(reActive)
{
sprite.node.active = true;
}
if(cc.isValid(frame))
{
frame.setTexture(tex);
sprite.spriteFrame = frame;
}
}));
}
setAtlasSprite(sprite:cc.Sprite, atlasUrl:string, spriteFrameName:string, reActive = false)
{
this.loadRes(atlasUrl, gen_handler((atlas:cc.SpriteAtlas) => {
if(!sprite || !cc.isValid(sprite.node))
{
cc.loader.release(atlasUrl);
return;
}
if(reActive)
{
sprite.node.active = true;
}
sprite.spriteFrame = atlas.getSpriteFrame(spriteFrameName);
}), cc.SpriteAtlas);
}
/**从远程url下载资源 */
loadExternalAsset(url:string, cb:handler, type?:string)
{
const res = cc.loader.getRes(url);
if(cc.isValid(res))
{
// console.log("loadExternalAsset from cache");
cb.exec(res);
return;
}
cc.loader.load(type ? {url, type} : url, (err, res) => {
if(err)
{
cc.warn("loadExternalAsset error", url);
return;
}
if(cc.isValid(res)) {
this.cacheExternalAsset(url);
cb.exec(res);
}
});
}
/**从远程url下载资源列表 */
loadExternalAssets(urls:string[], cb:handler, types?:string[])
{
let loaded_res = {};
let unloaded_urls:string[] = [];
urls.forEach(url => {
let res = cc.loader.getRes(url);
if(cc.isValid(res))
{
loaded_res[url] = res;
}
else
{
unloaded_urls.push(url);
}
});
if(unloaded_urls.length == 0)
{
cb.exec(loaded_res);
return;
}
const loadTasks = [];
unloaded_urls.forEach((url, i) => {
types ? loadTasks.push({url, type:types[i]}) : loadTasks.push(url);
})
cc.loader.load(loadTasks, (errs, ress) => {
// cc.log("loadExternalAssets from remote url");
if(errs)
{
cc.warn("loadExternalAssets error", errs);
return;
}
let isValid = true;
unloaded_urls.forEach(url => {
const res = ress.getContent(url);
if(!cc.isValid(res)) {
isValid = false;
return;
}
loaded_res[url] = res;
this.cacheExternalAsset(url);
});
if(isValid) {
cb.exec(loaded_res);
}
});
}
/**从resources目录加载asset*/
loadRes(url:string, cb:handler, assetType?:typeof cc.Asset):void
{
let res = cc.loader.getRes(url, assetType);
if(cc.isValid(res))
{
cb.exec(res);
return;
}
cc.loader.loadRes(url, assetType, (err, res) => {
if(err)
{
cc.warn("loadAsset error", url);
return;
}
if(cc.isValid(res)) {
this.cacheAsset(res);
cb.exec(res);
}
});
}
/**从resources目录加载asset列表,省略资源后缀*/
loadResArray(urls:string[], cb:handler, assetTypes?:typeof cc.Asset[], alias?:string[])
{
//加载同名资源时,需要手动给出不同的别名
let loaded_res = {};
let unloaded_urls:string[] = [];
let unloaded_alias:string[];
let unloaded_types:typeof cc.Asset[];
if(alias)
{
unloaded_alias = [];
}
if(assetTypes)
{
unloaded_types = [];
}
urls.forEach((url, idx) => {
const resType = assetTypes ? assetTypes[idx] : null;
const resAlias = alias ? alias[idx] : null;
const res = cc.loader.getRes(url, resType);
if(cc.isValid(res))
{
loaded_res[resAlias || url] = res;
}
else
{
unloaded_urls.push(url);
if(resType)
{
unloaded_types.push(resType);
}
if(resAlias)
{
unloaded_alias.push(resAlias);
}
}
});
if(unloaded_urls.length == 0)
{
cb.exec(loaded_res);
return;
}
cc.loader.loadResArray(unloaded_urls, unloaded_types, err => {
if(err)
{
cc.warn("loadResArray error", unloaded_urls);
return;
}
let isValid = true;
unloaded_urls.forEach((url, idx) => {
const resType = unloaded_types ? unloaded_types[idx] : null;
const resAlias = unloaded_alias ? unloaded_alias[idx] : null;
const res = cc.loader.getRes(url, resType);
if(!cc.isValid(res)) {
isValid = false;
return;
}
loaded_res[resAlias || url] = res;
this.cacheAsset(res);
});
if(isValid) {
cb.exec(loaded_res);
}
});
}
/**从resources目录加载prefab(省略资源后缀),加载成功后生成prefab实例*/
loadPrefabObj(url:string, cb:handler)
{
let res:cc.Prefab = cc.loader.getRes(url, cc.Prefab);
if(cc.isValid(res))
{
let node:cc.Node = cc.instantiate(res);
cb.exec(node);
return;
}
//err is typeof Error, err.message
cc.loader.loadRes(url, cc.Prefab, (err, res:cc.Prefab) => {
if(err)
{
cc.warn("loadPrefabObj error", url);
return;
}
if(cc.isValid(res)) {
this.cacheAsset(res);
let node:cc.Node = cc.instantiate(res);
cb.exec(node);
}
});
}
/**从resources目录加载prefab列表(省略资源后缀),加载成功后生成prefab实例*/
loadPrefabObjArray(urls:string[], cb:handler)
{
let loaded_obj:any = {};
let unloaded_urls:string[] = [];
urls.forEach((url:string) => {
const res:cc.Prefab = cc.loader.getRes(url, cc.Prefab);
if(cc.isValid(res))
{
loaded_obj[url] = cc.instantiate(res);
}
else
{
unloaded_urls.push(url);
}
});
if(unloaded_urls.length == 0)
{
cb.exec(loaded_obj);
return;
}
cc.loader.loadResArray(unloaded_urls, cc.Prefab, err => {
if(err)
{
cc.warn("loadPrefabObjArray error", unloaded_urls);
return;
}
let isValid = true;
unloaded_urls.forEach(url => {
const res:cc.Prefab = cc.loader.getRes(url, cc.Prefab);
if(!cc.isValid(res)) {
isValid = false;
return;
}
loaded_obj[url] = cc.instantiate(res);
this.cacheAsset(res);
});
if(isValid) {
cb.exec(loaded_obj);
}
});
}
loadPrefabDir(dir_path:string, cb:handler)
{
let map:any = {};
cc.loader.loadResDir(dir_path, cc.Prefab, (err:any, res_arr:any[], urls:string[]) => {
if(err)
{
cc.warn("loadPrefabObjDir error", dir_path);
return;
}
let isValid = true;
urls.forEach(url => {
const res:cc.Prefab = cc.loader.getRes(url, cc.Prefab);
if(!cc.isValid(res)) {
isValid = false;
return;
}
map[url] = res;
this.cacheAsset(res);
});
if(isValid) {
cb.exec(map);
}
});
}
loadPrefabObjDir(dir_path:string, cb:handler):void
{
let map:any = {};
cc.loader.loadResDir(dir_path, cc.Prefab, (err:any, res_arr:any[], urls:string[]) => {
if(err)
{
cc.warn("loadPrefabObjDir error", dir_path);
return;
}
let isValid = true;
urls.forEach(url => {
const res:cc.Prefab = cc.loader.getRes(url, cc.Prefab);
if(!cc.isValid(res)) {
isValid = false;
return;
}
map[url] = cc.instantiate(res);
this.cacheAsset(res);
});
if(isValid) {
cb.exec(map);
}
});
}
private cacheAsset(asset:cc.Asset)
{
if(cc.isValid(asset)) {
const key:string = cc.loader._getReferenceKey(asset);
if(key) {
this._loadedRes.set(key, true);
}
}
}
private cacheExternalAsset(url:string)
{
this._loadedExternalUrls.set(url, true);
}
releaseAll(excludeMap = null)
{
const leftRes:Map<string, boolean> = new Map();
this._loadedRes.forEach((_, res) => {
const deps = cc.loader.getDependsRecursively(res);
deps.forEach(d => {
if(!d) {
return;
}
// cc.log(`loaderMgr release loadedRes, dep=${d}, exclude=${excludeMap ? excludeMap[d] : false}`);
if(!excludeMap || !excludeMap[d]) {
cc.loader.release(d);
}
else {
leftRes.set(d, true);
}
});
});
this._loadedRes.clear();
leftRes.forEach((_, d) => {
this._loadedRes.set(d, true);
});
//释放外部资源
this._loadedExternalUrls.forEach((_, url) => {
// cc.log(`loaderMgr release loadedExternalRes, url=${url}`);
cc.loader.release(url);
});
this._loadedExternalUrls.clear();
cc.sys.garbageCollect();
// this.dump();
}
dump()
{
cc.log(`---------------------loader_mgr dump begin--------------------------`);
const cache = cc.loader._cache;
let count = 0;
for(let id in cache)
{
count++;
cc.log(`id=${id}, value=${cache[id]}`);
}
cc.log(`---------------------loader_mgr dump end, totalCount=${count}--------------------------`);
}
} | the_stack |
import { AuthenticationProviderOptions } from '@microsoft/microsoft-graph-client/lib/es/IAuthenticationProviderOptions';
import { Configuration, InteractionRequiredAuthError, SilentRequest } from '@azure/msal-browser';
import { LoginType, ProviderState, TeamsHelper } from '@microsoft/mgt-element';
import { Msal2Provider, PromptType } from '@microsoft/mgt-msal2-provider';
// tslint:disable-next-line: completed-docs
declare global {
// tslint:disable-next-line: completed-docs
interface Window {
// tslint:disable-next-line: completed-docs
nativeInterface: any;
}
}
/**
* Enumeration to define if we are using get or post
*
* @export
* @enum {string}
*/
export enum HttpMethod {
/**
* Will use Get and the querystring
*/
GET = 'GET',
/**
* Will use Post and the request body
*/
POST = 'POST'
}
/**
* Interface used to store authentication parameters in session storage
* between redirects
*
* @interface AuthParams
*/
interface AuthParams {
/**
* The app clientId
*
* @type {string}
* @memberof AuthParams
*/
clientId?: string;
/**
* The comma separated scopes
*
* @type {string}
* @memberof AuthParams
*/
scopes?: string;
/**
* The login hint to be used for authentication
*
* @type {string}
* @memberof AuthParams
*/
loginHint?: string;
/**
* Additional Msal configurations options to use
* See Msal.js documentation for more details
*
* @type {Configuration}
* @memberof AuthParams
*/
options?: Configuration;
/**
* The login hint to be used for authentication
*
* @type {string}
* @memberof AuthParams
*/
isConsent?: boolean;
}
/**
* Interface to define the configuration when creating a TeamsMsal2Provider
*
* @export
* @interface TeamsMsal2Config
*/
export interface TeamsMsal2Config {
/**
* The app clientId
*
* @type {string}
* @memberof TeamsMsal2Config
*/
clientId: string;
/**
* The relative or absolute path of the html page that will handle the authentication
*
* @type {string}
* @memberof TeamsMsal2Config
*/
authPopupUrl: string;
/**
* The scopes to use when authenticating the user
*
* @type {string[]}
* @memberof TeamsMsal2Config
*/
scopes?: string[];
/**
* Additional Msal configurations options to use
* See Msal.js documentation for more details
*
* @type {Configuration}
* @memberof TeamsMsal2Config
*/
msalOptions?: Configuration;
/**
* The relative or absolute path to the token exchange backend service
*
* @type {string}
* @memberof TeamsMsal2Config
*/
ssoUrl?: string;
/**
* Should the provider display a consent popup automatically if needed
*
* @type {string}
* @memberof TeamsMsal2Config
*/
autoConsent?: boolean;
/**
* Should the provider display a consent popup automatically if needed
*
* @type {AuthMethod}
* @memberof TeamsMsal2Config
*/
httpMethod?: HttpMethod;
}
/**
* Enables authentication of Single page apps inside of a Microsoft Teams tab
*
* @export
* @class TeamsMsal2Provider
* @extends {Msal2Provider}
*/
export class TeamsMsal2Provider extends Msal2Provider {
/**
* Gets whether the Teams provider can be used in the current context
* (Whether the app is running in Microsoft Teams)
*
* @readonly
* @static
* @memberof TeamsMsal2Provider
*/
public static get isAvailable(): boolean {
return TeamsHelper.isAvailable;
}
/**
* Optional entry point to the teams library
* If this value is not set, the provider will attempt to use
* the microsoftTeams global variable.
*
* @static
* @memberof TeamsMsal2Provider
*/
public static get microsoftTeamsLib(): any {
return TeamsHelper.microsoftTeamsLib;
}
public static set microsoftTeamsLib(value: any) {
TeamsHelper.microsoftTeamsLib = value;
}
/**
* Name used for analytics
*
* @readonly
* @memberof IProvider
*/
public get name() {
return 'MgtTeamsMsal2Provider';
}
/**
* Handle all authentication redirects in the authentication page and authenticates the user
*
* @static
* @returns
* @memberof TeamsMsal2Provider
*/
public static async handleAuth() {
// we are in popup world now - authenticate and handle it
const teams = TeamsHelper.microsoftTeamsLib;
if (!teams) {
// tslint:disable-next-line: no-console
console.error('Make sure you have referenced the Microsoft Teams sdk before using the TeamsMsal2Provider');
return;
}
teams.initialize();
// if we were signing out before, then we are done
if (sessionStorage.getItem(this._sessionStorageLogoutInProgress)) {
teams.authentication.notifySuccess();
}
const url = new URL(window.location.href);
const isSignOut = url.searchParams.get('signout');
const paramsString = localStorage.getItem(this._localStorageParametersKey);
let authParams: AuthParams;
if (paramsString) {
authParams = JSON.parse(paramsString);
} else {
authParams = {};
}
if (!authParams.clientId) {
teams.authentication.notifyFailure('no clientId provided');
return;
}
const scopes = authParams.scopes ? authParams.scopes.split(',') : null;
const prompt = authParams.isConsent ? PromptType.CONSENT : PromptType.SELECT_ACCOUNT;
const options = authParams.options || { auth: { clientId: authParams.clientId } };
options.system = options.system || {};
options.system.loadFrameTimeout = 10000;
const provider = new Msal2Provider({
clientId: authParams.clientId,
options,
scopes,
loginHint: authParams.loginHint,
prompt: prompt
});
const handleProviderState = async () => {
// how do we handle when user can't sign in
// change to promise and return status
if (provider.state === ProviderState.SignedOut) {
if (isSignOut) {
teams.authentication.notifySuccess();
return;
}
// make sure we are calling login only once
if (!sessionStorage.getItem(this._sessionStorageLoginInProgress)) {
sessionStorage.setItem(this._sessionStorageLoginInProgress, 'true');
provider.login();
}
} else if (provider.state === ProviderState.SignedIn) {
if (isSignOut) {
sessionStorage.setItem(this._sessionStorageLogoutInProgress, 'true');
await provider.logout();
return;
}
try {
const accessToken = await provider.getAccessTokenForScopes(...provider.scopes);
teams.authentication.notifySuccess(accessToken);
} catch (e) {
teams.authentication.notifyFailure(e);
}
}
};
provider.onStateChanged(handleProviderState);
handleProviderState();
}
protected clientId: string;
private static _localStorageParametersKey = 'msg-TeamsMsal2Provider-auth-parameters';
private static _sessionStorageLoginInProgress = 'msg-TeamsMsal2Provider-login-in-progress';
private static _sessionStorageLogoutInProgress = 'msg-TeamsMsal2Provider-logout-in-progress';
private teamsContext;
private _authPopupUrl: string;
private _msalOptions: Configuration;
private _ssoUrl: string;
private _needsConsent: boolean;
private _autoConsent: boolean;
private _httpMethod: HttpMethod;
constructor(config: TeamsMsal2Config) {
super({
clientId: config.clientId,
loginType: LoginType.Redirect,
options: config.msalOptions,
scopes: config.scopes
});
this.clientId = config.clientId;
this._msalOptions = config.msalOptions;
this._authPopupUrl = config.authPopupUrl;
this._ssoUrl = config.ssoUrl;
this._autoConsent = typeof config.autoConsent !== 'undefined' ? config.autoConsent : true;
this._httpMethod = typeof config.httpMethod !== 'undefined' ? config.httpMethod : HttpMethod.GET;
const teams = TeamsHelper.microsoftTeamsLib;
teams.initialize();
// If we are in SSO-mode.
if (this._ssoUrl) {
this.internalLogin();
}
}
/**
* Opens the teams authentication popup to the authentication page
*
* @returns {Promise<void>}
* @memberof TeamsMsal2Provider
*/
public async login(): Promise<void> {
// In SSO mode the login should not be able to be run via user click
// this method is called from the SSO internal login process if we need to consent
if (this._ssoUrl && !this._needsConsent) {
return;
}
this.setState(ProviderState.Loading);
const teams = TeamsHelper.microsoftTeamsLib;
return new Promise((resolve, reject) => {
teams.getContext(context => {
this.teamsContext = context;
const authParams: AuthParams = {
clientId: this.clientId,
loginHint: context.loginHint,
options: this._msalOptions,
scopes: this.scopes.join(','),
isConsent: this._autoConsent
};
localStorage.setItem(TeamsMsal2Provider._localStorageParametersKey, JSON.stringify(authParams));
const url = new URL(this._authPopupUrl, new URL(window.location.href));
teams.authentication.authenticate({
failureCallback: reason => {
this.setState(ProviderState.SignedOut);
reject();
},
successCallback: result => {
// If we are in SSO Mode, the consent has been successful. Consider logged in
if (this._ssoUrl) {
this.setState(ProviderState.SignedIn);
resolve();
} else {
// Otherwise log in via MSAL
this.trySilentSignIn();
resolve();
}
},
url: url.href
});
});
});
}
/**
* sign out user
*
* @returns {Promise<void>}
* @memberof MsalProvider
*/
public async logout(): Promise<void> {
// In SSO mode the logout should not be able to be run at all
if (this._ssoUrl) {
return;
}
const teams = TeamsHelper.microsoftTeamsLib;
return new Promise((resolve, reject) => {
teams.getContext(context => {
this.teamsContext = context;
const url = new URL(this._authPopupUrl, new URL(window.location.href));
url.searchParams.append('signout', 'true');
teams.authentication.authenticate({
failureCallback: reason => {
this.trySilentSignIn();
reject();
},
successCallback: result => {
this.trySilentSignIn();
resolve();
},
url: url.href
});
});
});
}
/**
* Returns an access token that can be used for making calls to the Microsoft Graph
*
* @param {AuthenticationProviderOptions} options
* @returns {Promise<string>}
* @memberof TeamsMsal2Provider
*/
public async getAccessToken(options: AuthenticationProviderOptions): Promise<string> {
if (!this.teamsContext && TeamsHelper.microsoftTeamsLib) {
const teams = TeamsHelper.microsoftTeamsLib;
teams.initialize();
this.teamsContext = await teams.getContext();
}
const scopes = options ? options.scopes || this.scopes : this.scopes;
// If we are in SSO Mode
if (this._ssoUrl) {
// Get token via the Teams SDK
const clientToken = await this.getClientToken();
let url: URL = new URL(this._ssoUrl, new URL(window.location.href));
let response: Response;
// Use GET and Query String
if (this._httpMethod === HttpMethod.GET) {
const params = new URLSearchParams({
ssoToken: clientToken,
scopes: scopes.join(','),
clientId: this.clientId
});
response = await fetch(`${url.href}?${params}`, {
method: 'GET',
mode: 'cors',
cache: 'default'
});
}
// Use POST and body
else {
response = await fetch(url.href, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
authorization: `Bearer ${clientToken}`
},
body: JSON.stringify({
scopes: scopes,
clientid: this.clientId
}),
mode: 'cors',
cache: 'default'
});
}
// Exchange token from server
const data = await response.json().catch(this.unhandledFetchError);
if (!response.ok && data.error === 'consent_required') {
// A consent_required error means the user must consent to the requested scope, or use MFA
// If we are in the log in process, display a dialog
this._needsConsent = true;
} else if (!response.ok) {
throw data;
} else {
this._needsConsent = false;
return data.access_token;
}
}
// If we are not in SSO Mode and using the Login component
else {
return new Promise(async (resolve, reject) => {
const accessTokenRequest: SilentRequest = {
scopes: scopes,
account: this.getAccount()
};
try {
const response = await this.publicClientApplication.acquireTokenSilent(accessTokenRequest);
// return response.accessToken;
resolve(response.accessToken);
} catch (e) {
if (e instanceof InteractionRequiredAuthError) {
// nothing we can do now until we can do incremental consent
// return null;
resolve(null);
} else {
// throw e;
reject(e);
}
}
});
}
}
/**
* Makes sure we can get an access token before considered logged in
*
* @returns {Promise<void>}
* @memberof TeamsMsal2Provider
*/
private async internalLogin(): Promise<void> {
// Try to get access token
const accessToken: string = await this.getAccessToken(null);
// If we have an access token. Consider the user signed in
if (accessToken) {
this.setState(ProviderState.SignedIn);
} else {
// If we need to consent to additional scopes
if (this._needsConsent) {
// If autoconsent is configured. Display a popup where the user can consent
if (this._autoConsent) {
// We need to pass the scopes from the client side
if (!this.scopes) {
throw new Error('For auto consent, scopes must be provided');
} else {
this.login();
return;
}
} else {
throw new Error('Auto consent is not configured. You need to consent to additional scopes');
}
}
}
}
/**
* Get a token via the Teams SDK
*
* @returns {Promise<string>}
* @memberof TeamsMsal2Provider
*/
private async getClientToken(): Promise<string> {
const teams = TeamsHelper.microsoftTeamsLib;
return new Promise((resolve, reject) => {
teams.authentication.getAuthToken({
successCallback: (result: string) => {
resolve(result);
},
failureCallback: reason => {
this.setState(ProviderState.SignedOut);
reject();
}
});
});
}
private unhandledFetchError(err: any) {
console.error(`There was an error during the server side token exchange: ${err}`);
}
} | the_stack |
import { expect } from 'chai';
import * as sinon from 'sinon';
import { cloneDeep } from 'lodash';
import * as fsAsync from '../../src/common/fsAsync';
import * as os from 'os';
import * as path from 'path';
import {
IVSCodeManager,
IConfigManager,
IVSIcons,
ConfigurationTarget,
PresetNames,
} from '../../src/models';
import { constants } from '../../src/constants';
import { Utils } from '../../src/utils';
import { ErrorHandler } from '../../src/common/errorHandler';
import { ConfigManager } from '../../src/configuration/configManager';
import { VSCodeManager } from '../../src/vscode/vscodeManager';
import { vsicons } from '../fixtures/vsicons';
describe('ConfigManager: tests', function () {
context('ensures that', function () {
let sandbox: sinon.SinonSandbox;
let vscodeManagerStub: sinon.SinonStubbedInstance<IVSCodeManager>;
let readdirAsyncStub: sinon.SinonStub;
let envStub: sinon.SinonStub;
let updateFileStub: sinon.SinonStub;
let logErrorStub: sinon.SinonStub;
let dirnameStub: sinon.SinonStub;
let getStub: sinon.SinonStub;
let getConfigurationStub: sinon.SinonStub;
let inspectStub: sinon.SinonStub;
let updateStub: sinon.SinonStub;
let pathUnixJoinStub: sinon.SinonStub;
let vsiconsClone: IVSIcons;
let configManager: IConfigManager;
let splitter: (content: string) => string[];
beforeEach(function () {
sandbox = sinon.createSandbox();
readdirAsyncStub = sandbox.stub(fsAsync, 'readdirAsync');
envStub = sandbox.stub(process, 'env');
logErrorStub = sandbox.stub(ErrorHandler, 'logError');
updateFileStub = sandbox.stub(Utils, 'updateFile');
pathUnixJoinStub = sandbox.stub(Utils, 'pathUnixJoin');
sandbox.stub(Utils, 'getAppDataDirPath');
// This is an effective way to stub '__dirname'
// but requires that the code uses `path.dirname(__filename)` instead
dirnameStub = sandbox.stub(path, 'dirname');
envStub.value({
VSCODE_CWD: '/VSCode/Path/Insiders/To/OSS/Installation/Dev/Dir',
});
vscodeManagerStub = sandbox.createStubInstance<IVSCodeManager>(
VSCodeManager,
);
getStub = sandbox.stub();
inspectStub = sandbox.stub().returns({
globalValue: undefined,
workspaceValue: undefined,
});
updateStub = sandbox.stub().resolves();
vsiconsClone = cloneDeep(vsicons);
getConfigurationStub = sandbox.stub().returns({
vsicons: vsiconsClone,
get: getStub,
inspect: inspectStub,
update: updateStub,
});
sandbox.stub(vscodeManagerStub, 'workspace').get(() => ({
getConfiguration: getConfigurationStub,
}));
configManager = new ConfigManager(vscodeManagerStub);
splitter = (content: string): string[] => content.split('\n');
dirnameStub.returns(
`/path/to/.vscode/extensions/${constants.extension.name}-1.0.0`,
);
readdirAsyncStub.resolves([`${constants.extension.name}-1.0.0`]);
});
afterEach(function () {
vsiconsClone = null;
configManager = null;
sandbox.restore();
});
context(`function 'rootDir'`, function () {
let originalRootDir: string;
beforeEach(function () {
dirnameStub.returns('/path/to/filename');
originalRootDir = ConfigManager.rootDir;
});
afterEach(function () {
ConfigManager.rootDir = originalRootDir;
});
context(`returns the 'root' directory`, function () {
const regexp = /^[a-zA-Z:\\]+|\//;
it(`by default`, function () {
expect(ConfigManager.rootDir).to.match(regexp);
});
context(`when assigned one is`, function () {
it(`an empty string`, function () {
ConfigManager.rootDir = '';
expect(ConfigManager.rootDir).to.match(regexp);
});
it(`'undefined'`, function () {
ConfigManager.rootDir = undefined;
expect(ConfigManager.rootDir).to.match(regexp);
});
it(`'null'`, function () {
ConfigManager.rootDir = null;
expect(ConfigManager.rootDir).to.match(regexp);
});
});
});
it(`returns the assigned 'root' directory`, function () {
const assignedDir = '/path';
ConfigManager.rootDir = assignedDir;
expect(ConfigManager.rootDir).to.equal(assignedDir);
});
});
context(`function 'outDir'`, function () {
it(`returns the 'out' directory`, function () {
const baseRegexp = `^[a-zA-Z:\\\\]+|/`;
expect(ConfigManager.outDir).to.match(
new RegExp(`${baseRegexp}${constants.extension.outDirName}`),
);
});
});
context(`function 'sourceDir'`, function () {
it(`returns the 'source' directory`, function () {
const baseRegexp = `^[a-zA-Z:\\\\]+|/`;
expect(ConfigManager.sourceDir).to.match(
new RegExp(
`${baseRegexp}${constants.extension.outDirName}[\\\\|/]${constants.extension.srcDirName}`,
),
);
});
});
context(`function 'iconsDir'`, function () {
it(`returns the 'icons' directory`, function () {
const baseRegexp = `^[a-zA-Z:\\\\]+|/`;
expect(ConfigManager.iconsDir).to.match(
new RegExp(`${baseRegexp}${constants.extension.iconsDirName}`),
);
});
});
context(`function 'vsicons'`, function () {
const fixture1 = {
icon: 'js',
extensions: ['myExt1', 'myExt2.custom.js'],
format: 'svg',
};
const fixture2 = {
icon: 'js2',
extensions: ['myExt1', 'myExt2.custom.js'],
format: 'svg',
};
const fixture3 = {
icon: 'js',
extensions: ['myExt', 'myExt2.custom.js'],
format: 'svg',
};
context(`returns for files:`, function () {
it(`the 'globalValue', if no 'workspaceValue' present`, function () {
inspectStub.onThirdCall().returns({
globalValue: [fixture1],
});
vsiconsClone.associations.files = [fixture1];
// make 'readonly' as 'vscode' config objects are immutable
Object.freeze(vsiconsClone.associations);
expect(configManager.vsicons).to.eqls(vsiconsClone);
});
it(`the 'globalValue', if 'workspaceValue' is an empty array`, function () {
inspectStub.onThirdCall().returns({
globalValue: [fixture1],
workspaceValue: [],
});
vsiconsClone.associations.files = [fixture1];
// make 'readonly' as 'vscode' config objects are immutable
Object.freeze(vsiconsClone.associations);
expect(configManager.vsicons).to.eqls(vsiconsClone);
});
it(`both 'workspaceValue' and 'globalValue' settings`, function () {
inspectStub.onThirdCall().returns({
globalValue: [fixture2],
workspaceValue: [fixture1],
});
vsiconsClone.associations.files = [fixture1, fixture2];
// make 'readonly' as 'vscode' config objects are immutable
Object.freeze(vsiconsClone.associations);
expect(configManager.vsicons).to.eqls(vsiconsClone);
});
it(`both 'workspaceValue' and 'globalValue' settings, removing duplicates`, function () {
inspectStub.onThirdCall().returns({
globalValue: [fixture3],
workspaceValue: [fixture2, fixture3],
});
vsiconsClone.associations.files = [fixture2, fixture3];
// make 'readonly' as 'vscode' config objects are immutable
Object.freeze(vsiconsClone.associations);
expect(configManager.vsicons).to.eql(vsiconsClone);
});
});
context(`returns for folders:`, function () {
it(`the 'globalValue', if no 'workspaceValue' present`, function () {
inspectStub.onCall(3).returns({
globalValue: [fixture1],
});
vsiconsClone.associations.folders = [fixture1];
// make 'readonly' as 'vscode' config objects are immutable
Object.freeze(vsiconsClone.associations);
expect(configManager.vsicons).to.eqls(vsiconsClone);
});
it(`the 'globalValue', if 'workspaceValue' is an empty array`, function () {
inspectStub.onCall(3).returns({
globalValue: [fixture1],
workspaceValue: [],
});
vsiconsClone.associations.folders = [fixture1];
// make 'readonly' as 'vscode' config objects are immutable
Object.freeze(vsiconsClone.associations);
expect(configManager.vsicons).to.eqls(vsiconsClone);
});
it(`both 'workspaceValue' and 'globalValue' settings`, function () {
inspectStub.onCall(3).returns({
globalValue: [fixture2],
workspaceValue: [fixture1],
});
vsiconsClone.associations.folders = [fixture1, fixture2];
// make 'readonly' as 'vscode' config objects are immutable
Object.freeze(vsiconsClone.associations);
expect(configManager.vsicons).to.eqls(vsiconsClone);
});
it(`both 'workspaceValue' and 'globalValue' settings, removing duplicates`, function () {
inspectStub.onCall(3).returns({
globalValue: [fixture3],
workspaceValue: [fixture2, fixture3],
});
vsiconsClone.associations.folders = [fixture2, fixture3];
// make 'readonly' as 'vscode' config objects are immutable
Object.freeze(vsiconsClone.associations);
expect(configManager.vsicons).to.eqls(vsiconsClone);
});
});
});
context(`function 'removeSettings'`, function () {
context(`does NOT update 'vscode' the settings file`, function () {
it('on extension update', async function () {
readdirAsyncStub.resolves([
`${constants.extension.name}-1.0.0`,
`${constants.extension.name}-1.1.0`,
]);
updateFileStub.callsArgWith(1, ['']).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.called).to.be.false;
});
});
context(`updates the 'vscode' settings file`, function () {
it('on extension full uninstall', async function () {
updateFileStub.callsArgWith(1, ['']).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
});
});
it('logs an Error message when updating the file fails', async function () {
const error = new Error();
updateFileStub.rejects(error);
await ConfigManager.removeSettings();
expect(logErrorStub.calledOnceWithExactly(error)).to.be.true;
});
});
context(`function 'getAppUserPath'`, function () {
context('returns the correct path', function () {
context('when the process platform is', function () {
let appPath: string;
let dirPath: string;
let platformStub: sinon.SinonStub;
beforeEach(() => {
platformStub = sandbox.stub(process, 'platform');
updateFileStub.callsArgWith(1, ['']).resolves();
});
context('*nix', function () {
beforeEach(() => {
appPath = '/var/local';
dirPath = `${appPath}/%appDir%/extensions`;
platformStub.value('freebsd');
});
context(`and extension's installed directory is`, function () {
it('in portable mode', async function () {
const userPath = `${process.env.VSCODE_CWD}/data/user-data/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', 'data'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('freebsd');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.vscode'`, async function () {
const userPath = `${appPath}/Code/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', '.vscode'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('freebsd');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.vscode-insiders'`, async function () {
const userPath = `${appPath}/Code - Insiders/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(
dirPath.replace('%appDir%', '.vscode-insiders'),
);
await ConfigManager.removeSettings();
expect(process.platform).to.equal('freebsd');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.code-oss-dev'`, async function () {
const userPath = `${appPath}/code-oss-dev/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(
dirPath.replace('%appDir%', '.vscode-oss-dev'),
);
await ConfigManager.removeSettings();
expect(process.platform).to.equal('freebsd');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.code-oss'`, async function () {
const userPath = `${appPath}/Code - OSS/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', '.vscode-oss'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('freebsd');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
});
});
context('linux', function () {
beforeEach(() => {
sandbox.stub(os, 'homedir').returns('/home/user');
appPath = `${os.homedir()}/.config`;
dirPath = `${os.homedir()}/%appDir%/extensions`;
platformStub.value('linux');
});
context(`and extension's installed directory is`, function () {
it('in portable mode', async function () {
const userPath = `${process.env.VSCODE_CWD}/data/user-data/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', 'data'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('linux');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.vscode'`, async function () {
const userPath = `${appPath}/Code/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', '.vscode'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('linux');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.vscode-insiders'`, async function () {
const userPath = `${appPath}/Code - Insiders/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(
dirPath.replace('%appDir%', '.vscode-insiders'),
);
await ConfigManager.removeSettings();
expect(process.platform).to.equal('linux');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.code-oss-dev'`, async function () {
const userPath = `${appPath}/code-oss-dev/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(
dirPath.replace('%appDir%', '.vscode-oss-dev'),
);
await ConfigManager.removeSettings();
expect(process.platform).to.equal('linux');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.code-oss'`, async function () {
const userPath = `${appPath}/Code - OSS/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', '.vscode-oss'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('linux');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
});
});
context('darwin (macOS)', function () {
beforeEach(() => {
sandbox.stub(os, 'homedir').returns('/Users/User');
appPath = `${os.homedir()}/Library/Application Support`;
dirPath = `${os.homedir()}/%appDir%/extensions`;
platformStub.value('darwin');
});
context(`and extension's installed directory is`, function () {
context('in portable mode', function () {
it(`of 'vscode'`, async function () {
const userPath = `${process.env.VSCODE_CWD}/code-portable-data/user-data/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', 'data'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('darwin');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`of 'vscode-insiders'`, async function () {
sandbox.stub(fsAsync, 'existsAsync').resolves(true);
const userPath = `${process.env.VSCODE_CWD}/code-insiders-portable-data/user-data/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', 'data'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('darwin');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
});
it(`'.vscode'`, async function () {
const userPath = `${appPath}/Code/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', '.vscode'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('darwin');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.vscode-insiders'`, async function () {
const userPath = `${appPath}/Code - Insiders/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(
dirPath.replace('%appDir%', '.vscode-insiders'),
);
await ConfigManager.removeSettings();
expect(process.platform).to.equal('darwin');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.code-oss-dev'`, async function () {
const userPath = `${appPath}/code-oss-dev/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(
dirPath.replace('%appDir%', '.vscode-oss-dev'),
);
await ConfigManager.removeSettings();
expect(process.platform).to.equal('darwin');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.code-oss'`, async function () {
const userPath = `${appPath}/Code - OSS/User`;
const expected = new RegExp(`^${userPath}`);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', '.vscode-oss'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('darwin');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
});
});
context('win32 (windows)', function () {
beforeEach(() => {
dirPath = 'C:\\Users\\User\\%appDir%\\extensions';
platformStub.value('win32');
envStub.value({
APPDATA: 'C:\\Users\\User\\AppData\\Roaming',
VSCODE_CWD:
'D:\\VSCode\\Path\\Insiders\\To\\OSS\\Installation\\Dev\\Dir',
});
});
context(`and extension's installed directory is`, function () {
it('in portable mode', async function () {
const userPath = `${process.env.VSCODE_CWD}/data/user-data/User`;
const expected = new RegExp(
`^${userPath.replace(/\\/g, '\\\\')}`,
);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', 'data'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('win32');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.vscode' `, async function () {
const userPath = `${process.env.APPDATA}/Code/User`;
const expected = new RegExp(
`^${userPath.replace(/\\/g, '\\\\')}`,
);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', '.vscode'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('win32');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.vscode-insiders'`, async function () {
const userPath = `${process.env.APPDATA}/Code - Insiders/User`;
const expected = new RegExp(
`^${userPath.replace(/\\/g, '\\\\')}`,
);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(
dirPath.replace('%appDir%', '.vscode-insiders'),
);
await ConfigManager.removeSettings();
expect(process.platform).to.equal('win32');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.code-oss-dev'`, async function () {
const userPath = `${process.env.APPDATA}/code-oss-dev/User`;
const expected = new RegExp(
`^${userPath.replace(/\\/g, '\\\\')}`,
);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(
dirPath.replace('%appDir%', '.vscode-oss-dev'),
);
await ConfigManager.removeSettings();
expect(process.platform).to.equal('win32');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
it(`'.code-oss'`, async function () {
const userPath = `${process.env.APPDATA}/Code - OSS/User`;
const expected = new RegExp(
`^${userPath.replace(/\\/g, '\\\\')}`,
);
pathUnixJoinStub.returns(userPath);
dirnameStub.returns(dirPath.replace('%appDir%', '.vscode-oss'));
await ConfigManager.removeSettings();
expect(process.platform).to.equal('win32');
expect(updateFileStub.firstCall.args[0]).to.match(expected);
});
});
});
});
});
});
context(`function 'isSingleInstallation'`, function () {
let isSingleInstallationSpy: sinon.SinonSpy;
beforeEach(() => {
isSingleInstallationSpy = sandbox.spy(
ConfigManager,
// @ts-ignore
'isSingleInstallation',
);
});
it(`to return 'true' on a single installation`, async function () {
readdirAsyncStub.resolves([`${constants.extension.name}-1.1.0`]);
updateFileStub.resolves();
await ConfigManager.removeSettings();
expect(isSingleInstallationSpy.calledOnce).to.be.true;
expect(await isSingleInstallationSpy.firstCall.returnValue).to.be.true;
});
it(`to return 'false' on multiple installations`, async function () {
readdirAsyncStub.resolves([
`${constants.extension.name}-2.0.0`,
`${constants.extension.name}-2.1.0`,
]);
await ConfigManager.removeSettings();
expect(isSingleInstallationSpy.calledOnce).to.be.true;
expect(await isSingleInstallationSpy.firstCall.returnValue).to.be.false;
});
});
context(`function 'removeVSIconsConfigs'`, function () {
let removeVSIconsConfigsSpy: sinon.SinonSpy;
beforeEach(() => {
removeVSIconsConfigsSpy = sandbox.spy(
ConfigManager,
// @ts-ignore
'removeVSIconsConfigs',
);
});
context(`to maintain comments and`, function () {
it(`to remove a 'vsicons' configuration when it is last`, async function () {
const content: string[] = splitter(
'{\n"updateChannel": "none",\n' +
'\\\\ Comments\n' +
`"${constants.vsicons.dontShowNewVersionMessageSetting}": true\n}`,
);
const expected: string[] = splitter(
`{\n"updateChannel": "none",\n\\\\ Comments\n}`,
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeVSIconsConfigsSpy.calledOnce).to.be.true;
expect(removeVSIconsConfigsSpy.returned(expected)).to.be.true;
});
it(`to remove a 'vsicons' configuration when it is first`, async function () {
const content = splitter(
`{\n"${constants.vsicons.dontShowNewVersionMessageSetting}": true,\n` +
'\\\\ Comments\n' +
'"window.zoomLevel": 0,\n"updateChannel": "none"\n}',
);
const expected = splitter(
`{\n\\\\ Comments\n"window.zoomLevel": 0,\n"updateChannel": "none"\n}`,
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeVSIconsConfigsSpy.calledOnce).to.be.true;
expect(removeVSIconsConfigsSpy.returned(expected)).to.be.true;
});
it(`to remove a 'vsicons' configuration when it is in between`, async function () {
const content = splitter(
'{\n"window.zoomLevel": 0,\n' +
'\\\\ Comments\n' +
`"${constants.vsicons.dontShowNewVersionMessageSetting}": true,\n` +
'"updateChannel": "none"\n}',
);
const expected = splitter(
`{\n"window.zoomLevel": 0,\n\\\\ Comments\n"updateChannel": "none"\n}`,
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeVSIconsConfigsSpy.calledOnce).to.be.true;
expect(removeVSIconsConfigsSpy.returned(expected)).to.be.true;
});
it(`to remove multiple 'vsicons' settings`, async function () {
const content = splitter(
'{\n' +
' "window.zoomLevel": 0,\n' +
' \\\\ Comments\n' +
` "${constants.vsicons.dontShowNewVersionMessageSetting}": true,\n` +
` "${constants.vsicons.presets.angular}": true,\n` +
' "updateChannel": "none"\n' +
'}',
);
const expected = splitter(
`{\n "window.zoomLevel": 0,\n \\\\ Comments\n "updateChannel": "none"\n}`,
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeVSIconsConfigsSpy.calledOnce).to.be.true;
expect(removeVSIconsConfigsSpy.returned(expected)).to.be.true;
});
it(`to remove 'vsicons' settings of 'object' type`, async function () {
const content = splitter(
'{\n' +
' "window.zoomLevel": 0,\n' +
' \\\\ Comments\n' +
` "${constants.vsicons.associations.defaultFileSetting}": {\n` +
' \\\\ Comments\n' +
' "icon": "ts",\n' +
' "extensions": ["extone"],\n' +
' "format": "svg"\n' +
' }\n' +
'}',
);
const expected = splitter(
`{\n "window.zoomLevel": 0,\n \\\\ Comments\n}`,
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeVSIconsConfigsSpy.calledOnce).to.be.true;
expect(removeVSIconsConfigsSpy.returned(expected)).to.be.true;
});
context(`to remove 'vsicons' settings of 'array' type`, function () {
it(`when the trailing character is '['`, async function () {
const content = splitter(
'{\n' +
' "window.zoomLevel": 0,\n' +
' \\\\ Comments\n' +
` "${constants.vsicons.associations.filesSetting}": [\n` +
' \\\\ Comments\n' +
' {\n' +
' "icon": "one",\n' +
' "extensions": ["extone"],\n' +
' "format": "svg"\n' +
' }\n' +
'],\n' +
'}',
);
const expected = splitter(
`{\n "window.zoomLevel": 0,\n \\\\ Comments\n}`,
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeVSIconsConfigsSpy.calledOnce).to.be.true;
expect(removeVSIconsConfigsSpy.returned(expected)).to.be.true;
});
it(`when the trailing character is '[{'`, async function () {
const content = splitter(
'{\n' +
' "window.zoomLevel": 0,\n' +
' \\\\ Comments\n' +
` "${constants.vsicons.associations.filesSetting}": [{\n` +
' "icon": "one",\n' +
' "extensions": ["extone"],\n' +
' "format": "svg"\n' +
' },\n' +
' {\n' +
' "icon": "two",\n' +
' "extensions": ["extone", "exttwo"],\n' +
' "format": "svg"\n' +
' },\n' +
' {\n' +
' "icon": "three",\n' +
' "extensions": ["extone"],\n' +
' "format": "svg"\n' +
' },\n' +
' ],\n' +
'}',
);
const expected = splitter(
`{\n "window.zoomLevel": 0,\n \\\\ Comments\n}`,
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeVSIconsConfigsSpy.calledOnce).to.be.true;
expect(removeVSIconsConfigsSpy.returned(expected)).to.be.true;
});
});
});
});
context(`function 'resetIconTheme'`, function () {
let resetIconThemeSpy: sinon.SinonSpy;
beforeEach(() => {
resetIconThemeSpy = sandbox.spy(
ConfigManager,
// @ts-ignore
'resetIconTheme',
);
});
context(`does reset the 'iconTheme' configuration`, function () {
it(`if it was set to 'vscode-icons'`, async function () {
const content = splitter(
'{\n' +
'"window.zoomLevel": 0,\n' +
`"${constants.vscode.iconThemeSetting}": "${constants.extension.name}"\n` +
'}',
);
const expected = splitter(`{\n"window.zoomLevel": 0\n` + '}');
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(resetIconThemeSpy.calledOnce).to.be.true;
expect(resetIconThemeSpy.returned(expected)).to.be.true;
});
});
context(`does NOT reset the 'iconTheme' configuration`, function () {
it(`if it's NOT set to 'vscode-icons'`, async function () {
const content = splitter(
'{\n' +
'"window.zoomLevel": 0,\n' +
`"${constants.vscode.iconThemeSetting}": "otherIconTheme"\n` +
'}',
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(resetIconThemeSpy.calledOnce).to.be.true;
expect(resetIconThemeSpy.returned(content)).to.be.true;
});
});
});
context(`function 'removeLastEntryTrailingComma'`, function () {
let removeLastEntryTrailingCommaStub: sinon.SinonSpy;
beforeEach(() => {
removeLastEntryTrailingCommaStub = sandbox.spy(
ConfigManager,
// @ts-ignore
'removeLastEntryTrailingComma',
);
});
context('to remove the trailing comma', function () {
context('of the last settings entry', function () {
it('when there is no EOF extra line', async function () {
const content = splitter(
`{\n"window.zoomLevel": 0,\n"updateChannel": "none",\n}`,
);
const expected = splitter(
`{\n"window.zoomLevel": 0,\n"updateChannel": "none"\n}`,
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeLastEntryTrailingCommaStub.calledOnce).to.be.true;
expect(
removeLastEntryTrailingCommaStub.returned(expected),
).to.be.true;
});
it('when there is an EOF extra line', async function () {
const content = splitter(
`{\n"window.zoomLevel": 0,\n"updateChannel": "none",\n}\n`,
);
const expected = splitter(
`{\n"window.zoomLevel": 0,\n"updateChannel": "none"\n}\n`,
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeLastEntryTrailingCommaStub.calledOnce).to.be.true;
expect(
removeLastEntryTrailingCommaStub.returned(expected),
).to.be.true;
});
it(`when the last entry is of 'object' type`, async function () {
const content = splitter(
'{\n' +
'"window.zoomLevel": 0,\n' +
'"updateChannel": "none",\n' +
'"files.associations": {\n' +
'"js": "something"\n' +
'},\n' +
'}',
);
const expected = splitter(
'{\n' +
'"window.zoomLevel": 0,\n' +
'"updateChannel": "none",\n' +
'"files.associations": {\n' +
'"js": "something"\n' +
'}\n' +
'}',
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeLastEntryTrailingCommaStub.calledOnce).to.be.true;
expect(
removeLastEntryTrailingCommaStub.returned(expected),
).to.be.true;
});
it(`when the last entry is of 'array' type`, async function () {
const content = splitter(
'{\n' +
'"window.zoomLevel": 0,\n' +
'"updateChannel": "none",\n' +
'"some.setting": [\n' +
'"entry",\n' +
'"anotherEntry"\n' +
'],\n' +
'}',
);
const expected = splitter(
'{\n' +
'"window.zoomLevel": 0,\n' +
'"updateChannel": "none",\n' +
'"some.setting": [\n' +
'"entry",\n' +
'"anotherEntry"\n' +
']\n' +
'}',
);
updateFileStub.callsArgWith(1, content).resolves();
await ConfigManager.removeSettings();
expect(updateFileStub.calledOnce).to.be.true;
expect(updateFileStub.firstCall.callback).to.be.a('function');
expect(removeLastEntryTrailingCommaStub.calledOnce).to.be.true;
expect(
removeLastEntryTrailingCommaStub.returned(expected),
).to.be.true;
});
});
});
});
context(`function 'updateVSIconsConfigState'`, function () {
let supportsThemesReloadStub: sinon.SinonStub;
beforeEach(function () {
supportsThemesReloadStub = sandbox.stub(
vscodeManagerStub,
'supportsThemesReload',
);
});
context(`when editor supports themes reload`, function () {
beforeEach(function () {
supportsThemesReloadStub.value(true);
});
it(`updates the initial configuration state`, function () {
// @ts-ignore
const initConfig = configManager.initVSIconsConfig as IVSIcons;
vsiconsClone.presets.angular = true;
configManager.updateVSIconsConfigState();
// @ts-ignore
expect(configManager.initVSIconsConfig).to.not.be.eql(initConfig);
});
});
context(`when editor does NOT support themes reload`, function () {
beforeEach(function () {
supportsThemesReloadStub.value(false);
});
it(`does NOT update the initial configuration state`, function () {
// @ts-ignore
const initConfig = configManager.initVSIconsConfig as IVSIcons;
vsiconsClone.presets.angular = true;
configManager.updateVSIconsConfigState();
// @ts-ignore
expect(configManager.initVSIconsConfig).to.be.eql(initConfig);
});
});
});
context(`function 'hasConfigChanged'`, function () {
context(`returns 'true'`, function () {
it(`when no configuration is provided`, function () {
expect(configManager.hasConfigChanged(undefined)).to.be.true;
});
context(`when the config has changed`, function () {
it(`in any section`, function () {
vsiconsClone.customIconFolderPath = 'path/to';
expect(configManager.hasConfigChanged(vsiconsClone)).to.be.true;
});
it(`only on the specified sections`, function () {
vsiconsClone.presets.hideExplorerArrows = true;
expect(
configManager.hasConfigChanged(vsiconsClone, [
constants.vsicons.presets.name,
]),
).to.be.true;
});
});
});
context(`returns 'false'`, function () {
context(`when the config has NOT changed`, function () {
it(`in any section`, function () {
expect(configManager.hasConfigChanged(vsiconsClone)).to.be.false;
});
it(`in the specified sections`, function () {
vsiconsClone.presets.hideExplorerArrows = true;
expect(
configManager.hasConfigChanged(vsiconsClone, [
constants.vsicons.associations.name,
]),
).to.be.false;
});
});
});
});
context(`function 'getCustomIconsDirPath'`, function () {
it(`returns the app user directory, when no directory path is provided`, async function () {
const appUserDirPath = '/Path/To/App/User/Dir/Path';
vscodeManagerStub.getAppUserDirPath.returns(appUserDirPath);
const dirPath = await configManager.getCustomIconsDirPath('');
expect(dirPath).to.be.equal(appUserDirPath);
});
context(`returns the provide directory path, when`, function () {
it(`it's an absolute path`, async function () {
const customIconsDirPath = '/Path/To/Custom/Icons/Dir/';
const dirPath = await configManager.getCustomIconsDirPath(
customIconsDirPath,
);
expect(dirPath).to.be.equal(customIconsDirPath);
});
it(`no 'workspace' directory paths exist`, async function () {
const customIconsDirPath = './Path/To/Custom/Icons/Dir/';
vscodeManagerStub.getWorkspacePaths.returns(undefined);
const dirPath = await configManager.getCustomIconsDirPath(
customIconsDirPath,
);
expect(dirPath).to.be.equal(customIconsDirPath);
});
it(`the 'workspace' directory paths are empty`, async function () {
const customIconsDirPath = './Path/To/Custom/Icons/Dir/';
vscodeManagerStub.getWorkspacePaths.returns([]);
const dirPath = await configManager.getCustomIconsDirPath(
customIconsDirPath,
);
expect(dirPath).to.be.equal(customIconsDirPath);
});
it(`the 'workspace' directory path does NOT exist`, async function () {
const customIconsDirPath = './Path/To/Custom/Icons/Dir/';
const rootDir = '/';
const joinedDir = path.posix.join('', customIconsDirPath);
vscodeManagerStub.getWorkspacePaths.returns([rootDir]);
sandbox.stub(fsAsync, 'existsAsync').resolves(false);
pathUnixJoinStub.returns(joinedDir);
const dirPath = await configManager.getCustomIconsDirPath(
customIconsDirPath,
);
expect(dirPath).to.be.equal(joinedDir);
});
});
context(`returns an absolute directory path, when`, function () {
it(`the provided path is relative to the 'workspace' directory`, async function () {
const customIconsDirPath = './Path/To/Custom/Icons/Dir/';
const rootDir = '/';
const joinedDir = path.posix.join(rootDir, customIconsDirPath);
vscodeManagerStub.getWorkspacePaths.returns([rootDir]);
sandbox.stub(fsAsync, 'existsAsync').resolves(true);
pathUnixJoinStub.returns(joinedDir);
const dirPath = await configManager.getCustomIconsDirPath(
customIconsDirPath,
);
expect(dirPath).to.be.equal(joinedDir);
});
});
});
context(`function 'getIconTheme'`, function () {
it(`returns the icon theme setting`, function () {
getStub.returns(constants.vsicons.name);
expect(configManager.getIconTheme()).to.equal(constants.vsicons.name);
expect(
getStub.calledOnceWith(constants.vscode.iconThemeSetting),
).to.be.true;
});
it(`returns 'undefined' if the icon theme setting does NOT exists`, function () {
getStub.returns(undefined);
expect(configManager.getIconTheme()).to.be.undefined;
expect(
getStub.calledOnceWith(constants.vscode.iconThemeSetting),
).to.be.true;
});
});
context(`function 'getPreset'`, function () {
it(`returns the preset setting`, function () {
const expected = {
key: PresetNames[PresetNames.hideFolders],
defaultValue: false,
globalValue: undefined,
workspaceValue: undefined,
workspaceFolderValue: undefined,
};
inspectStub.returns(expected);
expect(
configManager.getPreset<boolean>(
PresetNames[PresetNames.hideFolders],
),
).to.eql(expected);
expect(
inspectStub
.getCall(2)
.calledWith(PresetNames[PresetNames.hideFolders]),
).to.be.true;
});
it(`returns 'undefined', if the preset setting does NOT exists`, function () {
inspectStub.returns(undefined);
expect(configManager.getPreset('some.unknown')).to.be.undefined;
expect(inspectStub.getCall(2).calledWith('some.unknown')).to.be.true;
});
});
context(`function 'updateDontShowNewVersionMessage'`, function () {
it(`updates the setting to 'true'`, async function () {
await configManager.updateDontShowNewVersionMessage(true);
expect(
updateStub.calledOnceWith(
constants.vsicons.dontShowNewVersionMessageSetting,
true,
ConfigurationTarget.Global,
),
).to.be.true;
});
it(`updates the setting to 'false'`, async function () {
await configManager.updateDontShowNewVersionMessage(false);
expect(
updateStub.calledOnceWith(
constants.vsicons.dontShowNewVersionMessageSetting,
false,
ConfigurationTarget.Global,
),
).to.be.true;
});
});
context(
`function 'updateDontShowConfigManuallyChangedMessage'`,
function () {
it(`updates the setting to 'true'`, async function () {
await configManager.updateDontShowConfigManuallyChangedMessage(true);
expect(
updateStub.calledOnceWith(
constants.vsicons.dontShowConfigManuallyChangedMessageSetting,
true,
ConfigurationTarget.Global,
),
).to.be.true;
});
it(`updates the setting to 'false'`, async function () {
await configManager.updateDontShowConfigManuallyChangedMessage(false);
expect(
updateStub.calledOnceWith(
constants.vsicons.dontShowConfigManuallyChangedMessageSetting,
false,
ConfigurationTarget.Global,
),
).to.be.true;
});
},
);
context(`function 'updateAutoReload'`, function () {
it(`updates the setting to 'true'`, async function () {
await configManager.updateAutoReload(true);
expect(
updateStub.calledOnceWith(
constants.vsicons.projectDetectionAutoReloadSetting,
true,
ConfigurationTarget.Global,
),
).to.be.true;
});
it(`updates the setting to 'false'`, async function () {
await configManager.updateAutoReload(false);
expect(
updateStub.calledOnceWith(
constants.vsicons.projectDetectionAutoReloadSetting,
false,
ConfigurationTarget.Global,
),
).to.be.true;
});
});
context(`function 'updateDisableDetection'`, function () {
it(`updates the setting to 'true'`, async function () {
await configManager.updateDisableDetection(true);
expect(
updateStub.calledOnceWith(
constants.vsicons.projectDetectionDisableDetectSetting,
true,
ConfigurationTarget.Global,
),
).to.be.true;
});
it(`updates the setting to 'false'`, async function () {
await configManager.updateDisableDetection(false);
expect(
updateStub.calledOnceWith(
constants.vsicons.projectDetectionDisableDetectSetting,
false,
ConfigurationTarget.Global,
),
).to.be.true;
});
});
context(`function 'updateIconTheme'`, function () {
it(`updates the icon theme setting to 'vsicons'`, async function () {
await configManager.updateIconTheme();
expect(
updateStub.calledOnceWith(
constants.vscode.iconThemeSetting,
constants.extension.name,
ConfigurationTarget.Global,
),
).to.be.true;
});
});
context(`function 'updatePreset'`, function () {
it(`updates the preset setting to 'true'`, async function () {
inspectStub.returns({ defaultValue: false });
await configManager.updatePreset(
PresetNames[PresetNames.tsOfficial],
true,
ConfigurationTarget.Global,
);
expect(
inspectStub
.getCall(2)
.calledWith(
`${constants.vsicons.presets.fullname}.${
PresetNames[PresetNames.tsOfficial]
}`,
),
).to.be.true;
expect(
updateStub.calledOnceWith(
`${constants.vsicons.presets.fullname}.${
PresetNames[PresetNames.tsOfficial]
}`,
true,
ConfigurationTarget.Global,
),
).to.be.true;
});
it(`removes the preset setting when the value is 'false'`, async function () {
inspectStub.returns({ defaultValue: false });
await configManager.updatePreset(
PresetNames[PresetNames.jsOfficial],
false,
ConfigurationTarget.Global,
);
expect(
inspectStub
.getCall(2)
.calledWith(
`${constants.vsicons.presets.fullname}.${
PresetNames[PresetNames.jsOfficial]
}`,
),
).to.be.true;
expect(
updateStub.calledOnceWith(
`${constants.vsicons.presets.fullname}.${
PresetNames[PresetNames.jsOfficial]
}`,
undefined,
ConfigurationTarget.Global,
),
).to.be.true;
});
it(`respects the configuration target`, async function () {
inspectStub.returns({ defaultValue: false });
await configManager.updatePreset(
PresetNames[PresetNames.angular],
false,
ConfigurationTarget.Workspace,
);
expect(
inspectStub
.getCall(2)
.calledWith(
`${constants.vsicons.presets.fullname}.${
PresetNames[PresetNames.angular]
}`,
),
).to.be.true;
expect(
updateStub.calledOnceWith(
`${constants.vsicons.presets.fullname}.${
PresetNames[PresetNames.angular]
}`,
undefined,
ConfigurationTarget.Workspace,
),
).to.be.true;
});
});
});
}); | the_stack |
import { IDisposable } from '@lumino/disposable';
import { NotebookActions } from '@jupyterlab/notebook';
import { NotebookPanel, Notebook } from '@jupyterlab/notebook';
import { Cell, ICellModel } from '@jupyterlab/cells';
import { StickyContent } from './content';
import { StickyMarkdown } from './markdown';
import { StickyCode } from './code';
import { StickyLand } from './stickyland';
import { ContentType } from './content';
import { MyIcons } from './icons';
export type Tab = {
cellType: ContentType;
cellIndex: number;
tabNode: HTMLElement;
tabContent: StickyContent;
hasNewUpdate: boolean;
};
export class StickyTab implements IDisposable {
stickyContainer: HTMLElement;
node: HTMLElement;
stickyLand: StickyLand;
notebook: NotebookPanel;
addButton: HTMLElement;
activeTab: Tab | null = null;
tabs: Tab[] = [];
autoRunTimeout: number | null = null;
autoRunningCellNodes: Set<HTMLElement> = new Set([]);
autoRunCells = new Array<StickyCode>();
autoRunTabs = new Array<Tab>();
isDisposed = false;
constructor(
stickyContainer: HTMLElement,
panel: NotebookPanel,
stickyLand: StickyLand
) {
this.stickyContainer = stickyContainer;
this.stickyLand = stickyLand;
this.notebook = panel;
// Add the tab element
this.node = document.createElement('div');
this.node.classList.add('sticky-tab', 'sticky-tab-bar');
this.stickyContainer.append(this.node);
// Add new cell button
this.addButton = document.createElement('button');
this.addButton.classList.add('add-tab');
this.node.appendChild(this.addButton);
MyIcons.addIcon2.element({ container: this.addButton });
this.addButton.addEventListener('click', (e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
// Create a new tab and switch the active tab
this.createTab();
});
// Create the first tab
this.createTab();
/**
* Listen to the notebook execution events so we can auto-run the code cell
* We need to register the listener at the tab level because there can be
* multiple code cells with auto-run turned on. If each triggers its own
* listener then there will be a race and infinite auto-runs.
*/
NotebookActions.executionScheduled.connect(
this.handleExecutionScheduled,
this
);
NotebookActions.executed.connect(this.handleExecuted, this);
}
/**
* Handle the executionScheduled signal.
*/
handleExecutionScheduled = (
_: any,
args: {
notebook: Notebook;
cell: Cell<ICellModel>;
}
) => {
if (this.autoRunningCellNodes.size !== 0) {
return;
}
// Get all the code cells that have auto-run turned on
const autoRunCells = new Array<StickyCode>();
const autoRunTabs = new Array<Tab>();
this.tabs.forEach(d => {
if (d.cellType === ContentType.Code) {
const curContent = d.tabContent.curContent as StickyCode;
if (curContent.autoRun) {
autoRunCells.push(curContent);
autoRunTabs.push(d);
}
}
});
// We need to set a timeout to workaround the current executionScheduled
// emit order
// https://github.com/jupyterlab/jupyterlab/pull/11453
// Also users might run multiple cells at one time, we can set a short
// timeout so that we only run the sticky code cell once in a series of
// other executions of other cells
if (this.autoRunTimeout !== null) {
clearTimeout(this.autoRunTimeout);
}
this.autoRunTimeout = setTimeout(() => {
// Run the auto-run code cells
const toRunCells = new Array<StickyCode>();
autoRunCells.forEach(d => {
// If the signal source is the cell itself, we mark it as autoRunScheduled
// so we won't run it again after its peers finish running
if (d.originalCell.node === args.cell.node) {
d.autoRunScheduled = true;
} else {
if (!d.autoRunScheduled) {
d.autoRunScheduled = true;
// d.execute returns a promise but the promise can be fulfilled before
// the cell is executed, so we manually keep a record of all running
// cells and resolve them manually
toRunCells.push(d);
this.autoRunningCellNodes.add(d.originalCell.node);
}
}
});
toRunCells.forEach(d => d.execute(true));
// Move the local autoRunCells/autoRunTabs to object level
this.autoRunCells = autoRunCells;
this.autoRunTabs = autoRunTabs;
}, 200);
};
/**
* Handle the executed signal.
*/
handleExecuted = (
_: any,
args: {
notebook: Notebook;
cell: Cell<ICellModel>;
}
) => {
// Check if the cell that just finishes running is scheduled by us
if (this.autoRunningCellNodes.has(args.cell.node)) {
// Remove watching this cell
this.autoRunningCellNodes.delete(args.cell.node);
// If all auto-running cells finish running, we allow all these cells to
// be auto-run again in the future
if (this.autoRunningCellNodes.size === 0) {
this.autoRunCells.forEach(d => {
d.autoRunScheduled = false;
});
// Also mark the tab to indicate there is new update in this tab
this.autoRunTabs.forEach(d => {
// const curCell = d.tabContent.curContent as StickyCode;
if (!d.tabNode.classList.contains('current')) {
d.tabNode.classList.add('new-update');
}
});
this.autoRunCells = [];
this.autoRunTabs = [];
}
}
};
/**
* Create a tab containing a dropzone content. The tab name is always 'new'
* for new tabs. Creating a different content (after interacting with the
* dropzone will update the tab name).
* @returns New tab
*/
createTab = (): Tab => {
// Create a new tab node
const tabNode = document.createElement('button');
tabNode.classList.add('tab', 'new-tab');
tabNode.setAttribute('title', 'New tab');
// Add a label to the button
const tabLabel = document.createElement('span');
tabLabel.classList.add('tab-label');
tabNode.appendChild(tabLabel);
// Add a delete icon
const tabIcon = document.createElement('div');
tabIcon.classList.add('tab-icon');
MyIcons.tabCloseIcon.element({ container: tabIcon });
tabNode.appendChild(tabIcon);
// New tab always has the dropzone content
tabLabel.innerHTML = 'New';
const tabContent = new StickyContent(
this.stickyContainer,
this.notebook,
this.stickyLand
);
// Add this tab to the model and view
const newTab: Tab = {
cellType: ContentType.Dropzone,
cellIndex: 0,
tabNode: tabNode,
tabContent: tabContent,
hasNewUpdate: false
};
// Handle delete icon clicked
tabIcon.addEventListener('click', (e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
this.closeTab(newTab);
});
this.tabs.push(newTab);
this.node.insertBefore(newTab.tabNode, this.addButton);
// Handle tab clicked
tabNode.addEventListener('click', (e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
// Switch the active tab to the current one
if (this.activeTab?.tabNode !== tabNode) {
this.switchActiveTab(newTab);
// Remove the new update if it's there
newTab.tabNode.classList.remove('new-update');
}
});
// Move the current active tab to this new one
this.switchActiveTab(newTab);
// Return this tab
return newTab;
};
/**
* Close the given tab
* @param tab Tab to close
*/
closeTab = (tab: Tab) => {
// Case 1: this tab is the only tab
if (this.tabs.length === 1) {
// Swap the content to dropzone
tab.tabContent.swapToDropzone();
// Update the tab name
this.updateActiveTab();
} else {
// Case 2: if there are other tabs
// First swap the content to dropzone
tab.tabContent.swapToDropzone();
// Then remove the content
tab.tabContent.dispose();
// Prepare to remove the tab
const tabIndex = this.tabs.indexOf(tab);
// Change the active tab to the one on the left or on the right if there
// is no tab on the left
if (tabIndex !== 0) {
this.switchActiveTab(this.tabs[tabIndex - 1]);
} else {
this.switchActiveTab(this.tabs[tabIndex + 1]);
}
// Remove the tab from model
this.tabs.splice(tabIndex, 1);
// Remove the tab from the DOM
tab.tabNode.remove();
}
};
/**
* Change the currently active tab to the new tab
*/
switchActiveTab = (newTab: Tab) => {
if (this.activeTab) {
// Hide the old active tab's content
this.activeTab.tabContent.wrapperNode.classList.add('no-display');
this.activeTab.tabNode.classList.remove('current');
}
this.activeTab = newTab;
newTab.tabNode.classList.add('current');
newTab.tabContent.wrapperNode.classList.remove('no-display');
this.stickyLand.stickyContent = newTab.tabContent;
};
/**
* Update the tab name for the active tab. This function is called when user
* creates a new code/md cell.
*/
updateActiveTab = () => {
if (this.activeTab) {
const newContent = this.activeTab?.tabContent.curContent;
// Find the new content type
let newCellType = ContentType.Dropzone;
if (newContent instanceof StickyCode) {
newCellType = ContentType.Code;
} else if (newContent instanceof StickyMarkdown) {
newCellType = ContentType.Markdown;
}
// Find the new cell index
let newCellIndex = 1;
this.tabs.forEach(d => {
if (d.cellType === newCellType) {
newCellIndex++;
}
});
// Update the tab name
const tabLabel = this.activeTab.tabNode.querySelector('.tab-label');
if (tabLabel) {
switch (newCellType) {
case ContentType.Code:
tabLabel.innerHTML = `Code-${newCellIndex}`;
this.activeTab.tabNode.setAttribute(
'title',
`Code-${newCellIndex}`
);
this.activeTab.tabNode.classList.remove('new-tab');
break;
case ContentType.Markdown:
tabLabel.innerHTML = `Markdown-${newCellIndex}`;
this.activeTab.tabNode.setAttribute(
'title',
`Markdown-${newCellIndex}`
);
this.activeTab.tabNode.classList.remove('new-tab');
break;
case ContentType.Dropzone:
tabLabel.innerHTML = 'New';
this.activeTab.tabNode.setAttribute('title', 'New tab');
this.activeTab.tabNode.classList.add('new-tab');
break;
default:
break;
}
}
// Update the model data
this.activeTab.cellIndex = newCellIndex;
this.activeTab.cellType = newCellType;
}
};
dispose = () => {
this.isDisposed = true;
NotebookActions.executionScheduled.disconnect(
this.handleExecutionScheduled,
this
);
NotebookActions.executed.disconnect(this.handleExecuted, this);
};
} | the_stack |
import './strings.m.js';
import './alert_indicators.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {CustomElement} from 'chrome://resources/js/custom_element.js';
import {getFavicon} from 'chrome://resources/js/icon.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {isRTL} from 'chrome://resources/js/util.m.js';
import {AlertIndicatorsElement} from './alert_indicators.js';
import {Tab, TabNetworkState} from './tab_strip.mojom-webui.js';
import {TabSwiper} from './tab_swiper.js';
import {CloseTabAction, TabsApiProxy, TabsApiProxyImpl} from './tabs_api_proxy.js';
function getAccessibleTitle(tab: Tab): string {
const tabTitle = tab.title;
if (tab.crashed) {
return loadTimeData.getStringF('tabCrashed', tabTitle);
}
if (tab.networkState === TabNetworkState.kError) {
return loadTimeData.getStringF('tabNetworkError', tabTitle);
}
return tabTitle;
}
/**
* TODO(crbug.com/1025390): padding-inline-end cannot be animated yet.
*/
function getPaddingInlineEndProperty(): string {
return isRTL() ? 'paddingLeft' : 'paddingRight';
}
export class TabElement extends CustomElement {
static get template() {
return `{__html_template__}`;
}
private alertIndicatorsEl_: AlertIndicatorsElement;
private closeButtonEl_: HTMLElement;
private dragImageEl_: HTMLElement;
private tabEl_: HTMLElement;
private faviconEl_: HTMLElement;
private thumbnailContainer_: HTMLElement;
private thumbnail_: HTMLImageElement;
private tab_: Tab;
private tabsApi_: TabsApiProxy;
private titleTextEl_: HTMLElement;
private isValidDragOverTarget_: boolean;
private tabSwiper_: TabSwiper;
private onTabActivating_: (tabId: number) => void;
constructor() {
super();
this.alertIndicatorsEl_ =
this.$<AlertIndicatorsElement>('tabstrip-alert-indicators')!;
// Normally, custom elements will get upgraded automatically once added
// to the DOM, but TabElement may need to update properties on
// AlertIndicatorElement before this happens, so upgrade it manually.
customElements.upgrade(this.alertIndicatorsEl_);
this.closeButtonEl_ = this.$<HTMLElement>('#close')!;
this.closeButtonEl_.setAttribute(
'aria-label', loadTimeData.getString('closeTab'));
this.dragImageEl_ = this.$<HTMLElement>('#dragImage')!;
this.tabEl_ = this.$<HTMLElement>('#tab')!;
this.faviconEl_ = this.$<HTMLElement>('#favicon')!;
this.thumbnailContainer_ = this.$<HTMLElement>('#thumbnail')!;
this.thumbnail_ = this.$<HTMLImageElement>('#thumbnailImg')!;
this.tabsApi_ = TabsApiProxyImpl.getInstance();
this.titleTextEl_ = this.$<HTMLElement>('#titleText')!;
/**
* Flag indicating if this TabElement can accept dragover events. This
* is used to pause dragover events while animating as animating causes
* the elements below the pointer to shift.
*/
this.isValidDragOverTarget_ = true;
this.tabEl_.addEventListener('click', () => this.onClick_());
this.tabEl_.addEventListener('contextmenu', e => this.onContextMenu_(e));
this.tabEl_.addEventListener('keydown', e => this.onKeyDown_(e));
this.tabEl_.addEventListener('pointerup', e => this.onPointerUp_(e));
this.closeButtonEl_.addEventListener('click', e => this.onClose_(e));
this.addEventListener('swipe', () => this.onSwipe_());
this.tabSwiper_ = new TabSwiper(this);
this.onTabActivating_ = (tabId: number) => {};
}
get tab(): Tab {
return this.tab_;
}
set tab(tab: Tab) {
this.toggleAttribute('active', tab.active);
this.tabEl_.setAttribute('aria-selected', tab.active.toString());
this.toggleAttribute('hide-icon_', !tab.showIcon);
this.toggleAttribute(
'waiting_',
!tab.shouldHideThrobber &&
tab.networkState === TabNetworkState.kWaiting);
this.toggleAttribute(
'loading_',
!tab.shouldHideThrobber &&
tab.networkState === TabNetworkState.kLoading);
this.toggleAttribute('pinned', tab.pinned);
this.toggleAttribute('blocked_', tab.blocked);
this.setAttribute('draggable', String(true));
this.toggleAttribute('crashed_', tab.crashed);
if (tab.title) {
this.titleTextEl_.textContent = tab.title;
} else if (
!tab.shouldHideThrobber &&
(tab.networkState === TabNetworkState.kWaiting ||
tab.networkState === TabNetworkState.kLoading)) {
this.titleTextEl_.textContent = loadTimeData.getString('loadingTab');
} else {
this.titleTextEl_.textContent = loadTimeData.getString('defaultTabTitle');
}
this.titleTextEl_.setAttribute('aria-label', getAccessibleTitle(tab));
if (tab.networkState === TabNetworkState.kWaiting ||
(tab.networkState === TabNetworkState.kLoading &&
tab.isDefaultFavicon)) {
this.faviconEl_.style.backgroundImage = 'none';
} else if (tab.faviconUrl) {
this.faviconEl_.style.backgroundImage = `url(${tab.faviconUrl.url})`;
} else {
this.faviconEl_.style.backgroundImage = getFavicon('');
}
// Expose the ID to an attribute to allow easy querySelector use
this.setAttribute('data-tab-id', tab.id.toString());
this.alertIndicatorsEl_.updateAlertStates(tab.alertStates)
.then((alertIndicatorsCount) => {
this.toggleAttribute('has-alert-states_', alertIndicatorsCount > 0);
});
if (!this.tab_ || (this.tab_.pinned !== tab.pinned && !tab.pinned)) {
this.tabSwiper_.startObserving();
} else if (this.tab_.pinned !== tab.pinned && tab.pinned) {
this.tabSwiper_.stopObserving();
}
this.tab_ = Object.freeze(tab);
}
get isValidDragOverTarget(): boolean {
return !this.hasAttribute('dragging_') && this.isValidDragOverTarget_;
}
set isValidDragOverTarget(isValid: boolean) {
this.isValidDragOverTarget_ = isValid;
}
set onTabActivating(callback: (tabId: number) => void) {
this.onTabActivating_ = callback;
}
focus() {
this.tabEl_.focus();
}
getDragImage(): HTMLElement {
return this.dragImageEl_;
}
getDragImageCenter(): HTMLElement {
// dragImageEl_ has padding, so the drag image should be centered relative
// to tabEl_, the element within the padding.
return this.tabEl_;
}
updateThumbnail(imgData: string) {
this.thumbnail_.src = imgData;
}
private onClick_() {
if (!this.tab_ || this.tabSwiper_.wasSwiping()) {
return;
}
const tabId = this.tab_.id;
this.onTabActivating_(tabId);
this.tabsApi_.activateTab(tabId);
this.tabsApi_.closeContainer();
}
private onContextMenu_(event: Event) {
event.preventDefault();
event.stopPropagation();
}
private onClose_(event: Event) {
assert(this.tab_);
event.stopPropagation();
this.tabsApi_.closeTab(this.tab_.id, CloseTabAction.CLOSE_BUTTON);
}
private onSwipe_() {
assert(this.tab_);
this.tabsApi_.closeTab(this.tab_.id, CloseTabAction.SWIPED_TO_CLOSE);
}
private onKeyDown_(event: KeyboardEvent) {
if (event.key === 'Enter' || event.key === ' ') {
this.onClick_();
}
}
private onPointerUp_(event: PointerEvent) {
event.stopPropagation();
if (event.pointerType !== 'touch' && event.button === 2) {
this.tabsApi_.showTabContextMenu(
this.tab.id, event.clientX, event.clientY);
}
}
resetSwipe() {
this.tabSwiper_.reset();
}
setDragging(isDragging: boolean) {
this.toggleAttribute('dragging_', isDragging);
}
setDraggedOut(isDraggedOut: boolean) {
this.toggleAttribute('dragged-out_', isDraggedOut);
}
isDraggedOut(): boolean {
return this.hasAttribute('dragged-out_');
}
setTouchPressed(isTouchPressed: boolean) {
this.toggleAttribute('touch_pressed_', isTouchPressed);
}
slideIn(): Promise<void> {
const paddingInlineEnd = getPaddingInlineEndProperty();
// If this TabElement is the last tab, there needs to be enough space for
// the view to scroll to it. Therefore, immediately take up all the space
// it needs to and only animate the scale.
const isLastChild = this.nextElementSibling === null;
const startState = {
maxWidth: isLastChild ? 'var(--tabstrip-tab-width)' : 0,
transform: `scale(0)`,
[paddingInlineEnd]: isLastChild ? 'var(--tabstrip-tab-spacing)' : 0,
};
const finishState = {
maxWidth: `var(--tabstrip-tab-width)`,
transform: `scale(1)`,
[paddingInlineEnd]: 'var(--tabstrip-tab-spacing)',
};
return new Promise(resolve => {
const animation = this.animate([startState, finishState], {
duration: 300,
easing: 'cubic-bezier(.4, 0, 0, 1)',
});
animation.onfinish = () => {
resolve();
};
// TODO(crbug.com/1035678) By the next animation frame, the animation
// should start playing. By the time another animation frame happens,
// force play the animation if the animation has not yet begun. Remove
// if/when the Blink issue has been fixed.
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (animation.pending) {
animation.play();
}
});
});
});
}
slideOut(): Promise<void> {
if (!this.tabsApi_.isVisible() || this.tab_.pinned ||
this.tabSwiper_.wasSwiping()) {
this.remove();
return Promise.resolve();
}
return new Promise(resolve => {
const finishCallback = () => {
this.remove();
resolve();
};
const translateAnimation = this.animate(
{
transform: ['translateY(0)', 'translateY(-100%)'],
},
{
duration: 150,
easing: 'cubic-bezier(.4, 0, 1, 1)',
fill: 'forwards',
});
const opacityAnimation = this.animate(
{
opacity: [1, 0],
},
{
delay: 97.5,
duration: 50,
fill: 'forwards',
});
const widthAnimationKeyframes = {
maxWidth: ['var(--tabstrip-tab-width)', 0],
[getPaddingInlineEndProperty()]: ['var(--tabstrip-tab-spacing)', 0],
};
// TODO(dpapad): Figure out why TypeScript compiler does not understand
// the alternative keyframe syntax. Seems to work in the TS playground.
const widthAnimation = this.animate(widthAnimationKeyframes as any, {
delay: 97.5,
duration: 300,
easing: 'cubic-bezier(.4, 0, 0, 1)',
fill: 'forwards',
});
const visibilityChangeListener = () => {
if (!this.tabsApi_.isVisible()) {
// If a tab strip becomes hidden during the animation, the onfinish
// event will not get fired until the tab strip becomes visible again.
// Therefore, when the tab strip becomes hidden, immediately call the
// finish callback.
translateAnimation.cancel();
opacityAnimation.cancel();
widthAnimation.cancel();
finishCallback();
}
};
document.addEventListener(
'visibilitychange', visibilityChangeListener, {once: true});
// The onfinish handler is put on the width animation, as it will end
// last.
widthAnimation.onfinish = () => {
document.removeEventListener(
'visibilitychange', visibilityChangeListener);
finishCallback();
};
});
}
}
declare global {
interface HTMLElementTagNameMap {
'tabstrip-tab': TabElement;
}
}
customElements.define('tabstrip-tab', TabElement);
export function isTabElement(element: Element): boolean {
return element.tagName === 'TABSTRIP-TAB';
} | the_stack |
import { Array } from "@siteimprove/alfa-array";
import { Cache } from "@siteimprove/alfa-cache";
import { Device } from "@siteimprove/alfa-device";
import { Attribute, Element, Node, Text } from "@siteimprove/alfa-dom";
import { Equatable } from "@siteimprove/alfa-equatable";
import { Iterable } from "@siteimprove/alfa-iterable";
import { Serializable } from "@siteimprove/alfa-json";
import { Option, None } from "@siteimprove/alfa-option";
import { Predicate } from "@siteimprove/alfa-predicate";
import { Refinement } from "@siteimprove/alfa-refinement";
import { Sequence } from "@siteimprove/alfa-sequence";
import { Style } from "@siteimprove/alfa-style";
import { Thunk } from "@siteimprove/alfa-thunk";
import * as json from "@siteimprove/alfa-json";
import { Feature } from "./feature";
import { Role } from "./role";
import * as predicate from "./name/predicate";
const { hasId, isElement } = Element;
const { isText } = Text;
const { equals } = Predicate;
const { or } = Refinement;
/**
* @public
*/
export class Name implements Equatable, Serializable<Name.JSON> {
public static of(value: string, sources: Iterable<Name.Source> = []): Name {
return new Name(value, Array.from(sources));
}
private readonly _value: string;
private readonly _sources: Array<Name.Source>;
private constructor(value: string, sources: Array<Name.Source>) {
this._value = value;
this._sources = sources;
}
public get value(): string {
return this._value;
}
public get source(): ReadonlyArray<Name.Source> {
return this._sources;
}
public isEmpty(): boolean {
return this._value.length === 0;
}
public equals(value: unknown): value is this {
return (
value instanceof Name &&
value._value === this._value &&
value._sources.length === this._sources.length &&
value._sources.every((source, i) => source.equals(this._sources[i]))
);
}
public toJSON(): Name.JSON {
return {
value: this._value,
sources: this._sources.map((source) => source.toJSON()),
};
}
public toString(): string {
return this._value;
}
}
/**
* @public
*/
export namespace Name {
export interface JSON {
[key: string]: json.JSON;
value: string;
sources: Array<Source.JSON>;
}
export type Source =
| Source.Data
| Source.Descendant
| Source.Ancestor
| Source.Label
| Source.Reference;
export namespace Source {
export type JSON =
| Data.JSON
| Descendant.JSON
| Ancestor.JSON
| Label.JSON
| Reference.JSON;
export class Data implements Equatable, Serializable<Data.JSON> {
public static of(text: Text): Data {
return new Data(text);
}
private readonly _text: Text;
private constructor(text: Text) {
this._text = text;
}
public get type(): "data" {
return "data";
}
public get text(): Text {
return this._text;
}
public equals(value: unknown): value is this {
return value instanceof Data && value._text.equals(this._text);
}
public toJSON(): Data.JSON {
return {
type: "data",
text: this._text.path(),
};
}
}
export namespace Data {
export interface JSON {
[key: string]: json.JSON;
type: "data";
text: string;
}
}
export function data(text: Text): Data {
return Data.of(text);
}
export class Descendant
implements Equatable, Serializable<Descendant.JSON>
{
public static of(element: Element, name: Name): Descendant {
return new Descendant(element, name);
}
private readonly _element: Element;
private readonly _name: Name;
private constructor(element: Element, name: Name) {
this._element = element;
this._name = name;
}
public get type(): "descendants" {
return "descendants";
}
public get element(): Element {
return this._element;
}
public get name(): Name {
return this._name;
}
public equals(value: unknown): value is this {
return (
value instanceof Descendant &&
value._element.equals(this._element) &&
value._name.equals(this._name)
);
}
public toJSON(): Descendant.JSON {
return {
type: "descendant",
element: this._element.path(),
name: this._name.toJSON(),
};
}
}
export namespace Descendant {
export interface JSON {
[key: string]: json.JSON;
type: "descendant";
element: string;
name: Name.JSON;
}
}
export function descendant(element: Element, name: Name): Descendant {
return Descendant.of(element, name);
}
export class Ancestor implements Equatable, Serializable<Ancestor.JSON> {
public static of(element: Element, name: Name): Ancestor {
return new Ancestor(element, name);
}
private readonly _element: Element;
private readonly _name: Name;
private constructor(element: Element, name: Name) {
this._element = element;
this._name = name;
}
public get type(): "ancestor" {
return "ancestor";
}
public get element(): Element {
return this._element;
}
public get name(): Name {
return this._name;
}
public equals(value: unknown): value is this {
return (
value instanceof Ancestor &&
value._element.equals(this._element) &&
value._name.equals(this._name)
);
}
public toJSON(): Ancestor.JSON {
return {
type: "ancestor",
element: this._element.path(),
name: this._name.toJSON(),
};
}
}
export namespace Ancestor {
export interface JSON {
[key: string]: json.JSON;
type: "ancestor";
element: string;
name: Name.JSON;
}
}
export function ancestor(element: Element, name: Name): Ancestor {
return Ancestor.of(element, name);
}
export class Label implements Equatable, Serializable<Label.JSON> {
public static of(attribute: Attribute): Label {
return new Label(attribute);
}
private readonly _attribute: Attribute;
private constructor(attribute: Attribute) {
this._attribute = attribute;
}
public get type(): "label" {
return "label";
}
public get attribute(): Attribute {
return this._attribute;
}
public equals(value: unknown): value is this {
return (
value instanceof Label && value._attribute.equals(this._attribute)
);
}
public toJSON(): Label.JSON {
return {
type: "label",
attribute: this._attribute.path(),
};
}
}
export namespace Label {
export interface JSON {
[key: string]: json.JSON;
type: "label";
attribute: string;
}
}
export function label(attribute: Attribute): Label {
return Label.of(attribute);
}
export class Reference implements Equatable, Serializable<Reference.JSON> {
public static of(attribute: Attribute, name: Name): Reference {
return new Reference(attribute, name);
}
private readonly _attribute: Attribute;
private readonly _name: Name;
private constructor(attribute: Attribute, name: Name) {
this._attribute = attribute;
this._name = name;
}
public get type(): "reference" {
return "reference";
}
public get attribute(): Attribute {
return this._attribute;
}
public get name(): Name {
return this._name;
}
public equals(value: unknown): value is this {
return (
value instanceof Reference && value._attribute.equals(this._attribute)
);
}
public toJSON(): Reference.JSON {
return {
type: "reference",
attribute: this._attribute.path(),
name: this._name.toJSON(),
};
}
}
export namespace Reference {
export interface JSON {
[key: string]: json.JSON;
type: "reference";
attribute: string;
name: Name.JSON;
}
}
export function reference(attribute: Attribute, name: Name): Reference {
return Reference.of(attribute, name);
}
}
/**
* @internal
*/
export class State implements Equatable, Serializable<State.JSON> {
private static _empty = new State([], None, false, false);
public static empty(): State {
return this._empty;
}
private readonly _visited: Array<Element>;
private readonly _referrer: Option<Element>;
private readonly _isRecursing: boolean;
private readonly _isDescending: boolean;
private constructor(
visited: Array<Element>,
referrer: Option<Element>,
isRecursing: boolean,
isDescending: boolean
) {
this._visited = visited;
this._referrer = referrer;
this._isRecursing = isRecursing;
this._isDescending = isDescending;
}
/**
* The elements that have been seen by the name computation so far. This is
* used for detecting circular references resulting from things such as the
* `aria-labelledby` attribute and form controls that get their name from
* a containing `<label>` element.
*/
public get visited(): Iterable<Element> {
return this._visited;
}
/**
* The element that referenced the name computation.
*/
public get referrer(): Option<Element> {
return this._referrer;
}
/**
* Whether or not the name computation is the result of recursion.
*/
public get isRecursing(): boolean {
return this._isRecursing;
}
/**
* Whether or not the name computation is the result of a reference.
*/
public get isReferencing(): boolean {
return this._referrer.isSome();
}
/**
* Whether or not the name computation is descending into a subtree.
*/
public get isDescending(): boolean {
return this._isDescending;
}
public hasVisited(element: Element): boolean {
return this._visited.includes(element);
}
public visit(element: Element): State {
if (this._visited.includes(element)) {
return this;
}
return new State(
[...this._visited, element],
this._referrer,
this._isRecursing,
this._isDescending
);
}
public recurse(isRecursing: boolean): State {
if (this._isRecursing === isRecursing) {
return this;
}
return new State(
this._visited,
this._referrer,
isRecursing,
this._isDescending
);
}
public reference(referrer: Option<Element>): State {
if (this._referrer.equals(referrer)) {
return this;
}
return new State(
this._visited,
referrer,
this._isRecursing,
this._isDescending
);
}
public descend(isDescending: boolean): State {
if (this._isDescending === isDescending) {
return this;
}
return new State(
this._visited,
this._referrer,
this._isRecursing,
isDescending
);
}
public equals(state: State): boolean;
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return (
value instanceof State &&
Array.equals(value._visited, this._visited) &&
value._referrer.equals(this._referrer) &&
value._isRecursing === this._isRecursing &&
value._isDescending === this._isDescending
);
}
public toJSON(): State.JSON {
return {
visited: this._visited.map((element) => element.path()),
referrer: this._referrer.map((element) => element.path()).getOr(null),
isRecursing: this._isRecursing,
isDescending: this._isDescending,
};
}
}
export namespace State {
export interface JSON {
[key: string]: json.JSON;
visited: Array<string>;
referrer: string | null;
isRecursing: boolean;
isDescending: boolean;
}
}
export function from(node: Element | Text, device: Device): Option<Name> {
return fromNode(node, device, State.empty());
}
const names = Cache.empty<Device, Cache<Node, Option<Name>>>();
/**
* @internal
*/
export function fromNode(
node: Element | Text,
device: Device,
state: State
): Option<Name> {
// Construct a thunk with the computed name of the node. We first need to
// decide whether or not we can pull the name of the node from the cache and
// so the actual computation of the name must be delayed.
const name = () =>
isElement(node) ? fromElement(node, device, state) : fromText(node);
if (isElement(node)) {
// As chained references are not allowed, we cannot make use of the cache
// when computing a referenced name. If, for example, <foo> references
// <bar> and <bar> references <baz>...
//
// <foo> -> <bar> -> <baz> "Hello world"
//
// ...the reference from <bar> to <baz> is only allowed to be followed
// when computing a name for <bar>:
//
// <bar> "Hello world" -> <baz> "Hello world"
//
// When computing the name for <foo>, however, the second reference must
// be ignored and the name for <bar> computed as if though the reference
// does not exist:
//
// <foo> null -> <bar> null
//
// We therefore cannot make use of whatever is in the cache for <bar>.
if (state.isReferencing) {
return name();
}
// If we're descending then the name already in the cache may not be
// relevant due to the last step of the name computation. If, for example,
// <baz> is a child of <bar> which is a child of <foo>...
//
// <foo>
// <bar>
// <baz> "Hello world"
//
// ...and the name of <baz> has already been computed as "Hello world" and
// we then compute the name of <bar> and <bar> is not allowed to be named
// by its contents, it will not have a name:
//
// <bar> null
// <baz> "Hello world"
//
// However, when we compute the name of <foo> and <foo> is allowed to be
// named by its contents, the last step of the same computation kicks in
// and includes all descendant names:
//
// <foo> "Hello world"
// <bar> "Hello world"
// <baz> "Hello world"
//
// We therefore cannot make use of whatever is in the cache for <bar>.
if (state.isDescending) {
return name();
}
}
return names.get(device, Cache.empty).get(node, name);
}
/**
* @internal
*/
export function fromElement(
element: Element,
device: Device,
state: State
): Option<Name> {
if (state.hasVisited(element)) {
// While self-references are allowed, any other forms of circular
// references are not. If the referrer therefore isn't the element itself,
// the result will be an empty name.
if (!state.referrer.includes(element)) {
return None;
}
} else {
state = state.visit(element);
}
// The following code handles the _generic_ steps of the accessible name
// computation, that is any steps that are shared for all namespaces. All
// remaining steps are handled by namespace-specific feature mappings.
const role = Role.from(element);
// Step 1: Does the role prohibit naming?
// https://w3c.github.io/accname/#step1
// Step 1 is skipped when referencing due to step 2B.ii.b
// https://w3c.github.io/accname/#step2B.ii.b
// Step 1 is skipped when descending due to step 2F.iii.b
// https://w3c.github.io/accname/#step2B.iii.b
if (
!state.isReferencing &&
!state.isDescending &&
role.some((role) => role.isNameProhibited())
) {
return None;
}
// Step 2A: Is the element hidden and not referenced?
// https://w3c.github.io/accname/#step2A
if (!state.isReferencing && isHidden(element, device)) {
return None;
}
return fromSteps(
// Step 2B: Use the `aria-labelledby` attribute, if present and allowed.
// https://w3c.github.io/accname/#step2B
() => {
// Chained `aria-labelledby` references, such `foo` -> `bar` -> `baz`,
// are not allowed. If the element is therefore being referenced
// already then this step produces an empty name.
if (state.isReferencing) {
return None;
}
const attribute = element.attribute("aria-labelledby");
if (attribute.isNone()) {
return None;
}
return fromReferences(attribute.get(), element, device, state);
},
// Step 2C: Use the `aria-label` attribute, if present.
// https://w3c.github.io/accname/#step2C
() => {
const attribute = element.attribute("aria-label");
if (attribute.isNone()) {
return None;
}
return fromLabel(attribute.get());
},
// Step 2D: Use native features, if present and allowed.
// https://w3c.github.io/accname/#step2D
() => {
// Using native features is only allowed if the role, if any, of the
// element is not presentational and the element has a namespace with
// which to look up its feature mapping, if it exists. If the role of
// element therefore is presentational or the element has no namespace
// then this step produces an empty name.
if (
role.some((role) => role.isPresentational()) ||
element.namespace.isNone()
) {
return None;
}
const feature = Feature.from(element.namespace.get(), element.name);
if (feature.isNone()) {
return None;
}
return feature.get().name(element, device, state);
},
// Step 2F: Use the subtree content, if referencing or allowed.
// https://w3c.github.io/accname/#step2F
() => {
// Using the subtree content is only allowed if the element is either
// being referenced or the role, if any, of the element allows it to
// be named by its content. If the element therefore isn't being
// referenced and is not allowed to be named by its content then this
// step produces an empty name.
if (
!state.isReferencing &&
!role.some((role) => role.isNamedBy("contents"))
) {
return None;
}
return fromDescendants(element, device, state);
},
// Step 2H: Use the subtree content, if descending.
// https://w3c.github.io/accname/#step2H
() => {
// Unless we're already descending then this step produces an empty
// name.
if (!state.isDescending) {
return None;
}
return fromDescendants(element, device, state);
}
);
}
/**
* @internal
*/
export function fromText(text: Text): Option<Name> {
// Step 2G: Use the data of the text node.
// https://w3c.github.io/accname/#step2G
return fromData(text);
}
/**
* @internal
*/
export function fromDescendants(
element: Element,
device: Device,
state: State
): Option<Name> {
const names = element
.children()
.filter(or(isText, isElement))
.collect((element) =>
fromNode(
element,
device,
state.reference(None).recurse(true).descend(true)
)
);
const name = flatten(names.map((name) => name.value).join("")).trim();
if (name === "") {
return None;
}
return Option.of(
Name.of(
name,
names.map((name) => Source.descendant(element, name))
)
);
}
/**
* @internal
*/
export function fromLabel(attribute: Attribute): Option<Name> {
const name = flatten(attribute.value);
if (name === "") {
return None;
}
return Option.of(Name.of(name, [Source.label(attribute)]));
}
/**
* @internal
*/
export function fromReferences(
attribute: Attribute,
referrer: Element,
device: Device,
state: State
): Option<Name> {
const root = attribute.owner.get().root();
const references = root
.descendants()
.filter(isElement)
.filter(hasId(equals(...attribute.tokens())));
const names = references.collect((element) =>
fromNode(
element,
device,
state.reference(Option.of(referrer)).recurse(true).descend(false)
)
);
const name = flatten(names.map((name) => name.value).join(" "));
if (name === "") {
return None;
}
return Option.of(
Name.of(name, [
Source.reference(
attribute,
Name.of(
name,
names.flatMap((name) => Sequence.from(name.source))
)
),
])
);
}
/**
* @internal
*/
export function fromData(text: Text): Option<Name> {
const name = flatten(text.data);
if (name === "") {
return None;
}
return Option.of(Name.of(name, [Source.data(text)]));
}
/**
* @internal
*/
export function fromSteps(
...steps: Array<Thunk<Option<Name>>>
): Option<Name> {
return Array.collectFirst(steps, (step) => step());
}
export const { hasValue } = predicate;
}
function flatten(string: string): string {
return string.replace(/\s+/g, " ");
}
function isRendered(node: Node, device: Device): boolean {
if (Element.isElement(node)) {
const display = Style.from(node, device).computed("display").value;
const {
values: [outside],
} = display;
if (outside.value === "none") {
return false;
}
}
return node
.parent({ flattened: true })
.every((parent) => isRendered(parent, device));
}
/**
* {@link https://w3c.github.io/accname/#dfn-hidden}
* {@link https://github.com/w3c/accname/issues/30}
*/
function isHidden(element: Element, device: Device): boolean {
return (
!isRendered(element, device) ||
element
.attribute("aria-hidden")
.some((attribute) => attribute.value.toLowerCase() === "true")
);
} | the_stack |
/*
* ---------------------------------------------------------
* Copyright(C) Microsoft Corporation. All rights reserved.
* ---------------------------------------------------------
*
* ---------------------------------------------------------
* Generated file, DO NOT EDIT
* ---------------------------------------------------------
*/
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import * as restm from 'typed-rest-client/RestClient';
import vsom = require('./VsoClient');
import basem = require('./ClientApiBases');
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import FeatureManagementInterfaces = require("./interfaces/FeatureManagementInterfaces");
export interface IFeatureManagementApi extends basem.ClientApiBase {
getFeature(featureId: string): Promise<FeatureManagementInterfaces.ContributedFeature>;
getFeatures(targetContributionId?: string): Promise<FeatureManagementInterfaces.ContributedFeature[]>;
getFeatureState(featureId: string, userScope: string): Promise<FeatureManagementInterfaces.ContributedFeatureState>;
setFeatureState(feature: FeatureManagementInterfaces.ContributedFeatureState, featureId: string, userScope: string, reason?: string, reasonCode?: string): Promise<FeatureManagementInterfaces.ContributedFeatureState>;
getFeatureStateForScope(featureId: string, userScope: string, scopeName: string, scopeValue: string): Promise<FeatureManagementInterfaces.ContributedFeatureState>;
setFeatureStateForScope(feature: FeatureManagementInterfaces.ContributedFeatureState, featureId: string, userScope: string, scopeName: string, scopeValue: string, reason?: string, reasonCode?: string): Promise<FeatureManagementInterfaces.ContributedFeatureState>;
queryFeatureStates(query: FeatureManagementInterfaces.ContributedFeatureStateQuery): Promise<FeatureManagementInterfaces.ContributedFeatureStateQuery>;
queryFeatureStatesForDefaultScope(query: FeatureManagementInterfaces.ContributedFeatureStateQuery, userScope: string): Promise<FeatureManagementInterfaces.ContributedFeatureStateQuery>;
queryFeatureStatesForNamedScope(query: FeatureManagementInterfaces.ContributedFeatureStateQuery, userScope: string, scopeName: string, scopeValue: string): Promise<FeatureManagementInterfaces.ContributedFeatureStateQuery>;
}
export class FeatureManagementApi extends basem.ClientApiBase implements IFeatureManagementApi {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions) {
super(baseUrl, handlers, 'node-FeatureManagement-api', options);
}
/**
* Get a specific feature by its id
*
* @param {string} featureId - The contribution id of the feature
*/
public async getFeature(
featureId: string
): Promise<FeatureManagementInterfaces.ContributedFeature> {
return new Promise<FeatureManagementInterfaces.ContributedFeature>(async (resolve, reject) => {
let routeValues: any = {
featureId: featureId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"FeatureManagement",
"c4209f25-7a27-41dd-9f04-06080c7b6afd",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FeatureManagementInterfaces.ContributedFeature>;
res = await this.rest.get<FeatureManagementInterfaces.ContributedFeature>(url, options);
let ret = this.formatResponse(res.result,
null,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Get a list of all defined features
*
* @param {string} targetContributionId - Optional target contribution. If null/empty, return all features. If specified include the features that target the specified contribution.
*/
public async getFeatures(
targetContributionId?: string
): Promise<FeatureManagementInterfaces.ContributedFeature[]> {
return new Promise<FeatureManagementInterfaces.ContributedFeature[]>(async (resolve, reject) => {
let routeValues: any = {
};
let queryValues: any = {
targetContributionId: targetContributionId,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"FeatureManagement",
"c4209f25-7a27-41dd-9f04-06080c7b6afd",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FeatureManagementInterfaces.ContributedFeature[]>;
res = await this.rest.get<FeatureManagementInterfaces.ContributedFeature[]>(url, options);
let ret = this.formatResponse(res.result,
null,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Get the state of the specified feature for the given user/all-users scope
*
* @param {string} featureId - Contribution id of the feature
* @param {string} userScope - User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
*/
public async getFeatureState(
featureId: string,
userScope: string
): Promise<FeatureManagementInterfaces.ContributedFeatureState> {
return new Promise<FeatureManagementInterfaces.ContributedFeatureState>(async (resolve, reject) => {
let routeValues: any = {
featureId: featureId,
userScope: userScope
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"FeatureManagement",
"98911314-3f9b-4eaf-80e8-83900d8e85d9",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FeatureManagementInterfaces.ContributedFeatureState>;
res = await this.rest.get<FeatureManagementInterfaces.ContributedFeatureState>(url, options);
let ret = this.formatResponse(res.result,
FeatureManagementInterfaces.TypeInfo.ContributedFeatureState,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Set the state of a feature
*
* @param {FeatureManagementInterfaces.ContributedFeatureState} feature - Posted feature state object. Should specify the effective value.
* @param {string} featureId - Contribution id of the feature
* @param {string} userScope - User-Scope at which to set the value. Should be "me" for the current user or "host" for all users.
* @param {string} reason - Reason for changing the state
* @param {string} reasonCode - Short reason code
*/
public async setFeatureState(
feature: FeatureManagementInterfaces.ContributedFeatureState,
featureId: string,
userScope: string,
reason?: string,
reasonCode?: string
): Promise<FeatureManagementInterfaces.ContributedFeatureState> {
return new Promise<FeatureManagementInterfaces.ContributedFeatureState>(async (resolve, reject) => {
let routeValues: any = {
featureId: featureId,
userScope: userScope
};
let queryValues: any = {
reason: reason,
reasonCode: reasonCode,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"FeatureManagement",
"98911314-3f9b-4eaf-80e8-83900d8e85d9",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FeatureManagementInterfaces.ContributedFeatureState>;
res = await this.rest.update<FeatureManagementInterfaces.ContributedFeatureState>(url, feature, options);
let ret = this.formatResponse(res.result,
FeatureManagementInterfaces.TypeInfo.ContributedFeatureState,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Get the state of the specified feature for the given named scope
*
* @param {string} featureId - Contribution id of the feature
* @param {string} userScope - User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
* @param {string} scopeName - Scope at which to get the feature setting for (e.g. "project" or "team")
* @param {string} scopeValue - Value of the scope (e.g. the project or team id)
*/
public async getFeatureStateForScope(
featureId: string,
userScope: string,
scopeName: string,
scopeValue: string
): Promise<FeatureManagementInterfaces.ContributedFeatureState> {
return new Promise<FeatureManagementInterfaces.ContributedFeatureState>(async (resolve, reject) => {
let routeValues: any = {
featureId: featureId,
userScope: userScope,
scopeName: scopeName,
scopeValue: scopeValue
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"FeatureManagement",
"dd291e43-aa9f-4cee-8465-a93c78e414a4",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FeatureManagementInterfaces.ContributedFeatureState>;
res = await this.rest.get<FeatureManagementInterfaces.ContributedFeatureState>(url, options);
let ret = this.formatResponse(res.result,
FeatureManagementInterfaces.TypeInfo.ContributedFeatureState,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Set the state of a feature at a specific scope
*
* @param {FeatureManagementInterfaces.ContributedFeatureState} feature - Posted feature state object. Should specify the effective value.
* @param {string} featureId - Contribution id of the feature
* @param {string} userScope - User-Scope at which to set the value. Should be "me" for the current user or "host" for all users.
* @param {string} scopeName - Scope at which to get the feature setting for (e.g. "project" or "team")
* @param {string} scopeValue - Value of the scope (e.g. the project or team id)
* @param {string} reason - Reason for changing the state
* @param {string} reasonCode - Short reason code
*/
public async setFeatureStateForScope(
feature: FeatureManagementInterfaces.ContributedFeatureState,
featureId: string,
userScope: string,
scopeName: string,
scopeValue: string,
reason?: string,
reasonCode?: string
): Promise<FeatureManagementInterfaces.ContributedFeatureState> {
return new Promise<FeatureManagementInterfaces.ContributedFeatureState>(async (resolve, reject) => {
let routeValues: any = {
featureId: featureId,
userScope: userScope,
scopeName: scopeName,
scopeValue: scopeValue
};
let queryValues: any = {
reason: reason,
reasonCode: reasonCode,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"FeatureManagement",
"dd291e43-aa9f-4cee-8465-a93c78e414a4",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FeatureManagementInterfaces.ContributedFeatureState>;
res = await this.rest.update<FeatureManagementInterfaces.ContributedFeatureState>(url, feature, options);
let ret = this.formatResponse(res.result,
FeatureManagementInterfaces.TypeInfo.ContributedFeatureState,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Get the effective state for a list of feature ids
*
* @param {FeatureManagementInterfaces.ContributedFeatureStateQuery} query - Features to query along with current scope values
*/
public async queryFeatureStates(
query: FeatureManagementInterfaces.ContributedFeatureStateQuery
): Promise<FeatureManagementInterfaces.ContributedFeatureStateQuery> {
return new Promise<FeatureManagementInterfaces.ContributedFeatureStateQuery>(async (resolve, reject) => {
let routeValues: any = {
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"FeatureManagement",
"2b4486ad-122b-400c-ae65-17b6672c1f9d",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FeatureManagementInterfaces.ContributedFeatureStateQuery>;
res = await this.rest.create<FeatureManagementInterfaces.ContributedFeatureStateQuery>(url, query, options);
let ret = this.formatResponse(res.result,
FeatureManagementInterfaces.TypeInfo.ContributedFeatureStateQuery,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Get the states of the specified features for the default scope
*
* @param {FeatureManagementInterfaces.ContributedFeatureStateQuery} query - Query describing the features to query.
* @param {string} userScope
*/
public async queryFeatureStatesForDefaultScope(
query: FeatureManagementInterfaces.ContributedFeatureStateQuery,
userScope: string
): Promise<FeatureManagementInterfaces.ContributedFeatureStateQuery> {
return new Promise<FeatureManagementInterfaces.ContributedFeatureStateQuery>(async (resolve, reject) => {
let routeValues: any = {
userScope: userScope
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"FeatureManagement",
"3f810f28-03e2-4239-b0bc-788add3005e5",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FeatureManagementInterfaces.ContributedFeatureStateQuery>;
res = await this.rest.create<FeatureManagementInterfaces.ContributedFeatureStateQuery>(url, query, options);
let ret = this.formatResponse(res.result,
FeatureManagementInterfaces.TypeInfo.ContributedFeatureStateQuery,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Get the states of the specified features for the specific named scope
*
* @param {FeatureManagementInterfaces.ContributedFeatureStateQuery} query - Query describing the features to query.
* @param {string} userScope
* @param {string} scopeName
* @param {string} scopeValue
*/
public async queryFeatureStatesForNamedScope(
query: FeatureManagementInterfaces.ContributedFeatureStateQuery,
userScope: string,
scopeName: string,
scopeValue: string
): Promise<FeatureManagementInterfaces.ContributedFeatureStateQuery> {
return new Promise<FeatureManagementInterfaces.ContributedFeatureStateQuery>(async (resolve, reject) => {
let routeValues: any = {
userScope: userScope,
scopeName: scopeName,
scopeValue: scopeValue
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"FeatureManagement",
"f29e997b-c2da-4d15-8380-765788a1a74c",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<FeatureManagementInterfaces.ContributedFeatureStateQuery>;
res = await this.rest.create<FeatureManagementInterfaces.ContributedFeatureStateQuery>(url, query, options);
let ret = this.formatResponse(res.result,
FeatureManagementInterfaces.TypeInfo.ContributedFeatureStateQuery,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/clustersMappers";
import * as Parameters from "../models/parameters";
import { EventHubManagementClientContext } from "../eventHubManagementClientContext";
/** Class representing a Clusters. */
export class Clusters {
private readonly client: EventHubManagementClientContext;
/**
* Create a Clusters.
* @param {EventHubManagementClientContext} client Reference to the service client.
*/
constructor(client: EventHubManagementClientContext) {
this.client = client;
}
/**
* List the quantity of available pre-provisioned Event Hubs Clusters, indexed by Azure region.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListAvailableClusterRegionResponse>
*/
listAvailableClusterRegion(options?: msRest.RequestOptionsBase): Promise<Models.ClustersListAvailableClusterRegionResponse>;
/**
* @param callback The callback
*/
listAvailableClusterRegion(callback: msRest.ServiceCallback<Models.AvailableClustersList>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listAvailableClusterRegion(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AvailableClustersList>): void;
listAvailableClusterRegion(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AvailableClustersList>, callback?: msRest.ServiceCallback<Models.AvailableClustersList>): Promise<Models.ClustersListAvailableClusterRegionResponse> {
return this.client.sendOperationRequest(
{
options
},
listAvailableClusterRegionOperationSpec,
callback) as Promise<Models.ClustersListAvailableClusterRegionResponse>;
}
/**
* Lists the available Event Hubs Clusters within an ARM resource group
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ClustersListByResourceGroupResponse>;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ClusterListResult>): void;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ClusterListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ClusterListResult>, callback?: msRest.ServiceCallback<Models.ClusterListResult>): Promise<Models.ClustersListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.ClustersListByResourceGroupResponse>;
}
/**
* Gets the resource description of the specified Event Hubs Cluster.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersGetResponse>
*/
get(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<Models.ClustersGetResponse>;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param callback The callback
*/
get(resourceGroupName: string, clusterName: string, callback: msRest.ServiceCallback<Models.Cluster>): void;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, clusterName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Cluster>): void;
get(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Cluster>, callback?: msRest.ServiceCallback<Models.Cluster>): Promise<Models.ClustersGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
options
},
getOperationSpec,
callback) as Promise<Models.ClustersGetResponse>;
}
/**
* Creates or updates an instance of an Event Hubs Cluster.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param parameters Parameters for creating a eventhub cluster resource.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, clusterName: string, parameters: Models.Cluster, options?: msRest.RequestOptionsBase): Promise<Models.ClustersCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(resourceGroupName,clusterName,parameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ClustersCreateOrUpdateResponse>;
}
/**
* Modifies mutable properties on the Event Hubs Cluster. This operation is idempotent.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param parameters The properties of the Event Hubs Cluster which should be updated.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersUpdateResponse>
*/
update(resourceGroupName: string, clusterName: string, parameters: Models.Cluster, options?: msRest.RequestOptionsBase): Promise<Models.ClustersUpdateResponse> {
return this.beginUpdate(resourceGroupName,clusterName,parameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ClustersUpdateResponse>;
}
/**
* Deletes an existing Event Hubs Cluster. This operation is idempotent.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(resourceGroupName,clusterName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* List all Event Hubs Namespace IDs in an Event Hubs Dedicated Cluster.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListNamespacesResponse>
*/
listNamespaces(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<Models.ClustersListNamespacesResponse>;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param callback The callback
*/
listNamespaces(resourceGroupName: string, clusterName: string, callback: msRest.ServiceCallback<Models.EHNamespaceIdListResult>): void;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param options The optional parameters
* @param callback The callback
*/
listNamespaces(resourceGroupName: string, clusterName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EHNamespaceIdListResult>): void;
listNamespaces(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EHNamespaceIdListResult>, callback?: msRest.ServiceCallback<Models.EHNamespaceIdListResult>): Promise<Models.ClustersListNamespacesResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
clusterName,
options
},
listNamespacesOperationSpec,
callback) as Promise<Models.ClustersListNamespacesResponse>;
}
/**
* Creates or updates an instance of an Event Hubs Cluster.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param parameters Parameters for creating a eventhub cluster resource.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(resourceGroupName: string, clusterName: string, parameters: Models.Cluster, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
parameters,
options
},
beginCreateOrUpdateOperationSpec,
options);
}
/**
* Modifies mutable properties on the Event Hubs Cluster. This operation is idempotent.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param parameters The properties of the Event Hubs Cluster which should be updated.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(resourceGroupName: string, clusterName: string, parameters: Models.Cluster, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
parameters,
options
},
beginUpdateOperationSpec,
options);
}
/**
* Deletes an existing Event Hubs Cluster. This operation is idempotent.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param clusterName The name of the Event Hubs Cluster.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
clusterName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Lists the available Event Hubs Clusters within an ARM resource group
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ClustersListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ClustersListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ClusterListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ClusterListResult>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ClusterListResult>, callback?: msRest.ServiceCallback<Models.ClusterListResult>): Promise<Models.ClustersListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.ClustersListByResourceGroupNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listAvailableClusterRegionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.EventHub/availableClusterRegions",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AvailableClustersList
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/clusters",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ClusterListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/clusters/{clusterName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.clusterName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Cluster
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listNamespacesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/clusters/{clusterName}/namespaces",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.clusterName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.EHNamespaceIdListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/clusters/{clusterName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.clusterName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Cluster,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Cluster
},
201: {
bodyMapper: Mappers.Cluster
},
202: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/clusters/{clusterName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.clusterName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Cluster,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Cluster
},
201: {
bodyMapper: Mappers.Cluster
},
202: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/clusters/{clusterName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.clusterName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ClusterListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import {
IWebPartContext
} from '@microsoft/sp-webpart-base';
import {
ITermStore,
ITermSet,
ITermGroup,
ITerm
} from '../common/SPEntities';
import {
IDataHelper
} from './DataHelperBase';
/**
* Interface for terms with path property and nested terns
*/
interface ITermWithTerms extends ITerm {
/**
* Term's path
*/
path: string[];
/**
* Term's full path
*/
fullPath: string;
/**
* child terms
*/
terms?: ITerms;
}
/**
* Interface that represents a map wit key term ID and value ITermWithTerms object
*/
interface ITerms {
[name: string]: ITermWithTerms;
}
/**
* Interface that represents a map with key term set ID and value ITerms object
*/
interface ITermSetTerms {
[name: string]: ITerms;
}
/**
* SharePoint Data Helper class.
* Gets information from current web
*/
export class DataHelperSP implements IDataHelper {
/**
* cached term stores. This property can be changed to static to be able to use the same cache in different web parts
*/
private _loadedTermStores: SP.Taxonomy.ITermStoreCollection;
/**
* cached terms' hierarchy. This property can be changed to static to be able to use the same cache in different web parts
*/
private _loadedTermsHierarchy: ITermSetTerms = {};
/**
* cached terms' flat list. This property can be changed to static to be able to use the same cache in different web parts
*/
private _loadedTermsFlat: ITerms[] = [];
/**
* Web part context
*/
public context: IWebPartContext;
/**
* ctor
* @param context: web part context
*/
public constructor(_context: IWebPartContext) {
this.context = _context;
}
/**
* API to get Term Stores
*/
public getTermStores(): Promise<ITermStore[]> {
return new Promise<ITermStore[]>((resolve) => {
// term stores have been already loaded
if (this._loadedTermStores) {
// converting SP.Taxonomy.ITermStore object to ITermStore objects
const termStoreEntities: ITermStore[] = this.getTermStoreEntities(this._loadedTermStores);
resolve(termStoreEntities);
return;
}
//
// need to load term stores
//
this.loadScripts().then(() => { // loading scripts first
const taxonomySession = this.taxonomySession;
let termStores = taxonomySession.get_termStores();
this.clientContext.load(termStores);
this.clientContext.executeQueryAsync(() => {
// converting SP.Taxonomy.ITermStore object to ITermStore objects
const termStoreEntities: ITermStore[] = this.getTermStoreEntities(termStores);
// caching loaded term stores
this._loadedTermStores = termStores;
resolve(termStoreEntities);
}, () => {
resolve([]);
});
});
});
}
/**
* API to get Term Groups by Term Store
*/
public getTermGroups(termStoreId: string): Promise<ITermGroup[]> {
return new Promise<ITermGroup[]>((resolve) => {
this.getTermStoreById(termStoreId).then((termStore) => { // getting the term store
if (!termStore) {
resolve([]);
return;
}
let groups = termStore.get_groups();
//
// if Groups property is not loaded get_count will throw an error that will be handled to retrieve groups
//
try {
if (!groups.get_count()) { // this will throw error if groups were not loaded
resolve([]);
return;
}
// converting SP.Taxonomy.ITermGroup object to ITermGroup objects
resolve(this.getTermGroupEntities(groups, termStore.get_id().toString()));
}
catch (ex) { // retrieving groups
this.clientContext.load(groups);
this.clientContext.executeQueryAsync(() => {
// converting SP.Taxonomy.ITermGroup object to ITermGroup objects
resolve(this.getTermGroupEntities(groups, termStore.get_id().toString()));
}, () => {
resolve([]);
});
}
finally {
}
});
});
}
/**
* API to get Term Sets by Term Group
*/
public getTermSets(termGroup: ITermGroup): Promise<ITermSet[]> {
return new Promise<ITermSet[]>((resolve) => {
this.getTermStoreById(termGroup.termStoreId).then((termStore) => { // getting term store by id
if (!termStore) {
resolve([]);
return;
}
this.getTermGroupById(termStore, termGroup.id).then((group) => { // getting term group by id
if (!group) {
resolve([]);
return;
}
let termSets = group.get_termSets();
//
// if termSets property is not loaded get_count will throw an error that will be handled to retrieve term sets
//
try {
if (!termSets.get_count()) { // this will throw error if term sets were not loaded
resolve([]);
return;
}
//converting SP.Taxonomy.ITermSet object to ITermSet object
resolve(this.getTermSetEntities(termSets, termGroup.id, termGroup.termStoreId));
}
catch (ex) { // retrieving term sets
this.clientContext.load(termSets);
this.clientContext.executeQueryAsync(() => {
//converting SP.Taxonomy.ITermSet object to ITermSet object
resolve(this.getTermSetEntities(termSets, termGroup.id, termGroup.termStoreId));
}, () => {
resolve([]);
});
}
finally {
}
});
});
});
}
/**
* API to get Terms by Term Set
*/
public getTerms(termSet: ITermSet): Promise<ITerm[]> {
return new Promise<ITerm[]>((resolve) => {
// checking if terms were previously loaded
if (this._loadedTermsHierarchy[termSet.id]) {
const termSetTerms = this._loadedTermsHierarchy[termSet.id];
// converting ITerms object to collection of ITerm objects
resolve(this.getTermEntities(termSetTerms));
return;
}
//
// need to load terms
//
this.getTermStoreById(termSet.termStoreId).then((termStore) => { // getting store by id
if (!termStore) {
resolve([]);
return;
}
this.getTermGroupById(termStore, termSet.termGroupId).then((group) => { // getting group by id
if (!group) {
resolve([]);
return;
}
this.getTermSetById(termStore, group, termSet.id).then((set) => { // getting term set by id
if (!set) {
resolve([]);
return;
}
let allTerms: SP.Taxonomy.ITermCollection;
//
// if terms property is not loaded get_count will throw an error that will be handled to retrieve terms
//
try {
allTerms = set.getAllTerms();
if (!allTerms.get_count()) { // this will throw error if terms were not loaded
resolve([]);
return;
}
// caching terms
this._loadedTermsHierarchy[termSet.id] = this.buildTermsHierarchy(allTerms, termSet.id);
// converting ITerms object to collection of ITerm objects
resolve(this.getTermEntities(this._loadedTermsHierarchy[termSet.id]));
}
catch (ex) { // retrieving terms
this.clientContext.load(allTerms, 'Include(Id, Name, Description, IsRoot, TermsCount, PathOfTerm, Labels)');
this.clientContext.executeQueryAsync(() => {
// caching terms
this._loadedTermsHierarchy[termSet.id] = this.buildTermsHierarchy(allTerms, termSet.id);
// converting ITerms object to collection of ITerm objects
resolve(this.getTermEntities(this._loadedTermsHierarchy[termSet.id]));
}, () => {
resolve([]);
});
}
finally { }
});
});
});
});
}
/**
* API to get Terms by Term
*/
public getChildTerms(term: ITerm): Promise<ITerm[]> {
return new Promise<ITerm[]>((resolve) => {
if (!this._loadedTermsFlat.length) {
//
// We can add logic to retrieve term from term Store
// But I'll skip it for this example
//
resolve([]);
return;
}
let terms: ITerms;
// iterating through flat list of terms to find needed one
for (let i = 0, len = this._loadedTermsFlat.length; i < len; i++) {
const currTerm = this._loadedTermsFlat[i][term.id];
if (currTerm) {
terms = currTerm.terms;
break;
}
}
if (!terms) {
resolve([]);
return;
}
// converting ITerms object to collection of ITerm objects
resolve(this.getTermEntities(terms));
});
}
/**
* Loads scripts that are needed to work with taxonomy
*/
private loadScripts(): Promise<void> {
return new Promise<void>((resolve) => {
//
// constructing path to Layouts folder
//
let layoutsUrl: string = this.context.pageContext.site.absoluteUrl;
if (layoutsUrl.lastIndexOf('/') === layoutsUrl.length - 1)
layoutsUrl = layoutsUrl.slice(0, -1);
layoutsUrl += '/_layouts/15/';
this.loadScript(layoutsUrl + 'init.js', 'Sod').then(() => { // loading init.js
return this.loadScript(layoutsUrl + 'sp.runtime.js', 'sp_runtime_initialize'); // loading sp.runtime.js
}).then(() => {
return this.loadScript(layoutsUrl + 'sp.js', 'sp_initialize'); // loading sp.js
}).then(() => {
return this.loadScript(layoutsUrl + 'sp.taxonomy.js', 'SP.Taxonomy'); // loading sp.taxonomy.js
}).then(() => {
resolve();
});
});
}
/**
* Loads script
* @param url: script src
* @param globalObjectName: name of global object to check if it is loaded to the page
*/
private loadScript(url: string, globalObjectName: string): Promise<void> {
return new Promise<void>((resolve) => {
let isLoaded = true;
if (globalObjectName.indexOf('.') !== -1) {
const props = globalObjectName.split('.');
let currObj: any = window;
for (let i = 0, len = props.length; i < len; i++) {
if (!currObj[props[i]]) {
isLoaded = false;
break;
}
currObj = currObj[props[i]];
}
}
else {
isLoaded = !!window[globalObjectName];
}
// checking if the script was previously added to the page
if (isLoaded || document.head.querySelector('script[src="' + url + '"]')) {
resolve();
return;
}
// loading the script
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onload = () => {
resolve();
};
document.head.appendChild(script);
});
}
/**
* Taxonomy session getter
*/
private get taxonomySession(): SP.Taxonomy.TaxonomySession {
return SP.Taxonomy.TaxonomySession.getTaxonomySession(this.clientContext);
}
/**
* Client Context getter
*/
private get clientContext(): SP.ClientContext {
return SP.ClientContext.get_current();
}
/**
* Converts SP.Taxonomy.ITermStore objects to ITermStore objects
* @param termStores: SP.Taxonomy.ITermStoreCollection object
*/
private getTermStoreEntities(termStores: SP.Taxonomy.ITermStoreCollection): ITermStore[] {
if (!termStores)
return [];
const termStoreEntities: ITermStore[] = [];
for (let i = 0, len = termStores.get_count(); i < len; i++) {
const termStore = termStores.get_item(i);
termStoreEntities.push({
id: termStore.get_id().toString(),
name: termStore.get_name()
});
}
return termStoreEntities;
}
/**
* Converts SP.Taxonomy.ITermGroup objects to ITermGroup objects
* @param termGroups: SP.Taxonomy.ITermGroupCollection object
* @param termStoreId: the identifier of parent term store
*/
private getTermGroupEntities(termGroups: SP.Taxonomy.ITermGroupCollection, termStoreId: string): ITermGroup[] {
if (!termGroups)
return [];
const termGroupEntities: ITermGroup[] = [];
for (let i = 0, len = termGroups.get_count(); i < len; i++) {
const termGroup = termGroups.get_item(i);
termGroupEntities.push({
id: termGroup.get_id().toString(),
termStoreId: termStoreId,
name: termGroup.get_name(),
description: termGroup.get_description()
});
}
return termGroupEntities;
}
/**
* Converts SP.Taxonomy.ITermSet objects to ITermSet objects
* @param termSets: SP.Taxonomy.ITermSetCollection object
* @param termGroupId: the identifier of parent term group
* @param termStoreId: the identifier of parent term store
*/
private getTermSetEntities(termSets: SP.Taxonomy.ITermSetCollection, termGroupId: string, termStoreId: string): ITermSet[] {
if (!termSets)
return [];
const termSetEntities: ITermSet[] = [];
for (let i = 0, len = termSets.get_count(); i < len; i++) {
const termSet = termSets.get_item(i);
termSetEntities.push({
id: termSet.get_id().toString(),
name: termSet.get_name(),
description: termSet.get_description(),
termGroupId: termGroupId,
termStoreId: termStoreId
});
}
return termSetEntities;
}
/**
* Retrieves term store by its id
* @param termStoreId: the identifier of the store to retrieve
*/
private getTermStoreById(termStoreId: string): Promise<SP.Taxonomy.ITermStore> {
return new Promise<SP.Taxonomy.ITermStore>((resolve) => {
if (!this._loadedTermStores) { // term stores were not loaded, need to load them
this.getTermStores().then(() => {
return this.getTermStoreById(termStoreId);
});
}
else { // term stores are loaded
let termStore = null;
if (this._loadedTermStores) {
for (let i = 0, len = this._loadedTermStores.get_count(); i < len; i++) {
if (this._loadedTermStores.get_item(i).get_id().toString() === termStoreId) {
termStore = this._loadedTermStores.get_item(i);
break;
}
}
}
resolve(termStore);
}
});
}
/**
* Retrieves term group by its id and parent term store
* @param termStore: parent term store
* @param termGroupId: the identifier of the group to retrieve
*/
private getTermGroupById(termStore: SP.Taxonomy.ITermStore, termGroupId: string): Promise<SP.Taxonomy.ITermGroup> {
return new Promise<SP.Taxonomy.ITermGroup>((resolve) => {
if (!termStore || !termGroupId) {
resolve(null);
return;
}
let result: SP.Taxonomy.ITermGroup;
//
// if Groups property is not loaded get_count will throw an error that will be handled to retrieve groups
//
try {
const groups: SP.Taxonomy.ITermGroupCollection = termStore.get_groups();
const groupsCount: number = groups.get_count();
const groupIdUpper = termGroupId.toUpperCase();
for (let i = 0; i < groupsCount; i++) {
const currGroup: SP.Taxonomy.ITermGroup = groups.get_item(i);
if (currGroup.get_id().toString().toUpperCase() === groupIdUpper) {
result = currGroup;
break;
}
}
if (!result) { // throwing an exception to try to load the group from server again
throw new Error();
}
resolve(result);
}
catch (ex) { // retrieving the groups from server
result = termStore.getGroup(termGroupId);
this.clientContext.load(result);
this.clientContext.executeQueryAsync(() => {
resolve(result);
}, () => {
resolve(null);
});
}
finally { }
});
}
/**
* Retrieves term set by its id, parent group and parent store
* @param termStore: parent term store
* @param termGroup: parent term group
* @param termSetId: the identifier of the term set to retrieve
*/
private getTermSetById(termStore: SP.Taxonomy.ITermStore, termGroup: SP.Taxonomy.ITermGroup, termSetId: string): Promise<SP.Taxonomy.ITermSet> {
return new Promise<SP.Taxonomy.ITermSet>((resolve) => {
if (!termGroup || !termSetId) {
resolve(null);
return;
}
let result: SP.Taxonomy.ITermSet;
//
// if termSets property is not loaded get_count will throw an error that will be handled to retrieve term sets
//
try {
const termSets: SP.Taxonomy.ITermSetCollection = termGroup.get_termSets();
const setsCount: number = termSets.get_count();
const setIdUpper = termSetId.toUpperCase();
for (let i = 0; i < setsCount; i++) {
const currSet: SP.Taxonomy.ITermSet = termSets.get_item(i);
if (currSet.get_id().toString().toUpperCase() === setIdUpper) {
result = currSet;
break;
}
}
if (!result) { // throwing an exception to try to load the term set from server again
throw new Error();
}
resolve(result);
}
catch (ex) {
result = termStore.getTermSet(termSetId);
this.clientContext.load(result);
this.clientContext.executeQueryAsync(() => {
resolve(result);
}, () => {
resolve(null);
});
}
finally { }
});
}
/**
* Builds terms' hierarchy and also caches flat list of terms
* @param terms: SP.Taxonomy.ITermCollection object
* @param termSetId: the indetifier of parent term set
*/
private buildTermsHierarchy(terms: SP.Taxonomy.ITermCollection, termSetId: string): ITerms {
if (!terms)
return {};
const tree: ITerms = {};
const flat: ITerms = {};
//
// Iterating through terms to collect flat list and create ITermWithTerms instances
//
for (let i = 0, len = terms.get_count(); i < len; i++) {
const term = terms.get_item(i);
// creating instance
const termEntity: ITermWithTerms = {
id: term.get_id().toString(),
name: term.get_name(),
description: term.get_description(),
labels: [],
termsCount: term.get_termsCount(),
isRoot: term.get_isRoot(),
path: term.get_pathOfTerm().split(';'),
fullPath:term.get_pathOfTerm(),
termSetId: termSetId
};
//
// settings labels
//
const labels = term.get_labels();
for (let lblIdx = 0, lblLen = labels.get_count(); lblIdx < lblLen; lblIdx++) {
const lbl = labels.get_item(lblIdx);
termEntity.labels.push({
isDefaultForLanguage: lbl.get_isDefaultForLanguage(),
value: lbl.get_value(),
language: lbl.get_language()
});
}
// if term is root we need to add it to the tree
if (termEntity.isRoot) {
tree[termEntity.id] = termEntity;
}
// adding term entity to flat list
flat[termEntity.id] = termEntity;
}
const keys = Object.keys(flat);
//
// iterating through flat list of terms to build the tree structure
//
for (let keyIdx = 0, keysLength = keys.length; keyIdx < keysLength; keyIdx++) {
const key = keys[keyIdx];
const currentTerm = flat[key];
// skipping root items
if (currentTerm.isRoot) continue;
// getting parent term name
const termParentName = currentTerm.path[currentTerm.path.length - 2];
//
// second iteration to get parent term in flat list
//
for (let keySecondIndex = 0; keySecondIndex < keysLength; keySecondIndex++) {
const secondTerm = flat[keys[keySecondIndex]];
if (secondTerm.name === termParentName && secondTerm.path.length == currentTerm.path.length-1 && currentTerm.fullPath.indexOf(secondTerm.fullPath)==0) {
if (!secondTerm.terms)
secondTerm.terms = {};
secondTerm.terms[currentTerm.id] = currentTerm;
}
}
}
this._loadedTermsFlat.push(flat);
return tree;
}
/**
* Converts ITerms object to collection of ITerm objects
* @param terms: ITerms object
*/
private getTermEntities(terms: ITerms): ITerm[] {
const termsKeys = Object.keys(terms);
const termEntities: ITerm[] = [];
for (let keyIdx = 0, keysLength = termsKeys.length; keyIdx < keysLength; keyIdx++) {
termEntities.push(terms[termsKeys[keyIdx]]);
}
return termEntities;
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_ocoutboundmessage_Information {
interface Header extends DevKit.Controls.IHeader {
/** Unique identifier of the user or team who owns the activity. */
OwnerId: DevKit.Controls.Lookup;
/** Priority of the activity. */
PriorityCode: DevKit.Controls.OptionSet;
/** Scheduled end time of the activity. */
ScheduledEnd: DevKit.Controls.DateTime;
/** Status of the activity. */
StateCode: DevKit.Controls.OptionSet;
}
interface tab__D7D88659_2ED3_45F1_977B_4F32B69EE89D_Sections {
}
interface tab__D7D88659_2ED3_45F1_977B_4F32B69EE89D extends DevKit.Controls.ITab {
Section: tab__D7D88659_2ED3_45F1_977B_4F32B69EE89D_Sections;
}
interface Tabs {
_D7D88659_2ED3_45F1_977B_4F32B69EE89D: tab__D7D88659_2ED3_45F1_977B_4F32B69EE89D;
}
interface Body {
Tab: Tabs;
/** Outbound message delivery failure reason. */
msdyn_failurereason: DevKit.Controls.String;
/** Failure status code of outbound message */
msdyn_failurestatuscode: DevKit.Controls.Integer;
/** The channel(s) in the conversation. */
msdyn_occhanneltype: DevKit.Controls.MultiOptionSet;
/** Message text. */
msdyn_ocmessagetext: DevKit.Controls.String;
/** Unique identifier of the user or team who owns the activity. */
OwnerId: DevKit.Controls.Lookup;
/** Unique identifier of the object with which the activity is associated. */
RegardingObjectId: DevKit.Controls.Lookup;
/** Subject associated with the activity. */
Subject: DevKit.Controls.String;
}
}
class Formmsdyn_ocoutboundmessage_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_ocoutboundmessage_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_ocoutboundmessage_Information */
Body: DevKit.Formmsdyn_ocoutboundmessage_Information.Body;
/** The Header section of form msdyn_ocoutboundmessage_Information */
Header: DevKit.Formmsdyn_ocoutboundmessage_Information.Header;
}
class msdyn_ocoutboundmessageApi {
/**
* DynamicsCrm.DevKit msdyn_ocoutboundmessageApi
* @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;
/** Outbound message delivery failure reason. */
msdyn_failurereason: DevKit.WebApi.StringValue;
/** Failure status code of outbound message */
msdyn_failurestatuscode: DevKit.WebApi.IntegerValue;
/** Channel Provider Name. */
msdyn_occhannelprovidername: DevKit.WebApi.StringValue;
/** The channel(s) in the conversation. */
msdyn_occhanneltype: DevKit.WebApi.MultiOptionSetValue;
/** Customer preferred locale */
msdyn_occustomerlocale: DevKit.WebApi.LookupValue;
/** Work stream associated to the conversation */
msdyn_ocliveworkstreamid: DevKit.WebApi.LookupValue;
/** Message text. */
msdyn_ocmessagetext: DevKit.WebApi.StringValue;
/** Message type */
msdyn_ocmessagetype: DevKit.WebApi.OptionSetValue;
/** Associated Outbound Configuration. */
msdyn_ocoutboundconfiguration: DevKit.WebApi.LookupValue;
/** This can be an SMS number, Facebook page id, etc. */
msdyn_ocReceiverChannelId: DevKit.WebApi.StringValue;
/** This can be an SMS number, Facebook page id, etc. */
msdyn_ocsenderChannelId: DevKit.WebApi.StringValue;
/** Shows how long, in minutes, that the record was on hold. */
OnHoldTime: DevKit.WebApi.IntegerValueReadonly;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the business unit that owns the activity. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the team that owns the activity. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user that owns the activity. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** For internal use only. */
PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Priority of the activity. */
PriorityCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the Process. */
ProcessId: DevKit.WebApi.GuidValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_account_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_bookableresourcebooking_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_bookableresourcebookingheader_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_bulkoperation_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_campaign_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_campaignactivity_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_contact_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_contract_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_entitlement_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_entitlementtemplate_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_incident_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_new_interactionforemail_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_invoice_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_knowledgearticle_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_knowledgebaserecord_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_lead_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreement_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingdate_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingincident_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingservice_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingservicetask_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingsetup_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementinvoicedate_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementinvoiceproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementinvoicesetup_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_bookingalertstatus_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_bookingrule_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_bookingtimestamp_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_customerasset_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_fieldservicesetting_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_incidenttypecharacteristic_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_incidenttypeproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_incidenttypeservice_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventoryadjustment_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventoryadjustmentproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventoryjournal_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventorytransfer_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_payment_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_paymentdetail_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_paymentmethod_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_paymentterm_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_playbookinstance_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_postalbum_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_postalcode_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_processnotes_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_productinventory_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_projectteam_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorder_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderbill_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderreceipt_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderreceiptproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseordersubstatus_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingincident_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingservice_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingservicetask_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_resourceterritory_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rma_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmaproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmareceipt_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmareceiptproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmasubstatus_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rtv_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rtvproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rtvsubstatus_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_shipvia_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_systemuserschedulersetting_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_timegroup_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_timegroupdetail_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_timeoffrequest_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_warehouse_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorder_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workordercharacteristic_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderincident_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderproduct_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderresourcerestriction_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderservice_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderservicetask_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_opportunity_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_quote_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_salesorder_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_site_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_action_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_hostedapplication_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_nonhostedapplication_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_option_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_savedsession_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_workflow_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_workflowstep_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_workflow_workflowstep_mapping_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
RegardingObjectIdYomiName: DevKit.WebApi.StringValue;
/** Scheduled duration of the activity, specified in minutes. */
ScheduledDurationMinutes: DevKit.WebApi.IntegerValue;
/** Scheduled end time of the activity. */
ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Scheduled start time of the activity. */
ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Unique identifier of the mailbox associated with the sender of the email message. */
SenderMailboxId: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the activity was sent. */
SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Uniqueidentifier specifying the id of recurring series of an instance. */
SeriesId: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of an associated service. */
ServiceId: DevKit.WebApi.LookupValue;
/** Choose the service level agreement (SLA) that you want to apply to the case record. */
SLAId: DevKit.WebApi.LookupValue;
/** Last SLA that was applied to this case. This field is for internal use only. */
SLAInvokedId: DevKit.WebApi.LookupValueReadonly;
SLAName: DevKit.WebApi.StringValueReadonly;
/** Shows the date and time by which the activities are sorted. */
SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Unique identifier of the Stage. */
StageId: DevKit.WebApi.GuidValue;
/** Status of the activity. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the activity. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Subject associated with the activity. */
Subject: DevKit.WebApi.StringValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the currency associated with the activitypointer. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** For internal use only. */
TraversedPath: DevKit.WebApi.StringValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version number of the activity. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** The array of object that can cast object to ActivityPartyApi class */
ActivityParties: Array<any>;
}
}
declare namespace OptionSet {
namespace msdyn_ocoutboundmessage {
enum Community {
/** 5 */
Cortana,
/** 6 */
Direct_Line,
/** 8 */
Direct_Line_Speech,
/** 9 */
Email,
/** 1 */
Facebook,
/** 10 */
GroupMe,
/** 11 */
Kik,
/** 3 */
Line,
/** 7 */
Microsoft_Teams,
/** 0 */
Other,
/** 13 */
Skype,
/** 14 */
Slack,
/** 12 */
Telegram,
/** 2 */
Twitter,
/** 4 */
Wechat,
/** 15 */
WhatsApp
}
enum DeliveryPriorityCode {
/** 2 */
High,
/** 0 */
Low,
/** 1 */
Normal
}
enum InstanceTypeCode {
/** 0 */
Not_Recurring,
/** 3 */
Recurring_Exception,
/** 4 */
Recurring_Future_Exception,
/** 2 */
Recurring_Instance,
/** 1 */
Recurring_Master
}
enum msdyn_occhanneltype {
/** 192390000 */
Co_browse,
/** 192350002 */
Custom,
/** 192350000 */
Entity_Records,
/** 192330000 */
Facebook,
/** 192310000 */
LINE,
/** 192360000 */
Live_chat,
/** 19241000 */
Microsoft_Teams,
/** 192400000 */
Screen_sharing,
/** 192340000 */
SMS,
/** 192350001 */
Twitter,
/** 192380000 */
Video,
/** 192370000 */
Voice,
/** 192320000 */
WeChat,
/** 192300000 */
WhatsApp
}
enum msdyn_ocmessagetype {
/** 100000001 */
Create_conversation_on_send,
/** 100000000 */
Create_conversation_when_customer_responds_
}
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 { ServiceClientOptions } from "@azure/ms-rest-js";
import * as msRest from "@azure/ms-rest-js";
/**
* Defines the query context that Bing used for the request.
*/
export interface QueryContext {
/**
* Polymorphic Discriminator
*/
_type: "QueryContext";
/**
* The query string as specified in the request.
*/
originalQuery: string;
/**
* The query string used by Bing to perform the query. Bing uses the altered query string if the
* original query string contained spelling mistakes. For example, if the query string is "saling
* downwind", the altered query string will be "sailing downwind". This field is included only if
* the original query string contains a spelling mistake.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly alteredQuery?: string;
/**
* AlteredQuery that is formatted for display purpose. The query string in the
* AlterationDisplayQuery can be html-escaped and can contain hit-highlighting characters
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly alterationDisplayQuery?: string;
/**
* The query string to use to force Bing to use the original string. For example, if the query
* string is "saling downwind", the override query string will be "+saling downwind". Remember to
* encode the query string which results in "%2Bsaling+downwind". This field is included only if
* the original query string contains a spelling mistake.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly alterationOverrideQuery?: string;
/**
* A Boolean value that indicates whether the specified query has adult intent. The value is true
* if the query has adult intent; otherwise, false.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adultIntent?: boolean;
/**
* A Boolean value that indicates whether Bing requires the user's location to provide accurate
* results. If you specified the user's location by using the X-MSEdge-ClientIP and
* X-Search-Location headers, you can ignore this field. For location aware queries, such as
* "today's weather" or "restaurants near me" that need the user's location to provide accurate
* results, this field is set to true. For location aware queries that include the location (for
* example, "Seattle weather"), this field is set to false. This field is also set to false for
* queries that are not location aware, such as "best sellers".
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly askUserForLocation?: boolean;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isTransactional?: boolean;
}
/**
* Defines additional information about an entity such as type hints.
*/
export interface EntitiesEntityPresentationInfo {
/**
* Polymorphic Discriminator
*/
_type: "Entities/EntityPresentationInfo";
/**
* The supported scenario. Possible values include: 'DominantEntity', 'DisambiguationItem',
* 'ListItem'. Default value: 'DominantEntity'.
*/
entityScenario: EntityScenario;
/**
* A list of hints that indicate the entity's type. The list could contain a single hint such as
* Movie or a list of hints such as Place, LocalBusiness, Restaurant. Each successive hint in the
* array narrows the entity's type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityTypeHints?: EntityType[];
/**
* A display version of the entity hint. For example, if entityTypeHints is Artist, this field
* may be set to American Singer.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityTypeDisplayHint?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly query?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entitySubTypeHints?: string[];
}
/**
* Contains the possible cases for ResponseBase.
*/
export type ResponseBaseUnion = ResponseBase | IdentifiableUnion;
/**
* Response base
*/
export interface ResponseBase {
/**
* Polymorphic Discriminator
*/
_type: "ResponseBase";
}
/**
* Contains the possible cases for Identifiable.
*/
export type IdentifiableUnion = Identifiable | ResponseUnion;
/**
* Defines the identity of a resource.
*/
export interface Identifiable {
/**
* Polymorphic Discriminator
*/
_type: "Identifiable";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
}
/**
* Contains the possible cases for Response.
*/
export type ResponseUnion = Response | ThingUnion | SearchResponse | AnswerUnion | ErrorResponse;
/**
* Defines a response. All schemas that return at the root of the response must inherit from this
* object.
*/
export interface Response {
/**
* Polymorphic Discriminator
*/
_type: "Response";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
}
/**
* Contains the possible cases for Thing.
*/
export type ThingUnion = Thing | Place | CreativeWorkUnion | IntangibleUnion;
/**
* Defines a thing.
*/
export interface Thing {
/**
* Polymorphic Discriminator
*/
_type: "Thing";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* The name of the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The URL to get more information about the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly url?: string;
/**
* Additional information about the entity such as hints that you can use to determine the
* entity's type. To determine the entity's type, use the entityScenario and entityTypeHint
* fields.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityPresentationInfo?: EntitiesEntityPresentationInfo;
}
/**
* Contains the possible cases for Answer.
*/
export type AnswerUnion = Answer | SearchResultsAnswerUnion;
/**
* Defines an answer.
*/
export interface Answer {
/**
* Polymorphic Discriminator
*/
_type: "Answer";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
}
/**
* Contains the possible cases for SearchResultsAnswer.
*/
export type SearchResultsAnswerUnion = SearchResultsAnswer | Places;
/**
* Defines a search result answer.
*/
export interface SearchResultsAnswer {
/**
* Polymorphic Discriminator
*/
_type: "SearchResultsAnswer";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly queryContext?: QueryContext;
/**
* The estimated number of webpages that are relevant to the query. Use this number along with
* the count and offset query parameters to page the results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly totalEstimatedMatches?: number;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isFamilyFriendly?: boolean;
}
/**
* Defines a local entity answer.
*/
export interface Places {
/**
* Polymorphic Discriminator
*/
_type: "Places";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly queryContext?: QueryContext;
/**
* The estimated number of webpages that are relevant to the query. Use this number along with
* the count and offset query parameters to page the results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly totalEstimatedMatches?: number;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isFamilyFriendly?: boolean;
/**
* A list of local entities, such as restaurants or hotels.
*/
value: ThingUnion[];
}
/**
* Defines the top-level object that the response includes when the request succeeds.
*/
export interface SearchResponse {
/**
* Polymorphic Discriminator
*/
_type: "SearchResponse";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* An object that contains the query string that Bing used for the request. This object contains
* the query string as entered by the user. It may also contain an altered query string that Bing
* used for the query if the query string contained a spelling mistake.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly queryContext?: QueryContext;
/**
* A list of local entities such as restaurants or hotels that are relevant to the query.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly places?: Places;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly lottery?: SearchResultsAnswerUnion;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly searchResultsConfidenceScore?: number;
}
/**
* An interface representing GeoCoordinates.
*/
export interface GeoCoordinates {
/**
* Polymorphic Discriminator
*/
_type: "GeoCoordinates";
latitude: number;
longitude: number;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly elevation?: number;
}
/**
* Contains the possible cases for Intangible.
*/
export type IntangibleUnion = Intangible | StructuredValueUnion;
/**
* A utility class that serves as the umbrella for a number of 'intangible' things such as
* quantities, structured values, etc.
*/
export interface Intangible {
/**
* Polymorphic Discriminator
*/
_type: "Intangible";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* The name of the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The URL to get more information about the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly url?: string;
/**
* Additional information about the entity such as hints that you can use to determine the
* entity's type. To determine the entity's type, use the entityScenario and entityTypeHint
* fields.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityPresentationInfo?: EntitiesEntityPresentationInfo;
}
/**
* Contains the possible cases for StructuredValue.
*/
export type StructuredValueUnion = StructuredValue | PostalAddress;
/**
* An interface representing StructuredValue.
*/
export interface StructuredValue {
/**
* Polymorphic Discriminator
*/
_type: "StructuredValue";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* The name of the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The URL to get more information about the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly url?: string;
/**
* Additional information about the entity such as hints that you can use to determine the
* entity's type. To determine the entity's type, use the entityScenario and entityTypeHint
* fields.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityPresentationInfo?: EntitiesEntityPresentationInfo;
}
/**
* Defines a postal address.
*/
export interface PostalAddress {
/**
* Polymorphic Discriminator
*/
_type: "PostalAddress";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* The name of the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The URL to get more information about the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly url?: string;
/**
* Additional information about the entity such as hints that you can use to determine the
* entity's type. To determine the entity's type, use the entityScenario and entityTypeHint
* fields.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityPresentationInfo?: EntitiesEntityPresentationInfo;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly streetAddress?: string;
/**
* The city where the street address is located. For example, Seattle.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly addressLocality?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly addressSubregion?: string;
/**
* The state or province code where the street address is located. This could be the two-letter
* code. For example, WA, or the full name , Washington.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly addressRegion?: string;
/**
* The zip code or postal code where the street address is located. For example, 98052.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly postalCode?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly postOfficeBoxNumber?: string;
/**
* The country/region where the street address is located. This could be the two-letter ISO code.
* For example, US, or the full name, United States.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly addressCountry?: string;
/**
* The two letter ISO code of this country. For example, US.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly countryIso?: string;
/**
* The neighborhood where the street address is located. For example, Westlake.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly neighborhood?: string;
/**
* Region Abbreviation. For example, WA.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly addressRegionAbbreviation?: string;
/**
* The complete address. For example, 2100 Westlake Ave N, Bellevue, WA 98052.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly text?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly houseNumber?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly streetName?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly formattingRuleId?: string;
}
/**
* Defines information about a local entity, such as a restaurant or hotel.
*/
export interface Place {
/**
* Polymorphic Discriminator
*/
_type: "Place";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* The name of the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The URL to get more information about the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly url?: string;
/**
* Additional information about the entity such as hints that you can use to determine the
* entity's type. To determine the entity's type, use the entityScenario and entityTypeHint
* fields.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityPresentationInfo?: EntitiesEntityPresentationInfo;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly geo?: GeoCoordinates;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly routablePoint?: GeoCoordinates;
/**
* The postal address of where the entity is located
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly address?: PostalAddress;
/**
* The entity's telephone number
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly telephone?: string;
}
/**
* Contains the possible cases for CreativeWork.
*/
export type CreativeWorkUnion = CreativeWork | ActionUnion;
/**
* The most generic kind of creative work, including books, movies, photographs, software programs,
* etc.
*/
export interface CreativeWork {
/**
* Polymorphic Discriminator
*/
_type: "CreativeWork";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* The name of the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The URL to get more information about the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly url?: string;
/**
* Additional information about the entity such as hints that you can use to determine the
* entity's type. To determine the entity's type, use the entityScenario and entityTypeHint
* fields.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityPresentationInfo?: EntitiesEntityPresentationInfo;
/**
* The URL to a thumbnail of the item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly thumbnailUrl?: string;
/**
* For internal use only.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly about?: ThingUnion[];
/**
* For internal use only.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly mentions?: ThingUnion[];
/**
* The source of the creative work.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provider?: ThingUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creator?: ThingUnion;
/**
* Text content of this creative work
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly text?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly discussionUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly commentCount?: number;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly mainEntity?: ThingUnion;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly headLine?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyrightHolder?: ThingUnion;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyrightYear?: number;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly disclaimer?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isAccessibleForFree?: boolean;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly genre?: string[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isFamilyFriendly?: boolean;
}
/**
* Contains the possible cases for Action.
*/
export type ActionUnion = Action | SearchAction;
/**
* Defines an action.
*/
export interface Action {
/**
* Polymorphic Discriminator
*/
_type: "Action";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* The name of the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The URL to get more information about the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly url?: string;
/**
* Additional information about the entity such as hints that you can use to determine the
* entity's type. To determine the entity's type, use the entityScenario and entityTypeHint
* fields.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityPresentationInfo?: EntitiesEntityPresentationInfo;
/**
* The URL to a thumbnail of the item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly thumbnailUrl?: string;
/**
* For internal use only.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly about?: ThingUnion[];
/**
* For internal use only.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly mentions?: ThingUnion[];
/**
* The source of the creative work.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provider?: ThingUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creator?: ThingUnion;
/**
* Text content of this creative work
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly text?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly discussionUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly commentCount?: number;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly mainEntity?: ThingUnion;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly headLine?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyrightHolder?: ThingUnion;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyrightYear?: number;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly disclaimer?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isAccessibleForFree?: boolean;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly genre?: string[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isFamilyFriendly?: boolean;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly location?: Place[];
/**
* The result produced in the action.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly result?: ThingUnion[];
/**
* A display name for the action.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly displayName?: string;
/**
* A Boolean representing whether this result is the top action.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isTopAction?: boolean;
/**
* Use this URL to get additional data to determine how to take the appropriate action. For
* example, the serviceUrl might return JSON along with an image URL.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly serviceUrl?: string;
}
/**
* Defines the error that occurred.
*/
export interface ErrorModel {
/**
* Polymorphic Discriminator
*/
_type: "Error";
/**
* The error code that identifies the category of error. Possible values include: 'None',
* 'ServerError', 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization',
* 'InsufficientAuthorization'. Default value: 'None'.
*/
code: ErrorCode;
/**
* The error code that further helps to identify the error. Possible values include:
* 'UnexpectedError', 'ResourceError', 'NotImplemented', 'ParameterMissing',
* 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing',
* 'AuthorizationRedundancy', 'AuthorizationDisabled', 'AuthorizationExpired'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly subCode?: ErrorSubCode;
/**
* A description of the error.
*/
message: string;
/**
* A description that provides additional information about the error.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly moreDetails?: string;
/**
* The parameter in the request that caused the error.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly parameter?: string;
/**
* The parameter's value in the request that was not valid.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly value?: string;
}
/**
* The top-level response that represents a failed request.
*/
export interface ErrorResponse {
/**
* Polymorphic Discriminator
*/
_type: "ErrorResponse";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* A list of errors that describe the reasons why the request failed.
*/
errors: ErrorModel[];
}
/**
* An interface representing SearchAction.
*/
export interface SearchAction {
/**
* Polymorphic Discriminator
*/
_type: "SearchAction";
/**
* A String identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The URL that returns this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly webSearchUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly potentialAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly immediateAction?: ActionUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly preferredClickthroughUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly adaptiveCard?: string;
/**
* The name of the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The URL to get more information about the thing represented by this object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly url?: string;
/**
* Additional information about the entity such as hints that you can use to determine the
* entity's type. To determine the entity's type, use the entityScenario and entityTypeHint
* fields.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly entityPresentationInfo?: EntitiesEntityPresentationInfo;
/**
* The URL to a thumbnail of the item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly thumbnailUrl?: string;
/**
* For internal use only.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly about?: ThingUnion[];
/**
* For internal use only.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly mentions?: ThingUnion[];
/**
* The source of the creative work.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provider?: ThingUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creator?: ThingUnion;
/**
* Text content of this creative work
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly text?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly discussionUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly commentCount?: number;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly mainEntity?: ThingUnion;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly headLine?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyrightHolder?: ThingUnion;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyrightYear?: number;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly disclaimer?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isAccessibleForFree?: boolean;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly genre?: string[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isFamilyFriendly?: boolean;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly location?: Place[];
/**
* The result produced in the action.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly result?: ThingUnion[];
/**
* A display name for the action.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly displayName?: string;
/**
* A Boolean representing whether this result is the top action.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isTopAction?: boolean;
/**
* Use this URL to get additional data to determine how to take the appropriate action. For
* example, the serviceUrl might return JSON along with an image URL.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly serviceUrl?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly displayText?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly query?: string;
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly richContent?: AnswerUnion[];
/**
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly formattingRuleId?: string;
}
/**
* An interface representing LocalSearchClientOptions.
*/
export interface LocalSearchClientOptions extends ServiceClientOptions {
baseUri?: string;
}
/**
* Optional Parameters.
*/
export interface LocalSearchOptionalParams extends msRest.RequestOptionsBase {
/**
* A comma-delimited list of one or more languages to use for user interface strings. The list is
* in decreasing order of preference. For additional information, including expected format, see
* [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang
* query parameter are mutually exclusive; do not specify both. If you set this header, you must
* also specify the cc query parameter. Bing will use the first supported language it finds from
* the list, and combine that language with the cc parameter value to determine the market to
* return results for. If the list does not include a supported language, Bing will find the
* closest language and market that supports the request, and may use an aggregated or default
* market for the results instead of a specified one. You should use this header and the cc query
* parameter only if you specify multiple languages; otherwise, you should use the mkt and
* setLang query parameters. A user interface string is a string that's used as a label in a user
* interface. There are very few user interface strings in the JSON response objects. Any links
* in the response objects to Bing.com properties will apply the specified language.
*/
acceptLanguage?: string;
/**
* By default, Bing returns cached content, if available. To prevent Bing from returning cached
* content, set the Pragma header to no-cache (for example, Pragma: no-cache).
*/
pragma?: string;
/**
* The user agent originating the request. Bing uses the user agent to provide mobile users with
* an optimized experience. Although optional, you are strongly encouraged to always specify this
* header. The user-agent should be the same string that any commonly used browser would send.
* For information about user agents, see [RFC
* 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
*/
userAgent?: string;
/**
* Bing uses this header to provide users with consistent behavior across Bing API calls. Bing
* often flights new features and improvements, and it uses the client ID as a key for assigning
* traffic on different flights. If you do not use the same client ID for a user across multiple
* requests, then Bing may assign the user to multiple conflicting flights. Being assigned to
* multiple conflicting flights can lead to an inconsistent user experience. For example, if the
* second request has a different flight assignment than the first, the experience may be
* unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search
* history, providing a richer experience for the user. Bing also uses this header to help
* improve result rankings by analyzing the activity generated by a client ID. The relevance
* improvements help with better quality of results delivered by Bing APIs and in turn enables
* higher click-through rates for the API consumer. IMPORTANT: Although optional, you should
* consider this header required. Persisting the client ID across multiple requests for the same
* end user and device combination enables 1) the API consumer to receive a consistent user
* experience, and 2) higher click-through rates via better quality of results from the Bing
* APIs. Each user that uses your application on the device must have a unique, Bing generated
* client ID. If you do not include this header in the request, Bing generates an ID and returns
* it in the X-MSEdge-ClientID response header. The only time that you should NOT include this
* header in a request is the first time the user uses your app on that device. Use the client ID
* for each Bing API request that your app makes for this user on the device. Persist the client
* ID. To persist the ID in a browser app, use a persistent HTTP cookie to ensure the ID is used
* across all sessions. Do not use a session cookie. For other apps such as mobile apps, use the
* device's persistent storage to persist the ID. The next time the user uses your app on that
* device, get the client ID that you persisted. Bing responses may or may not include this
* header. If the response includes this header, capture the client ID and use it for all
* subsequent Bing requests for the user on that device. If you include the X-MSEdge-ClientID,
* you must not include cookies in the request.
*/
clientId?: string;
/**
* The IPv4 or IPv6 address of the client device. The IP address is used to discover the user's
* location. Bing uses the location information to determine safe search behavior. Although
* optional, you are encouraged to always specify this header and the X-Search-Location header.
* Do not obfuscate the address (for example, by changing the last octet to 0). Obfuscating the
* address results in the location not being anywhere near the device's actual location, which
* may result in Bing serving erroneous results.
*/
clientIp?: string;
/**
* A semicolon-delimited list of key/value pairs that describe the client's geographical
* location. Bing uses the location information to determine safe search behavior and to return
* relevant local content. Specify the key/value pair as <key>:<value>. The following are the
* keys that you use to specify the user's location. lat (required): The latitude of the client's
* location, in degrees. The latitude must be greater than or equal to -90.0 and less than or
* equal to +90.0. Negative values indicate southern latitudes and positive values indicate
* northern latitudes. long (required): The longitude of the client's location, in degrees. The
* longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative
* values indicate western longitudes and positive values indicate eastern longitudes. re
* (required): The radius, in meters, which specifies the horizontal accuracy of the coordinates.
* Pass the value returned by the device's location service. Typical values might be 22m for
* GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts
* (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp
* is the number of seconds since January 1, 1970.) head (optional): The client's relative
* heading or direction of travel. Specify the direction of travel as degrees from 0 through 360,
* counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp
* (optional): The horizontal velocity (speed), in meters per second, that the client device is
* traveling. alt (optional): The altitude of the client device, in meters. are (optional): The
* radius, in meters, that specifies the vertical accuracy of the coordinates. Specify this key
* only if you specify the alt key. Although many of the keys are optional, the more information
* that you provide, the more accurate the location results are. Although optional, you are
* encouraged to always specify the user's geographical location. Providing the location is
* especially important if the client's IP address does not accurately reflect the user's
* physical location (for example, if the client uses VPN). For optimal results, you should
* include this header and the X-MSEdge-ClientIP header, but at a minimum, you should include
* this header.
*/
location?: string;
/**
* A 2-character country code of the country where the results come from. This API supports only
* the United States market. If you specify this query parameter, it must be set to us. If you
* set this parameter, you must also specify the Accept-Language header. Bing uses the first
* supported language it finds from the languages list, and combine that language with the
* country code that you specify to determine the market to return results for. If the languages
* list does not include a supported language, Bing finds the closest language and market that
* supports the request, or it may use an aggregated or default market for the results instead of
* a specified one. You should use this query parameter and the Accept-Language query parameter
* only if you specify multiple languages; otherwise, you should use the mkt and setLang query
* parameters. This parameter and the mkt query parameter are mutually exclusive—do not specify
* both.
*/
countryCode?: string;
/**
* The market where the results come from. You are strongly encouraged to always specify the
* market, if known. Specifying the market helps Bing route the request and return an appropriate
* and optimal response. This parameter and the cc query parameter are mutually exclusive—do not
* specify both. Default value: 'en-us'.
*/
market?: string;
/**
* comma-delimited list of business categories to search for. Supported categories can be
* high-level such as EatDrink, Shop, SeeDo.
*/
localCategories?: string;
/**
* Preferred location to search around, expressed as Latitude, longitude and radius in meters.
* For example 47.61503,-122.1719,5000. Note that circular view should only be used to indicate a
* search around a point on the map, not as an approximation for a view port of a map rectangle.
*/
localCircularView?: string;
/**
* Preferred bounding box for results, specified in NW_latitude, NW_Longitude, SE_Latitude,
* SE_Longitude format. For example 47.64,-122.13,47.63,-122.12. These values are lat, long pairs
* for the Northwest corner and the Southeast corner of a rectangle.
*/
localMapView?: string;
/**
* Preferred number of results to return. If not specified, then Bing returns 1-20 of the most
* relevant results.
*/
count?: string;
/**
* First result to return. zero-based. default is 0.
*/
first?: string;
/**
* The media type to use for the response. The following are the possible case-insensitive
* values: JSON, JSONLD. The default is JSON. If you specify JSONLD, the response body includes
* JSON-LD objects that contain the search results.
*/
responseFormat?: ResponseFormat[];
/**
* A filter used to filter adult content. Off: Return webpages with adult text, images, or
* videos. Moderate: Return webpages with adult text, but not adult images or videos. Strict: Do
* not return webpages with adult text, images, or videos. The default is Moderate. If the
* request comes from a market that Bing's adult policy requires that safeSearch is set to
* Strict, Bing ignores the safeSearch value and uses Strict. If you use the site: query
* operator, there is the chance that the response may contain adult content regardless of what
* the safeSearch query parameter is set to. Use site: only if you are aware of the content on
* the site and your scenario supports the possibility of adult content. Possible values include:
* 'Off', 'Moderate', 'Strict'
*/
safeSearch?: SafeSearch;
/**
* The language to use for user interface strings. Specify the language using the ISO 639-1
* 2-letter language code. For example, the language code for English is EN. The default is EN
* (English). Although optional, you should always specify the language. Typically, you set
* setLang to the same language specified by mkt unless the user wants the user interface strings
* displayed in a different language. This parameter and the Accept-Language header are mutually
* exclusive; do not specify both. A user interface string is a string that's used as a label in
* a user interface. There are few user interface strings in the JSON response objects. Also, any
* links to Bing.com properties in the response objects apply the specified language.
*/
setLang?: string;
}
/**
* Defines values for EntityScenario.
* Possible values include: 'DominantEntity', 'DisambiguationItem', 'ListItem'
* @readonly
* @enum {string}
*/
export type EntityScenario = 'DominantEntity' | 'DisambiguationItem' | 'ListItem';
/**
* Defines values for EntityType.
* Possible values include: 'Place', 'LocalBusiness', 'Restaurant', 'Hotel'
* @readonly
* @enum {string}
*/
export type EntityType = 'Place' | 'LocalBusiness' | 'Restaurant' | 'Hotel';
/**
* Defines values for ErrorCode.
* Possible values include: 'None', 'ServerError', 'InvalidRequest', 'RateLimitExceeded',
* 'InvalidAuthorization', 'InsufficientAuthorization'
* @readonly
* @enum {string}
*/
export type ErrorCode = 'None' | 'ServerError' | 'InvalidRequest' | 'RateLimitExceeded' | 'InvalidAuthorization' | 'InsufficientAuthorization';
/**
* Defines values for ErrorSubCode.
* Possible values include: 'UnexpectedError', 'ResourceError', 'NotImplemented',
* 'ParameterMissing', 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked',
* 'AuthorizationMissing', 'AuthorizationRedundancy', 'AuthorizationDisabled',
* 'AuthorizationExpired'
* @readonly
* @enum {string}
*/
export type ErrorSubCode = 'UnexpectedError' | 'ResourceError' | 'NotImplemented' | 'ParameterMissing' | 'ParameterInvalidValue' | 'HttpNotAllowed' | 'Blocked' | 'AuthorizationMissing' | 'AuthorizationRedundancy' | 'AuthorizationDisabled' | 'AuthorizationExpired';
/**
* Defines values for ResponseFormat.
* Possible values include: 'Json', 'JsonLd'
* @readonly
* @enum {string}
*/
export type ResponseFormat = 'Json' | 'JsonLd';
/**
* Defines values for SafeSearch.
* Possible values include: 'Off', 'Moderate', 'Strict'
* @readonly
* @enum {string}
*/
export type SafeSearch = 'Off' | 'Moderate' | 'Strict';
/**
* Contains response data for the search operation.
*/
export type LocalSearchResponse = SearchResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SearchResponse;
};
}; | the_stack |
module android.widget {
import DataSetObserver = android.database.DataSetObserver;
import SystemClock = android.os.SystemClock;
import View = android.view.View;
import ViewGroup = android.view.ViewGroup;
import ArrayList = java.util.ArrayList;
import Collections = java.util.Collections;
import Integer = java.lang.Integer;
import Comparable = java.lang.Comparable;
import Adapter = android.widget.Adapter;
import AdapterView = android.widget.AdapterView;
import BaseAdapter = android.widget.BaseAdapter;
import ExpandableListAdapter = android.widget.ExpandableListAdapter;
import ExpandableListPosition = android.widget.ExpandableListPosition;
import HeterogeneousExpandableList = android.widget.HeterogeneousExpandableList;
import ListAdapter = android.widget.ListAdapter;
import ListView = android.widget.ListView;
/**
* A {@link BaseAdapter} that provides data/Views in an expandable list (offers
* features such as collapsing/expanding groups containing children). By
* itself, this adapter has no data and is a connector to a
* {@link ExpandableListAdapter} which provides the data.
* <p>
* Internally, this connector translates the flat list position that the
* ListAdapter expects to/from group and child positions that the ExpandableListAdapter
* expects.
*/
export class ExpandableListConnector extends BaseAdapter /*implements Filterable*/ {
/**
* The ExpandableListAdapter to fetch the data/Views for this expandable list
*/
private mExpandableListAdapter:ExpandableListAdapter;
/**
* List of metadata for the currently expanded groups. The metadata consists
* of data essential for efficiently translating between flat list positions
* and group/child positions. See {@link GroupMetadata}.
*/
private mExpGroupMetadataList:ArrayList<ExpandableListConnector.GroupMetadata>;
/** The number of children from all currently expanded groups */
private mTotalExpChildrenCount:number = 0;
/** The maximum number of allowable expanded groups. Defaults to 'no limit' */
private mMaxExpGroupCount:number = Integer.MAX_VALUE;
/** Change observer used to have ExpandableListAdapter changes pushed to us */
private mDataSetObserver:DataSetObserver = new ExpandableListConnector.MyDataSetObserver(this);
/**
* Constructs the connector
*/
constructor(expandableListAdapter:ExpandableListAdapter) {
super();
this.mExpGroupMetadataList = new ArrayList<ExpandableListConnector.GroupMetadata>();
this.setExpandableListAdapter(expandableListAdapter);
}
/**
* Point to the {@link ExpandableListAdapter} that will give us data/Views
*
* @param expandableListAdapter the adapter that supplies us with data/Views
*/
setExpandableListAdapter(expandableListAdapter:ExpandableListAdapter):void {
if (this.mExpandableListAdapter != null) {
this.mExpandableListAdapter.unregisterDataSetObserver(this.mDataSetObserver);
}
this.mExpandableListAdapter = expandableListAdapter;
expandableListAdapter.registerDataSetObserver(this.mDataSetObserver);
}
/**
* Translates a flat list position to either a) group pos if the specified
* flat list position corresponds to a group, or b) child pos if it
* corresponds to a child. Performs a binary search on the expanded
* groups list to find the flat list pos if it is an exp group, otherwise
* finds where the flat list pos fits in between the exp groups.
*
* @param flPos the flat list position to be translated
* @return the group position or child position of the specified flat list
* position encompassed in a {@link PositionMetadata} object
* that contains additional useful info for insertion, etc.
*/
getUnflattenedPos(flPos:number):ExpandableListConnector.PositionMetadata {
/* Keep locally since frequent use */
const egml:ArrayList<ExpandableListConnector.GroupMetadata> = this.mExpGroupMetadataList;
const numExpGroups:number = egml.size();
/* Binary search variables */
let leftExpGroupIndex:number = 0;
let rightExpGroupIndex:number = numExpGroups - 1;
let midExpGroupIndex:number = 0;
let midExpGm:ExpandableListConnector.GroupMetadata;
if (numExpGroups == 0) {
/*
* There aren't any expanded groups (hence no visible children
* either), so flPos must be a group and its group pos will be the
* same as its flPos
*/
return ExpandableListConnector.PositionMetadata.obtain(flPos, ExpandableListPosition.GROUP, flPos, -1, null, 0);
}
/*
* Binary search over the expanded groups to find either the exact
* expanded group (if we're looking for a group) or the group that
* contains the child we're looking for. If we are looking for a
* collapsed group, we will not have a direct match here, but we will
* find the expanded group just before the group we're searching for (so
* then we can calculate the group position of the group we're searching
* for). If there isn't an expanded group prior to the group being
* searched for, then the group being searched for's group position is
* the same as the flat list position (since there are no children before
* it, and all groups before it are collapsed).
*/
while (leftExpGroupIndex <= rightExpGroupIndex) {
midExpGroupIndex = Math.floor((rightExpGroupIndex - leftExpGroupIndex) / 2 + leftExpGroupIndex);
midExpGm = egml.get(midExpGroupIndex);
if (flPos > midExpGm.lastChildFlPos) {
/*
* The flat list position is after the current middle group's
* last child's flat list position, so search right
*/
leftExpGroupIndex = midExpGroupIndex + 1;
} else if (flPos < midExpGm.flPos) {
/*
* The flat list position is before the current middle group's
* flat list position, so search left
*/
rightExpGroupIndex = midExpGroupIndex - 1;
} else if (flPos == midExpGm.flPos) {
/*
* The flat list position is this middle group's flat list
* position, so we've found an exact hit
*/
return ExpandableListConnector.PositionMetadata.obtain(flPos, ExpandableListPosition.GROUP, midExpGm.gPos, -1, midExpGm, midExpGroupIndex);
} else if (flPos <= midExpGm.lastChildFlPos) /* && flPos > midGm.flPos as deduced from previous
* conditions */
{
/* The flat list position is a child of the middle group */
/*
* Subtract the first child's flat list position from the
* specified flat list pos to get the child's position within
* the group
*/
const childPos:number = flPos - (midExpGm.flPos + 1);
return ExpandableListConnector.PositionMetadata.obtain(flPos, ExpandableListPosition.CHILD, midExpGm.gPos, childPos, midExpGm, midExpGroupIndex);
}
}
/*
* If we've reached here, it means the flat list position must be a
* group that is not expanded, since otherwise we would have hit it
* in the above search.
*/
/**
* If we are to expand this group later, where would it go in the
* mExpGroupMetadataList ?
*/
let insertPosition:number = 0;
/** What is its group position in the list of all groups? */
let groupPos:number = 0;
/*
* To figure out exact insertion and prior group positions, we need to
* determine how we broke out of the binary search. We backtrack
* to see this.
*/
if (leftExpGroupIndex > midExpGroupIndex) {
/*
* This would occur in the first conditional, so the flat list
* insertion position is after the left group. Also, the
* leftGroupPos is one more than it should be (since that broke out
* of our binary search), so we decrement it.
*/
const leftExpGm:ExpandableListConnector.GroupMetadata = egml.get(leftExpGroupIndex - 1);
insertPosition = leftExpGroupIndex;
/*
* Sums the number of groups between the prior exp group and this
* one, and then adds it to the prior group's group pos
*/
groupPos = (flPos - leftExpGm.lastChildFlPos) + leftExpGm.gPos;
} else if (rightExpGroupIndex < midExpGroupIndex) {
/*
* This would occur in the second conditional, so the flat list
* insertion position is before the right group. Also, the
* rightGroupPos is one less than it should be, so increment it.
*/
const rightExpGm:ExpandableListConnector.GroupMetadata = egml.get(++rightExpGroupIndex);
insertPosition = rightExpGroupIndex;
/*
* Subtracts this group's flat list pos from the group after's flat
* list position to find out how many groups are in between the two
* groups. Then, subtracts that number from the group after's group
* pos to get this group's pos.
*/
groupPos = rightExpGm.gPos - (rightExpGm.flPos - flPos);
} else {
// TODO: clean exit
throw Error(`new RuntimeException("Unknown state")`);
}
return ExpandableListConnector.PositionMetadata.obtain(flPos, ExpandableListPosition.GROUP, groupPos, -1, null, insertPosition);
}
/**
* Translates either a group pos or a child pos (+ group it belongs to) to a
* flat list position. If searching for a child and its group is not expanded, this will
* return null since the child isn't being shown in the ListView, and hence it has no
* position.
*
* @param pos a {@link ExpandableListPosition} representing either a group position
* or child position
* @return the flat list position encompassed in a {@link PositionMetadata}
* object that contains additional useful info for insertion, etc., or null.
*/
getFlattenedPos(pos:ExpandableListPosition):ExpandableListConnector.PositionMetadata {
const egml:ArrayList<ExpandableListConnector.GroupMetadata> = this.mExpGroupMetadataList;
const numExpGroups:number = egml.size();
/* Binary search variables */
let leftExpGroupIndex:number = 0;
let rightExpGroupIndex:number = numExpGroups - 1;
let midExpGroupIndex:number = 0;
let midExpGm:ExpandableListConnector.GroupMetadata;
if (numExpGroups == 0) {
/*
* There aren't any expanded groups, so flPos must be a group and
* its flPos will be the same as its group pos. The
* insert position is 0 (since the list is empty).
*/
return ExpandableListConnector.PositionMetadata.obtain(pos.groupPos, pos.type, pos.groupPos, pos.childPos, null, 0);
}
/*
* Binary search over the expanded groups to find either the exact
* expanded group (if we're looking for a group) or the group that
* contains the child we're looking for.
*/
while (leftExpGroupIndex <= rightExpGroupIndex) {
midExpGroupIndex = Math.floor((rightExpGroupIndex - leftExpGroupIndex) / 2 + leftExpGroupIndex);
midExpGm = egml.get(midExpGroupIndex);
if (pos.groupPos > midExpGm.gPos) {
/*
* It's after the current middle group, so search right
*/
leftExpGroupIndex = midExpGroupIndex + 1;
} else if (pos.groupPos < midExpGm.gPos) {
/*
* It's before the current middle group, so search left
*/
rightExpGroupIndex = midExpGroupIndex - 1;
} else if (pos.groupPos == midExpGm.gPos) {
if (pos.type == ExpandableListPosition.GROUP) {
/* If it's a group, give them this matched group's flPos */
return ExpandableListConnector.PositionMetadata.obtain(midExpGm.flPos, pos.type, pos.groupPos, pos.childPos, midExpGm, midExpGroupIndex);
} else if (pos.type == ExpandableListPosition.CHILD) {
/* If it's a child, calculate the flat list pos */
return ExpandableListConnector.PositionMetadata.obtain(midExpGm.flPos + pos.childPos + 1, pos.type, pos.groupPos, pos.childPos, midExpGm, midExpGroupIndex);
} else {
return null;
}
}
}
/*
* If we've reached here, it means there was no match in the expanded
* groups, so it must be a collapsed group that they're search for
*/
if (pos.type != ExpandableListPosition.GROUP) {
/* If it isn't a group, return null */
return null;
}
/*
* To figure out exact insertion and prior group positions, we need to
* determine how we broke out of the binary search. We backtrack to see
* this.
*/
if (leftExpGroupIndex > midExpGroupIndex) {
/*
* This would occur in the first conditional, so the flat list
* insertion position is after the left group.
*
* The leftGroupPos is one more than it should be (from the binary
* search loop) so we subtract 1 to get the actual left group. Since
* the insertion point is AFTER the left group, we keep this +1
* value as the insertion point
*/
const leftExpGm:ExpandableListConnector.GroupMetadata = egml.get(leftExpGroupIndex - 1);
const flPos:number = leftExpGm.lastChildFlPos + (pos.groupPos - leftExpGm.gPos);
return ExpandableListConnector.PositionMetadata.obtain(flPos, pos.type, pos.groupPos, pos.childPos, null, leftExpGroupIndex);
} else if (rightExpGroupIndex < midExpGroupIndex) {
/*
* This would occur in the second conditional, so the flat list
* insertion position is before the right group. Also, the
* rightGroupPos is one less than it should be (from binary search
* loop), so we increment to it.
*/
const rightExpGm:ExpandableListConnector.GroupMetadata = egml.get(++rightExpGroupIndex);
const flPos:number = rightExpGm.flPos - (rightExpGm.gPos - pos.groupPos);
return ExpandableListConnector.PositionMetadata.obtain(flPos, pos.type, pos.groupPos, pos.childPos, null, rightExpGroupIndex);
} else {
return null;
}
}
areAllItemsEnabled():boolean {
return this.mExpandableListAdapter.areAllItemsEnabled();
}
isEnabled(flatListPos:number):boolean {
const metadata:ExpandableListConnector.PositionMetadata = this.getUnflattenedPos(flatListPos);
const pos:ExpandableListPosition = metadata.position;
let retValue:boolean;
if (pos.type == ExpandableListPosition.CHILD) {
retValue = this.mExpandableListAdapter.isChildSelectable(pos.groupPos, pos.childPos);
} else {
// Groups are always selectable
retValue = true;
}
metadata.recycle();
return retValue;
}
getCount():number {
/*
* Total count for the list view is the number groups plus the
* number of children from currently expanded groups (a value we keep
* cached in this class)
*/
return this.mExpandableListAdapter.getGroupCount() + this.mTotalExpChildrenCount;
}
getItem(flatListPos:number):any {
const posMetadata:ExpandableListConnector.PositionMetadata = this.getUnflattenedPos(flatListPos);
let retValue:any;
if (posMetadata.position.type == ExpandableListPosition.GROUP) {
retValue = this.mExpandableListAdapter.getGroup(posMetadata.position.groupPos);
} else if (posMetadata.position.type == ExpandableListPosition.CHILD) {
retValue = this.mExpandableListAdapter.getChild(posMetadata.position.groupPos, posMetadata.position.childPos);
} else {
// TODO: clean exit
throw Error(`new RuntimeException("Flat list position is of unknown type")`);
}
posMetadata.recycle();
return retValue;
}
getItemId(flatListPos:number):number {
const posMetadata:ExpandableListConnector.PositionMetadata = this.getUnflattenedPos(flatListPos);
const groupId:number = this.mExpandableListAdapter.getGroupId(posMetadata.position.groupPos);
let retValue:number;
if (posMetadata.position.type == ExpandableListPosition.GROUP) {
retValue = this.mExpandableListAdapter.getCombinedGroupId(groupId);
} else if (posMetadata.position.type == ExpandableListPosition.CHILD) {
const childId:number = this.mExpandableListAdapter.getChildId(posMetadata.position.groupPos, posMetadata.position.childPos);
retValue = this.mExpandableListAdapter.getCombinedChildId(groupId, childId);
} else {
// TODO: clean exit
throw Error(`new RuntimeException("Flat list position is of unknown type")`);
}
posMetadata.recycle();
return retValue;
}
getView(flatListPos:number, convertView:View, parent:ViewGroup):View {
const posMetadata:ExpandableListConnector.PositionMetadata = this.getUnflattenedPos(flatListPos);
let retValue:View;
if (posMetadata.position.type == ExpandableListPosition.GROUP) {
retValue = this.mExpandableListAdapter.getGroupView(posMetadata.position.groupPos, posMetadata.isExpanded(), convertView, parent);
} else if (posMetadata.position.type == ExpandableListPosition.CHILD) {
const isLastChild:boolean = posMetadata.groupMetadata.lastChildFlPos == flatListPos;
retValue = this.mExpandableListAdapter.getChildView(posMetadata.position.groupPos, posMetadata.position.childPos, isLastChild, convertView, parent);
} else {
// TODO: clean exit
throw Error(`new RuntimeException("Flat list position is of unknown type")`);
}
posMetadata.recycle();
return retValue;
}
getItemViewType(flatListPos:number):number {
const metadata:ExpandableListConnector.PositionMetadata = this.getUnflattenedPos(flatListPos);
const pos:ExpandableListPosition = metadata.position;
let retValue:number;
if (HeterogeneousExpandableList.isImpl(this.mExpandableListAdapter)) {
let adapter:HeterogeneousExpandableList = <HeterogeneousExpandableList><any>this.mExpandableListAdapter;
if (pos.type == ExpandableListPosition.GROUP) {
retValue = adapter.getGroupType(pos.groupPos);
} else {
const childType:number = adapter.getChildType(pos.groupPos, pos.childPos);
retValue = adapter.getGroupTypeCount() + childType;
}
} else {
if (pos.type == ExpandableListPosition.GROUP) {
retValue = 0;
} else {
retValue = 1;
}
}
metadata.recycle();
return retValue;
}
getViewTypeCount():number {
if (HeterogeneousExpandableList.isImpl(this.mExpandableListAdapter)) {
let adapter:HeterogeneousExpandableList = <HeterogeneousExpandableList><any>this.mExpandableListAdapter;
return adapter.getGroupTypeCount() + adapter.getChildTypeCount();
} else {
return 2;
}
}
hasStableIds():boolean {
return this.mExpandableListAdapter.hasStableIds();
}
/**
* Traverses the expanded group metadata list and fills in the flat list
* positions.
*
* @param forceChildrenCountRefresh Forces refreshing of the children count
* for all expanded groups.
* @param syncGroupPositions Whether to search for the group positions
* based on the group IDs. This should only be needed when calling
* this from an onChanged callback.
*/
private refreshExpGroupMetadataList(forceChildrenCountRefresh:boolean, syncGroupPositions:boolean):void {
const egml:ArrayList<ExpandableListConnector.GroupMetadata> = this.mExpGroupMetadataList;
let egmlSize:number = egml.size();
let curFlPos:number = 0;
/* Update child count as we go through */
this.mTotalExpChildrenCount = 0;
if (syncGroupPositions) {
// We need to check whether any groups have moved positions
let positionsChanged:boolean = false;
for (let i:number = egmlSize - 1; i >= 0; i--) {
let curGm:ExpandableListConnector.GroupMetadata = egml.get(i);
let newGPos:number = this.findGroupPosition(curGm.gId, curGm.gPos);
if (newGPos != curGm.gPos) {
if (newGPos == AdapterView.INVALID_POSITION) {
// Doh, just remove it from the list of expanded groups
egml.remove(i);
egmlSize--;
}
curGm.gPos = newGPos;
if (!positionsChanged)
positionsChanged = true;
}
}
if (positionsChanged) {
// At least one group changed positions, so re-sort
Collections.sort(egml);
}
}
let gChildrenCount:number;
let lastGPos:number = 0;
for (let i:number = 0; i < egmlSize; i++) {
/* Store in local variable since we'll access freq */
let curGm:ExpandableListConnector.GroupMetadata = egml.get(i);
/*
* Get the number of children, try to refrain from calling
* another class's method unless we have to (so do a subtraction)
*/
if ((curGm.lastChildFlPos == ExpandableListConnector.GroupMetadata.REFRESH) || forceChildrenCountRefresh) {
gChildrenCount = this.mExpandableListAdapter.getChildrenCount(curGm.gPos);
} else {
/* Num children for this group is its last child's fl pos minus
* the group's fl pos
*/
gChildrenCount = curGm.lastChildFlPos - curGm.flPos;
}
/* Update */
this.mTotalExpChildrenCount += gChildrenCount;
/*
* This skips the collapsed groups and increments the flat list
* position (for subsequent exp groups) by accounting for the collapsed
* groups
*/
curFlPos += (curGm.gPos - lastGPos);
lastGPos = curGm.gPos;
/* Update the flat list positions, and the current flat list pos */
curGm.flPos = curFlPos;
curFlPos += gChildrenCount;
curGm.lastChildFlPos = curFlPos;
}
}
/**
* Collapse a group in the grouped list view
*
* @param groupPos position of the group to collapse
*/
collapseGroup(groupPos:number):boolean {
let elGroupPos:ExpandableListPosition = ExpandableListPosition.obtain(ExpandableListPosition.GROUP, groupPos, -1, -1);
let pm:ExpandableListConnector.PositionMetadata = this.getFlattenedPos(elGroupPos);
elGroupPos.recycle();
if (pm == null)
return false;
let retValue:boolean = this.collapseGroupWithMeta(pm);
pm.recycle();
return retValue;
}
collapseGroupWithMeta(posMetadata:ExpandableListConnector.PositionMetadata):boolean {
/*
* If it is null, it must be already collapsed. This group metadata
* object should have been set from the search that returned the
* position metadata object.
*/
if (posMetadata.groupMetadata == null)
return false;
// Remove the group from the list of expanded groups
this.mExpGroupMetadataList.remove(posMetadata.groupMetadata);
// Refresh the metadata
this.refreshExpGroupMetadataList(false, false);
// Notify of change
this.notifyDataSetChanged();
// Give the callback
this.mExpandableListAdapter.onGroupCollapsed(posMetadata.groupMetadata.gPos);
return true;
}
/**
* Expand a group in the grouped list view
* @param groupPos the group to be expanded
*/
expandGroup(groupPos:number):boolean {
let elGroupPos:ExpandableListPosition = ExpandableListPosition.obtain(ExpandableListPosition.GROUP, groupPos, -1, -1);
let pm:ExpandableListConnector.PositionMetadata = this.getFlattenedPos(elGroupPos);
elGroupPos.recycle();
let retValue:boolean = this.expandGroupWithMeta(pm);
pm.recycle();
return retValue;
}
expandGroupWithMeta(posMetadata:ExpandableListConnector.PositionMetadata):boolean {
if (posMetadata.position.groupPos < 0) {
// TODO clean exit
throw Error(`new RuntimeException("Need group")`);
}
if (this.mMaxExpGroupCount == 0)
return false;
// Check to see if it's already expanded
if (posMetadata.groupMetadata != null)
return false;
/* Restrict number of expanded groups to mMaxExpGroupCount */
if (this.mExpGroupMetadataList.size() >= this.mMaxExpGroupCount) {
/* Collapse a group */
// TODO: Collapse something not on the screen instead of the first one?
// TODO: Could write overloaded function to take GroupMetadata to collapse
let collapsedGm:ExpandableListConnector.GroupMetadata = this.mExpGroupMetadataList.get(0);
let collapsedIndex:number = this.mExpGroupMetadataList.indexOf(collapsedGm);
this.collapseGroup(collapsedGm.gPos);
/* Decrement index if it is after the group we removed */
if (posMetadata.groupInsertIndex > collapsedIndex) {
posMetadata.groupInsertIndex--;
}
}
let expandedGm:ExpandableListConnector.GroupMetadata = ExpandableListConnector.GroupMetadata.obtain(ExpandableListConnector.GroupMetadata.REFRESH, ExpandableListConnector.GroupMetadata.REFRESH, posMetadata.position.groupPos, this.mExpandableListAdapter.getGroupId(posMetadata.position.groupPos));
this.mExpGroupMetadataList.add(posMetadata.groupInsertIndex, expandedGm);
// Refresh the metadata
this.refreshExpGroupMetadataList(false, false);
// Notify of change
this.notifyDataSetChanged();
// Give the callback
this.mExpandableListAdapter.onGroupExpanded(expandedGm.gPos);
return true;
}
/**
* Whether the given group is currently expanded.
* @param groupPosition The group to check.
* @return Whether the group is currently expanded.
*/
isGroupExpanded(groupPosition:number):boolean {
let groupMetadata:ExpandableListConnector.GroupMetadata;
for (let i:number = this.mExpGroupMetadataList.size() - 1; i >= 0; i--) {
groupMetadata = this.mExpGroupMetadataList.get(i);
if (groupMetadata.gPos == groupPosition) {
return true;
}
}
return false;
}
/**
* Set the maximum number of groups that can be expanded at any given time
*/
setMaxExpGroupCount(maxExpGroupCount:number):void {
this.mMaxExpGroupCount = maxExpGroupCount;
}
getAdapter():ExpandableListAdapter {
return this.mExpandableListAdapter;
}
//getFilter():Filter {
// let adapter:ExpandableListAdapter = this.getAdapter();
// if (adapter instanceof Filterable) {
// return (<Filterable> adapter).getFilter();
// } else {
// return null;
// }
//}
getExpandedGroupMetadataList():ArrayList<ExpandableListConnector.GroupMetadata> {
return this.mExpGroupMetadataList;
}
setExpandedGroupMetadataList(expandedGroupMetadataList:ArrayList<ExpandableListConnector.GroupMetadata>):void {
if ((expandedGroupMetadataList == null) || (this.mExpandableListAdapter == null)) {
return;
}
// Make sure our current data set is big enough for the previously
// expanded groups, if not, ignore this request
let numGroups:number = this.mExpandableListAdapter.getGroupCount();
for (let i:number = expandedGroupMetadataList.size() - 1; i >= 0; i--) {
if (expandedGroupMetadataList.get(i).gPos >= numGroups) {
// Doh, for some reason the client doesn't have some of the groups
return;
}
}
this.mExpGroupMetadataList = expandedGroupMetadataList;
this.refreshExpGroupMetadataList(true, false);
}
isEmpty():boolean {
let adapter:ExpandableListAdapter = this.getAdapter();
return adapter != null ? adapter.isEmpty() : true;
}
/**
* Searches the expandable list adapter for a group position matching the
* given group ID. The search starts at the given seed position and then
* alternates between moving up and moving down until 1) we find the right
* position, or 2) we run out of time, or 3) we have looked at every
* position
*
* @return Position of the row that matches the given row ID, or
* {@link AdapterView#INVALID_POSITION} if it can't be found
* @see AdapterView#findSyncPosition()
*/
findGroupPosition(groupIdToMatch:number, seedGroupPosition:number):number {
let count:number = this.mExpandableListAdapter.getGroupCount();
if (count == 0) {
return AdapterView.INVALID_POSITION;
}
// If there isn't a selection don't hunt for it
if (groupIdToMatch == AdapterView.INVALID_ROW_ID) {
return AdapterView.INVALID_POSITION;
}
// Pin seed to reasonable values
seedGroupPosition = Math.max(0, seedGroupPosition);
seedGroupPosition = Math.min(count - 1, seedGroupPosition);
let endTime:number = SystemClock.uptimeMillis() + AdapterView.SYNC_MAX_DURATION_MILLIS;
let rowId:number;
// first position scanned so far
let first:number = seedGroupPosition;
// last position scanned so far
let last:number = seedGroupPosition;
// True if we should move down on the next iteration
let next:boolean = false;
// True when we have looked at the first item in the data
let hitFirst:boolean;
// True when we have looked at the last item in the data
let hitLast:boolean;
// Get the item ID locally (instead of getItemIdAtPosition), so
// we need the adapter
let adapter:ExpandableListAdapter = this.getAdapter();
if (adapter == null) {
return AdapterView.INVALID_POSITION;
}
while (SystemClock.uptimeMillis() <= endTime) {
rowId = adapter.getGroupId(seedGroupPosition);
if (rowId == groupIdToMatch) {
// Found it!
return seedGroupPosition;
}
hitLast = last == count - 1;
hitFirst = first == 0;
if (hitLast && hitFirst) {
// Looked at everything
break;
}
if (hitFirst || (next && !hitLast)) {
// Either we hit the top, or we are trying to move down
last++;
seedGroupPosition = last;
// Try going up next time
next = false;
} else if (hitLast || (!next && !hitFirst)) {
// Either we hit the bottom, or we are trying to move up
first--;
seedGroupPosition = first;
// Try going down next time
next = true;
}
}
return AdapterView.INVALID_POSITION;
}
}
export module ExpandableListConnector{
export class MyDataSetObserver extends DataSetObserver {
_ExpandableListConnector_this:ExpandableListConnector;
constructor(arg:ExpandableListConnector){
super();
this._ExpandableListConnector_this = arg;
}
onChanged():void {
this._ExpandableListConnector_this.refreshExpGroupMetadataList(true, true);
this._ExpandableListConnector_this.notifyDataSetChanged();
}
onInvalidated():void {
this._ExpandableListConnector_this.refreshExpGroupMetadataList(true, true);
this._ExpandableListConnector_this.notifyDataSetInvalidated();
}
}
/**
* Metadata about an expanded group to help convert from a flat list
* position to either a) group position for groups, or b) child position for
* children
*/
export class GroupMetadata implements Comparable<GroupMetadata> {
static REFRESH:number = -1;
/** This group's flat list position */
flPos:number = 0;
/* firstChildFlPos isn't needed since it's (flPos + 1) */
/**
* This group's last child's flat list position, so basically
* the range of this group in the flat list
*/
lastChildFlPos:number = 0;
/**
* This group's group position
*/
gPos:number = 0;
/**
* This group's id
*/
gId:number = 0;
constructor( ) {
}
static obtain(flPos:number, lastChildFlPos:number, gPos:number, gId:number):GroupMetadata {
let gm:GroupMetadata = new GroupMetadata();
gm.flPos = flPos;
gm.lastChildFlPos = lastChildFlPos;
gm.gPos = gPos;
gm.gId = gId;
return gm;
}
compareTo(another:GroupMetadata):number {
if (another == null) {
throw Error(`new IllegalArgumentException()`);
}
return this.gPos - another.gPos;
}
}
/**
* Data type that contains an expandable list position (can refer to either a group
* or child) and some extra information regarding referred item (such as
* where to insert into the flat list, etc.)
*/
export class PositionMetadata {
private static MAX_POOL_SIZE:number = 5;
private static sPool:ArrayList<PositionMetadata> = new ArrayList<PositionMetadata>(PositionMetadata.MAX_POOL_SIZE);
/** Data type to hold the position and its type (child/group) */
position:ExpandableListPosition;
/**
* Link back to the expanded GroupMetadata for this group. Useful for
* removing the group from the list of expanded groups inside the
* connector when we collapse the group, and also as a check to see if
* the group was expanded or collapsed (this will be null if the group
* is collapsed since we don't keep that group's metadata)
*/
groupMetadata:ExpandableListConnector.GroupMetadata;
/**
* For groups that are collapsed, we use this as the index (in
* mExpGroupMetadataList) to insert this group when we are expanding
* this group.
*/
groupInsertIndex:number = 0;
private resetState():void {
if (this.position != null) {
this.position.recycle();
this.position = null;
}
this.groupMetadata = null;
this.groupInsertIndex = 0;
}
/**
* Use {@link #obtain(int, int, int, int, GroupMetadata, int)}
*/
constructor() {
}
static obtain(flatListPos:number, type:number, groupPos:number, childPos:number, groupMetadata:ExpandableListConnector.GroupMetadata, groupInsertIndex:number):PositionMetadata {
let pm:PositionMetadata = PositionMetadata.getRecycledOrCreate();
pm.position = ExpandableListPosition.obtain(type, groupPos, childPos, flatListPos);
pm.groupMetadata = groupMetadata;
pm.groupInsertIndex = groupInsertIndex;
return pm;
}
private static getRecycledOrCreate():PositionMetadata {
let pm:PositionMetadata;
{
if (PositionMetadata.sPool.size() > 0) {
pm = PositionMetadata.sPool.remove(0);
} else {
return new PositionMetadata();
}
}
pm.resetState();
return pm;
}
recycle():void {
this.resetState();
{
if (PositionMetadata.sPool.size() < PositionMetadata.MAX_POOL_SIZE) {
PositionMetadata.sPool.add(this);
}
}
}
/**
* Checks whether the group referred to in this object is expanded,
* or not (at the time this object was created)
*
* @return whether the group at groupPos is expanded or not
*/
isExpanded():boolean {
return this.groupMetadata != null;
}
}
}
} | the_stack |
import { expect } from 'chai';
import express from 'express';
import moment from 'moment';
import nock from 'nock';
import { run as runSettlementScript } from '../../cron/monthly/host-settlement';
import { TransactionKind } from '../../server/constants/transaction-kind';
import {
PLATFORM_TIP_TRANSACTION_PROPERTIES,
SETTLEMENT_EXPENSE_PROPERTIES,
} from '../../server/constants/transactions';
import { markExpenseAsUnpaid, payExpense } from '../../server/graphql/common/expenses';
import { createRefundTransaction, executeOrder } from '../../server/lib/payments';
import * as libPayments from '../../server/lib/payments';
import models from '../../server/models';
import {
fakeCollective,
fakeExpense,
fakeHost,
fakeOrder,
fakePayoutMethod,
fakeUser,
} from '../test-helpers/fake-data';
import { nockFixerRates, resetTestDB, snapshotLedger } from '../utils';
const SNAPSHOT_COLUMNS = [
'kind',
'type',
'amount',
'paymentProcessorFeeInHostCurrency',
'CollectiveId',
'FromCollectiveId',
'HostCollectiveId',
'settlementStatus',
'isRefund',
];
const SNAPSHOT_COLUMNS_MULTI_CURRENCIES = [
...SNAPSHOT_COLUMNS.slice(0, 3),
'currency',
'amountInHostCurrency',
'hostCurrency',
...SNAPSHOT_COLUMNS.slice(3),
];
const RATES = {
USD: { EUR: 0.84, JPY: 110.94 },
EUR: { USD: 1.19, JPY: 132.45 },
JPY: { EUR: 0.0075, USD: 0.009 },
};
/**
* Setup all tests with a similar environment, the only variables being the host/collective currencies
*/
const setupTestData = async (
hostCurrency,
collectiveCurrency,
selfContribution = false,
contributionFromCollective = false,
) => {
// TODO: The setup should ideally insert other hosts and transactions to make sure the balance queries are filtering correctly
await resetTestDB();
const hostAdmin = await fakeUser();
const host = await fakeHost({
name: 'OSC',
admin: hostAdmin.collective,
currency: hostCurrency,
plan: 'grow-plan-2021', // Use a plan with 15% host share
});
await hostAdmin.populateRoles();
await host.update({ HostCollectiveId: host.id, isActive: true });
const collective = await fakeCollective({
HostCollectiveId: host.id,
name: 'ESLint',
hostFeePercent: 5,
currency: collectiveCurrency,
});
const contributorUser = await fakeUser(undefined, { name: 'Ben' });
const contributorCollective = await fakeCollective({ name: 'Webpack', HostCollectiveId: host.id });
const ocInc = await fakeHost({ name: 'OC Inc', id: PLATFORM_TIP_TRANSACTION_PROPERTIES.CollectiveId });
await fakePayoutMethod({ type: 'OTHER', CollectiveId: ocInc.id }); // For the settlement expense
await fakeUser({ id: SETTLEMENT_EXPENSE_PROPERTIES.UserId, name: 'Pia' });
let FromCollectiveId;
if (selfContribution) {
FromCollectiveId = collective.id;
} else if (contributionFromCollective) {
FromCollectiveId = contributorCollective.id;
} else {
FromCollectiveId = contributorUser.CollectiveId;
}
const baseOrderData = {
description: `Financial contribution to ${collective.name}`,
totalAmount: 10000,
currency: collectiveCurrency,
FromCollectiveId: FromCollectiveId,
CollectiveId: collective.id,
PaymentMethodId: null,
};
return { collective, host, hostAdmin, ocInc, contributorUser, baseOrderData };
};
/**
* Creates the settlement expenses and pay them
*/
const executeAllSettlement = async remoteUser => {
await runSettlementScript(moment().add(1, 'month').toDate());
const settlementExpense = await models.Expense.findOne();
expect(settlementExpense, 'Settlement expense has not been created').to.exist;
await settlementExpense.update({ status: 'APPROVED' });
await payExpense(<express.Request>{ remoteUser }, { id: settlementExpense.id, forceManual: true });
};
describe('test/stories/ledger', () => {
let collective, host, hostAdmin, ocInc, contributorUser, baseOrderData;
// Mock currency conversion rates, based on real rates from 2021-06-23
before(() => {
nockFixerRates(RATES);
});
after(() => {
nock.cleanAll();
});
/** Check the validity of all transactions created during tests */
afterEach(async () => {
const transactions = await models.Transaction.findAll({ order: [['id', 'DESC']] });
await Promise.all(
transactions.map(transaction => models.Transaction.validate(transaction, { validateOppositeTransaction: true })),
);
});
describe('Level 1: Same currency (USD)', () => {
beforeEach(async () => {
({ collective, host, hostAdmin, ocInc, contributorUser, baseOrderData } = await setupTestData('USD', 'USD'));
});
it('1. Simple contribution without host fees', async () => {
await collective.update({ hostFeePercent: 0 });
const order = await fakeOrder(baseOrderData);
order.paymentMethod = { service: 'opencollective', type: 'manual', paid: true };
await executeOrder(contributorUser, order);
await snapshotLedger(SNAPSHOT_COLUMNS);
expect(await collective.getBalance()).to.eq(10000);
expect(await host.getTotalMoneyManaged()).to.eq(10000);
expect(await host.getBalance()).to.eq(0);
expect(await ocInc.getBalance()).to.eq(0);
});
it('2. Simple contribution with 5% host fees', async () => {
const order = await fakeOrder(baseOrderData);
order.paymentMethod = { service: 'opencollective', type: 'manual', paid: true };
await executeOrder(contributorUser, order);
await snapshotLedger(SNAPSHOT_COLUMNS);
expect(await collective.getBalance()).to.eq(9500); // 1000 - 5% host fee
expect(await host.getTotalMoneyManaged()).to.eq(10000);
expect(await host.getBalance()).to.eq(500); // 5% host fee
expect(await ocInc.getBalance()).to.eq(0);
});
it('3. Simple contribution with 5% host fees and indirect platform tip (unsettled)', async () => {
const order = await fakeOrder({ ...baseOrderData, data: { isFeesOnTop: true, platformFee: 1000 } });
order.paymentMethod = { service: 'opencollective', type: 'manual', paid: true };
await executeOrder(contributorUser, order);
await snapshotLedger(SNAPSHOT_COLUMNS);
expect(await collective.getBalance()).to.eq(8550); // (10000 Total - 1000 platform tip) - 5% host fee (450)
expect(await host.getTotalMoneyManaged()).to.eq(10000); // Tip is still on host's account
expect(await host.getBalance()).to.eq(1450);
expect(await host.getBalanceWithBlockedFunds()).to.eq(1450);
// TODO We should have a "Projected balance" that removes everything owed
expect(await ocInc.getBalance()).to.eq(0);
});
it('4. Simple contribution with 5% host fees and indirect platform tip (settled)', async () => {
// Create initial order
const order = await fakeOrder({ ...baseOrderData, data: { isFeesOnTop: true, platformFee: 1000 } });
order.paymentMethod = { service: 'opencollective', type: 'manual', paid: true };
await executeOrder(contributorUser, order);
// Run host settlement
await executeAllSettlement(hostAdmin);
// Check data
await snapshotLedger(SNAPSHOT_COLUMNS);
expect(await collective.getBalance()).to.eq(8550); // (10000 Total - 1000 platform tip) - 5% host fee (450)
expect(await host.getTotalMoneyManaged()).to.eq(8932); // 10000 - 1000 (platform tip) - 68 (host fee share)
expect(await host.getBalance()).to.eq(382); // 450 (host fee) - 68 (host fee share)
expect(await host.getBalanceWithBlockedFunds()).to.eq(382);
expect(await ocInc.getBalance()).to.eq(1068); // 1000 (platform tip) + 98 (host fee share)
expect(await ocInc.getBalanceWithBlockedFunds()).to.eq(1068);
});
it('5. Refunded contribution with host fees, payment processor fees and indirect platform tip', async () => {
// Create initial order
const order = await fakeOrder({
...baseOrderData,
data: { isFeesOnTop: true, platformFee: 1000, paymentProcessorFeeInHostCurrency: 200 },
});
order.paymentMethod = { service: 'opencollective', type: 'manual', paid: true };
await executeOrder(contributorUser, order);
// Run host settlement
await executeAllSettlement(hostAdmin);
// New checks for payment processor fees
expect(await collective.getBalance()).to.eq(8350); // (10000 Total - 1000 platform tip) - 5% host fee (450) - 200 processor fees
expect(await host.getTotalMoneyManaged()).to.eq(8732); // 10000 - 1000 (tip) - 200 (processor fee) - 68 (host fee share)
// Check host metrics pre-refund
let hostMetrics = await host.getHostMetrics();
expect(hostMetrics).to.deep.equal({
hostFees: 450,
platformFees: 0,
pendingPlatformFees: 0,
platformTips: 1000,
pendingPlatformTips: 0, // Already settled
hostFeeShare: 68,
pendingHostFeeShare: 0,
hostFeeSharePercent: 15,
settledHostFeeShare: 68,
totalMoneyManaged: 8732,
});
// ---- Refund transaction -----
const contributionTransaction = await models.Transaction.findOne({
where: { OrderId: order.id, kind: 'CONTRIBUTION', type: 'CREDIT' },
});
await createRefundTransaction(contributionTransaction, 0, null, null);
// Check data
await snapshotLedger(SNAPSHOT_COLUMNS);
expect(await collective.getBalance()).to.eq(0);
expect(await host.getTotalMoneyManaged()).to.eq(-1268);
expect(await host.getBalance()).to.eq(-1268); // Will be -200 after settlement (platform tip)
expect(await host.getBalanceWithBlockedFunds()).to.eq(-1268);
expect(await ocInc.getBalance()).to.eq(1068);
expect(await ocInc.getBalanceWithBlockedFunds()).to.eq(1068);
// Check host metrics
hostMetrics = await host.getHostMetrics();
expect(hostMetrics).to.deep.equal({
hostFees: 0,
platformFees: 0,
pendingPlatformFees: 0,
platformTips: 0, // There was a 1000 tip, but it was refunded
pendingPlatformTips: -1000,
hostFeeShare: 0, // Refunded. -> 68 - 68 = 0
hostFeeSharePercent: 15,
pendingHostFeeShare: -68, // -> 0 - 68 = -68 (Negative because owed by platform)
settledHostFeeShare: 68, // hostFeeShare - pendingHostFeeShare (weak metric)
totalMoneyManaged: -1268,
});
// Run OC settlement
// TODO: We should run the opposite settlement and check amount
});
it('6. Expense with Payment Processor fees marked as unpaid', async () => {
await collective.update({ hostFeePercent: 0 });
const order = await fakeOrder({ ...baseOrderData, totalAmount: 150000 });
order.paymentMethod = { service: 'opencollective', type: 'manual', paid: true };
await executeOrder(contributorUser, order);
const expense = await fakeExpense({
description: `Invoice #1`,
amount: 100000,
currency: host.currency,
FromCollectiveId: contributorUser.CollectiveId,
CollectiveId: collective.id,
legacyPayoutMethod: 'manual',
status: 'APPROVED',
});
await payExpense({ remoteUser: hostAdmin } as any, {
id: expense.id,
forceManual: true,
paymentProcessorFeeInCollectiveCurrency: 500,
});
await markExpenseAsUnpaid({ remoteUser: hostAdmin } as any, expense.id, false);
await snapshotLedger(SNAPSHOT_COLUMNS);
expect(await collective.getBalance()).to.eq(150000 + 500);
expect(await host.getTotalMoneyManaged()).to.eq(150000);
expect(await host.getBalance()).to.eq(-500);
});
});
describe('Level 2: Host with a different currency (Host=EUR, Collective=EUR)', () => {
beforeEach(async () => {
({ collective, host, hostAdmin, ocInc, contributorUser, baseOrderData } = await setupTestData('EUR', 'EUR'));
});
it('Refunded contribution with host fees, payment processor fees and indirect platform tip', async () => {
// Create initial order
const order = await fakeOrder({
...baseOrderData,
data: { isFeesOnTop: true, platformFee: 1000, paymentProcessorFeeInHostCurrency: 200 },
});
order.paymentMethod = { service: 'opencollective', type: 'manual', paid: true };
await executeOrder(contributorUser, order);
// Run host settlement
await executeAllSettlement(hostAdmin);
// Check data
const hostToPlatformFxRate = RATES[host.currency]['USD'];
expect(await host.getBalance()).to.eq(382);
expect(await host.getBalanceWithBlockedFunds()).to.eq(382);
expect(await ocInc.getBalance()).to.eq(Math.round(1068 * hostToPlatformFxRate));
expect(await ocInc.getBalanceWithBlockedFunds()).to.eq(Math.round(1068 * hostToPlatformFxRate));
expect(await collective.getBalance()).to.eq(8350); // (10000 Total - 1000 platform tip) - 5% host fee (450) - 200 processor fees
expect(await host.getTotalMoneyManaged()).to.eq(8732); // 10000 - 1000 - 200 - 68
// Check host metrics pre-refund
let hostMetrics = await host.getHostMetrics();
expect(hostMetrics).to.deep.equal({
hostFees: 450,
platformFees: 0,
pendingPlatformFees: 0,
platformTips: 1000,
pendingPlatformTips: 0, // Already settled
hostFeeShare: 68,
hostFeeSharePercent: 15,
pendingHostFeeShare: 0,
settledHostFeeShare: 68,
totalMoneyManaged: 8732,
});
// ---- Refund transaction -----
const contributionTransaction = await models.Transaction.findOne({
where: { OrderId: order.id, kind: 'CONTRIBUTION', type: 'CREDIT' },
});
await createRefundTransaction(contributionTransaction, 0, null, null);
// Check data
await snapshotLedger(SNAPSHOT_COLUMNS_MULTI_CURRENCIES);
expect(await collective.getBalance()).to.eq(0);
expect(await host.getTotalMoneyManaged()).to.eq(-1268);
expect(await host.getBalance()).to.eq(-1268); // Will be +200 after settlement (platform tip refund) +68 (host fee share refund)
expect(await host.getBalanceWithBlockedFunds()).to.eq(-1268);
expect(await ocInc.getBalance()).to.eq(Math.round(1068 * hostToPlatformFxRate));
expect(await ocInc.getBalanceWithBlockedFunds()).to.eq(Math.round(1068 * hostToPlatformFxRate));
// Check host metrics
hostMetrics = await host.getHostMetrics();
expect(hostMetrics).to.deep.equal({
hostFees: 0,
platformFees: 0,
pendingPlatformFees: 0,
platformTips: 0, // There was a 1000 tip, but it was refunded
pendingPlatformTips: -1000,
hostFeeShare: 0, // Refunded
hostFeeSharePercent: 15,
pendingHostFeeShare: -68, // -> 0 - 68 = -68 (Negative because owed by platform)
settledHostFeeShare: 68, // hostFeeShare - pendingHostFeeShare (weak metric)
totalMoneyManaged: -1268,
});
// Run OC settlement
// TODO: We should run the opposite settlement and check amount
});
});
describe('Level 3: Host and collective with different currencies (Host=EUR, Collective=JPY) 🤯️', () => {
beforeEach(async () => {
({ collective, host, hostAdmin, ocInc, contributorUser, baseOrderData } = await setupTestData('EUR', 'JPY'));
await host.update({ settings: { ...host.settings, features: { crossCurrencyManualTransactions: true } } });
});
it('Refunded contribution with host fees, payment processor fees and indirect platform tip', async () => {
const hostToPlatformFxRate = RATES[host.currency]['USD'];
const collectiveToHostFxRate = RATES[collective.currency][host.currency];
const hostToCollectiveFxRate = 1 / collectiveToHostFxRate; // This is how `calculateNetAmountInCollectiveCurrency` gets the reverse rate
const platformTipInCollectiveCurrency = 10000000;
const platformTipInHostCurrency = platformTipInCollectiveCurrency * collectiveToHostFxRate;
const processorFeeInHostCurrency = 200;
const processorFeeInCollectiveCurrency = Math.round(processorFeeInHostCurrency * hostToCollectiveFxRate);
const orderAmountInCollectiveCurrency = 100000000;
const orderAmountInHostCurrency = orderAmountInCollectiveCurrency * collectiveToHostFxRate;
const orderNetAmountInHostCurrency = orderAmountInHostCurrency - platformTipInHostCurrency;
const expectedHostFeeInHostCurrency = Math.round(orderNetAmountInHostCurrency * 0.05);
const expectedHostFeeInCollectiveCurrency = Math.round(expectedHostFeeInHostCurrency * hostToCollectiveFxRate);
const expectedHostFeeShareInHostCurrency = Math.round(expectedHostFeeInHostCurrency * 0.15);
const expectedHostProfitInHostCurrency = expectedHostFeeInHostCurrency - expectedHostFeeShareInHostCurrency;
const expectedPlatformProfitInHostCurrency = expectedHostFeeShareInHostCurrency + platformTipInHostCurrency;
const expectedNetAmountInHostCurrency =
orderNetAmountInHostCurrency - processorFeeInHostCurrency - expectedHostFeeShareInHostCurrency;
// Create initial order
const order = await fakeOrder({
...baseOrderData,
totalAmount: orderAmountInCollectiveCurrency, // JPY has a lower value, we need to set a higher amount to trigger the settlement
data: {
isFeesOnTop: true,
platformFee: platformTipInCollectiveCurrency,
paymentProcessorFeeInHostCurrency: processorFeeInHostCurrency,
},
});
order.paymentMethod = { service: 'opencollective', type: 'manual', paid: true };
await executeOrder(contributorUser, order);
// Run host settlement
await executeAllSettlement(hostAdmin);
// Check data
expect(await host.getBalance()).to.eq(expectedHostProfitInHostCurrency);
expect(await host.getBalanceWithBlockedFunds()).to.eq(expectedHostProfitInHostCurrency);
expect(await host.getTotalMoneyManaged()).to.eq(expectedNetAmountInHostCurrency);
expect(await ocInc.getBalance()).to.eq(Math.round(expectedPlatformProfitInHostCurrency * hostToPlatformFxRate));
expect(await ocInc.getBalanceWithBlockedFunds()).to.eq(
Math.round(expectedPlatformProfitInHostCurrency * hostToPlatformFxRate),
);
expect(await collective.getBalance()).to.eq(
orderAmountInCollectiveCurrency -
platformTipInCollectiveCurrency -
expectedHostFeeInCollectiveCurrency -
processorFeeInCollectiveCurrency,
);
// Check host metrics pre-refund
let hostMetrics = await host.getHostMetrics();
expect(hostMetrics).to.deep.equal({
hostFees: expectedHostFeeInHostCurrency,
platformFees: 0,
pendingPlatformFees: 0,
platformTips: Math.round((platformTipInCollectiveCurrency * RATES.JPY.USD) / RATES.EUR.USD),
pendingPlatformTips: 0, // Already settled
hostFeeShare: expectedHostFeeShareInHostCurrency,
hostFeeSharePercent: 15,
pendingHostFeeShare: 0,
settledHostFeeShare: expectedHostFeeShareInHostCurrency,
totalMoneyManaged: expectedNetAmountInHostCurrency,
});
// ---- Refund transaction -----
const contributionTransaction = await models.Transaction.findOne({
where: { OrderId: order.id, kind: 'CONTRIBUTION', type: 'CREDIT' },
});
await createRefundTransaction(contributionTransaction, 0, null, null);
// Check data
await snapshotLedger(SNAPSHOT_COLUMNS_MULTI_CURRENCIES);
expect(await collective.getBalance()).to.eq(0);
expect(await host.getTotalMoneyManaged()).to.eq(
-platformTipInHostCurrency - processorFeeInHostCurrency - expectedHostFeeShareInHostCurrency,
);
expect(await host.getBalance()).to.eq(
-platformTipInHostCurrency - processorFeeInHostCurrency - expectedHostFeeShareInHostCurrency,
);
expect(await host.getBalanceWithBlockedFunds()).to.eq(
-platformTipInHostCurrency - processorFeeInHostCurrency - expectedHostFeeShareInHostCurrency,
);
expect(await ocInc.getBalance()).to.eq(Math.round(expectedPlatformProfitInHostCurrency * hostToPlatformFxRate));
expect(await ocInc.getBalanceWithBlockedFunds()).to.eq(
Math.round(expectedPlatformProfitInHostCurrency * hostToPlatformFxRate),
);
// Check host metrics
hostMetrics = await host.getHostMetrics();
expect(hostMetrics).to.deep.equal({
hostFees: 0,
platformFees: 0,
pendingPlatformFees: 0,
platformTips: 0, // There was a 1000 tip, but it was refunded
pendingPlatformTips: -platformTipInHostCurrency,
hostFeeShare: 0, // Refunded
hostFeeSharePercent: 15,
pendingHostFeeShare: -expectedHostFeeShareInHostCurrency, // Negative because owed by platform
settledHostFeeShare: expectedHostFeeShareInHostCurrency, // hostFeeShare - pendingHostFeeShare (weak metric)
totalMoneyManaged: -platformTipInHostCurrency - processorFeeInHostCurrency - expectedHostFeeShareInHostCurrency,
});
// Run OC settlement
// TODO: We should run the opposite settlement and check amount
});
});
describe('Level 4: Refund added funds️', async () => {
const refundTransaction = async (collective, host, contributorUser, baseOrderData) => {
const order = await fakeOrder(baseOrderData);
order.paymentMethod = { service: 'opencollective', type: 'host', CollectiveId: host.id };
await executeOrder(contributorUser, order);
// ---- Refund transaction -----
const contributionTransaction = await models.Transaction.findOne({
where: { OrderId: order.id, kind: TransactionKind.ADDED_FUNDS, type: 'CREDIT' },
});
const paymentMethod = libPayments.findPaymentMethodProvider(order.PaymentMethod);
await paymentMethod.refundTransaction(contributionTransaction, 0, null, null);
await snapshotLedger(SNAPSHOT_COLUMNS);
expect(await collective.getBalance()).to.eq(0);
};
it('Refund added funds with same collective', async () => {
const { collective, host, contributorUser, baseOrderData } = await setupTestData('USD', 'USD', true);
await refundTransaction(collective, host, contributorUser, baseOrderData);
});
it('Refund added funds with different collectives', async () => {
const { collective, host, contributorUser, baseOrderData } = await setupTestData('USD', 'USD', false, true);
await refundTransaction(collective, host, contributorUser, baseOrderData);
});
});
}); | the_stack |
import { ID, SimpleEventEmitter } from 'acebase-core';
import { NodeLocker, NodeLock } from '../node-lock';
import { Storage } from '../storage';
export class AceBaseIPCPeerExitingError extends Error {
constructor(message: string) { super(`Exiting: ${message}`); }
}
/**
* Base class for Inter Process Communication, enables vertical scaling: using more CPU's on the same machine to share workload.
* These processes will have to communicate with eachother because they are reading and writing to the same database file
*/
export abstract class AceBaseIPCPeer extends SimpleEventEmitter {
protected masterPeerId: string;
protected ipcType: string = 'ipc';
public get isMaster() { return this.masterPeerId === this.id };
protected ourSubscriptions: Array<{ path: string, event: AceBaseEventType, callback: AceBaseSubscribeCallback }> = [];
protected remoteSubscriptions: Array<{ for?: string, path: string, event: AceBaseEventType, callback: AceBaseSubscribeCallback }> = [];
protected peers: Array<{ id: string, lastSeen: number }> = [];
private _nodeLocker: NodeLocker
constructor(protected storage: Storage, protected id: string, protected dbname: string = storage.name) {
super();
this._nodeLocker = new NodeLocker();
// Setup db event listeners
storage.on('subscribe', (subscription: { path: string, event: string, callback: AceBaseSubscribeCallback }) => {
// Subscription was added to db
storage.debug.verbose(`database subscription being added on peer ${this.id}`);
const remoteSubscription = this.remoteSubscriptions.find(sub => sub.callback === subscription.callback);
if (remoteSubscription) {
// Send ack
// return sendMessage({ type: 'subscribe_ack', from: tabId, to: remoteSubscription.for, data: { path: subscription.path, event: subscription.event } });
return;
}
const othersAlreadyNotifying = this.ourSubscriptions.some(sub => sub.event === subscription.event && sub.path === subscription.path);
// Add subscription
this.ourSubscriptions.push(subscription);
if (othersAlreadyNotifying) {
// Same subscription as other previously added. Others already know we want to be notified
return;
}
// Request other tabs to keep us updated of this event
const message:ISubscribeMessage = { type: 'subscribe', from: this.id, data: { path: subscription.path, event: subscription.event } };
this.sendMessage(message);
});
storage.on('unsubscribe', (subscription: { path: string, event?: string, callback?: AceBaseSubscribeCallback }) => {
// Subscription was removed from db
const remoteSubscription = this.remoteSubscriptions.find(sub => sub.callback === subscription.callback);
if (remoteSubscription) {
// Remove
this.remoteSubscriptions.splice(this.remoteSubscriptions.indexOf(remoteSubscription), 1);
// Send ack
// return sendMessage({ type: 'unsubscribe_ack', from: tabId, to: remoteSubscription.for, data: { path: subscription.path, event: subscription.event } });
return;
}
this.ourSubscriptions
.filter(sub => sub.path === subscription.path && (!subscription.event || sub.event === subscription.event) && (!subscription.callback || sub.callback === subscription.callback))
.forEach(sub => {
// Remove from our subscriptions
this.ourSubscriptions.splice(this.ourSubscriptions.indexOf(sub), 1);
// Request other tabs to stop notifying
const message:IUnsubscribeMessage = { type: 'unsubscribe', from: this.id, data: { path: sub.path, event: sub.event } };
this.sendMessage(message);
});
});
}
private _exiting: boolean = false;
/**
* Requests the peer to shut down. Resolves once its locks are cleared and 'exit' event has been emitted.
* Has to be overridden by the IPC implementation to perform custom shutdown tasks
* @param code optional exit code (eg one provided by SIGINT event)
*/
public async exit(code: number = 0) {
if (this._exiting) {
// Already exiting...
return this.once('exit');
}
this._exiting = true;
this.storage.debug.warn(`Received ${this.isMaster ? 'master' : 'worker ' + this.id} process exit request`);
if (this._locks.length > 0) {
this.storage.debug.warn(`Waiting for ${this.isMaster ? 'master' : 'worker'} ${this.id} locks to clear`);
await this.once('locks-cleared');
}
// Send "bye"
this.sayGoodbye(this.id);
this.storage.debug.warn(`${this.isMaster ? 'Master' : 'Worker ' + this.id} will now exit`);
this.emitOnce('exit', code);
}
protected sayGoodbye(forPeerId: string) {
// Send "bye" message on their behalf
const bye: IByeMessage = { type: 'bye', from: forPeerId, data: undefined };
this.sendMessage(bye);
}
protected addPeer(id: string, sendReply: boolean = true, ignoreDuplicate: boolean = false) {
if (this._exiting) { return; }
const peer = this.peers.find(w => w.id === id);
// if (peer) {
// if (!ignoreDuplicate) {
// throw new Error(`We're not supposed to know this peer!`);
// }
// return;
// }
if (!peer) {
this.peers.push({ id, lastSeen: Date.now() });
}
if (sendReply) {
// Send hello back to sender
const helloMessage:IHelloMessage = { type: 'hello', from: this.id, to: id, data: undefined };
this.sendMessage(helloMessage);
// Send our active subscriptions through
this.ourSubscriptions.forEach(sub => {
// Request to keep us updated
const message:ISubscribeMessage = { type: 'subscribe', from: this.id, to: id, data: { path: sub.path, event: sub.event } };
this.sendMessage(message);
});
}
}
protected removePeer(id: string, ignoreUnknown: boolean = false) {
if (this._exiting) { return; }
const peer = this.peers.find(peer => peer.id === id);
if (!peer) {
if (!ignoreUnknown) {
throw new Error(`We are supposed to know this peer!`);
}
return;
}
this.peers.splice(this.peers.indexOf(peer), 1);
// Remove their subscriptions
const subscriptions = this.remoteSubscriptions.filter(sub => sub.for === id);
subscriptions.forEach(sub => {
// Remove & stop their subscription
this.remoteSubscriptions.splice(this.remoteSubscriptions.indexOf(sub), 1);
this.storage.subscriptions.remove(sub.path, sub.event, sub.callback);
});
}
protected addRemoteSubscription(peerId: string, details:ISubscriptionData) {
if (this._exiting) { return; }
// this.storage.debug.log(`remote subscription being added`);
if (this.remoteSubscriptions.some(sub => sub.for === peerId && sub.event === details.event && sub.path === details.path)) {
// We're already serving this event for the other peer. Ignore
return;
}
// Add remote subscription
const subscribeCallback = (err: Error, path: string, val: any, previous: any, context: any) => {
// db triggered an event, send notification to remote subscriber
let eventMessage: IEventMessage = {
type: 'event',
from: this.id,
to: peerId,
path: details.path,
event: details.event,
data: {
path,
val,
previous,
context
}
};
this.sendMessage(eventMessage);
};
this.remoteSubscriptions.push({ for: peerId, event: details.event, path: details.path, callback: subscribeCallback });
this.storage.subscriptions.add(details.path, details.event, subscribeCallback);
}
protected cancelRemoteSubscription(peerId: string, details:ISubscriptionData) {
// Other tab requests to remove previously subscribed event
const sub = this.remoteSubscriptions.find(sub => sub.for === peerId && sub.event === details.event && sub.path === details.event);
if (!sub) {
// We don't know this subscription so we weren't notifying in the first place. Ignore
return;
}
// Stop subscription
this.storage.subscriptions.remove(details.path, details.event, sub.callback);
}
protected async handleMessage(message: IMessage) {
switch (message.type) {
case 'hello': return this.addPeer(message.from, message.to !== this.id, false);
case 'bye': return this.removePeer(message.from, true);
case 'subscribe': return this.addRemoteSubscription(message.from, message.data);
case 'unsubscribe': return this.cancelRemoteSubscription(message.from, message.data);
case 'event': {
if (!this._eventsEnabled) {
// IPC event handling is disabled for this client. Ignore message.
break;
}
const eventMessage = message as IEventMessage;
const context = eventMessage.data.context || {};
context.acebase_ipc = { type: this.ipcType, origin: eventMessage.from }; // Add IPC details
// Other peer raised an event we are monitoring
const subscriptions = this.ourSubscriptions.filter(sub => sub.event === eventMessage.event && sub.path === eventMessage.path);
subscriptions.forEach(sub => {
sub.callback(null, eventMessage.data.path, eventMessage.data.val, eventMessage.data.previous, context);
});
break;
}
case 'lock-request': {
// Lock request sent by worker to master
console.assert(this.isMaster, `Workers are not supposed to receive lock requests!`);
const request = message as ILockRequestMessage;
const result: ILockResponseMessage = { type: 'lock-result', id: request.id, from: this.id, to: request.from, ok: true, data: undefined };
try {
const lock = await this.lock(request.data);
result.data = {
id: lock.id,
path: lock.path,
tid: lock.tid,
write: lock.forWriting,
expires: lock.expires,
comment: lock.comment
};
}
catch(err) {
result.ok = false;
result.reason = err.stack || err.message || err;
}
return this.sendMessage(result);
}
case 'lock-result': {
// Lock result sent from master to worker
console.assert(!this.isMaster, `Masters are not supposed to receive results for lock requests!`);
const result = message as ILockResponseMessage;
const request = this._requests.get(result.id);
console.assert(typeof request === 'object', `The request must be known to us!`);
if (result.ok) {
request.resolve(result.data);
}
else {
request.reject(new Error(result.reason));
}
return;
}
case 'unlock-request': {
// lock release request sent from worker to master
console.assert(this.isMaster, `Workers are not supposed to receive unlock requests!`);
const request = message as IUnlockRequestMessage;
const result: IUnlockResponseMessage = { type: 'unlock-result', id: request.id, from: this.id, to: request.from, ok: true, data: { id: request.data.id } };
try {
const lockInfo = this._locks.find(l => l.lock?.id === request.data.id); // this._locks.get(request.data.id);
await lockInfo.lock.release(); //this.unlock(request.data.id);
}
catch(err) {
result.ok = false;
result.reason = err.stack || err.message || err;
}
return this.sendMessage(result);
}
case 'unlock-result': {
// lock release result sent from master to worker
console.assert(!this.isMaster, `Masters are not supposed to receive results for unlock requests!`);
const result = message as IUnlockResponseMessage;
const request = this._requests.get(result.id);
console.assert(typeof request === 'object', `The request must be known to us!`);
if (result.ok) {
request.resolve(result.data);
}
else {
request.reject(new Error(result.reason));
}
return;
}
case 'move-lock-request': {
// move lock request sent from worker to master
console.assert(this.isMaster, `Workers are not supposed to receive move lock requests!`);
const request = message as IMoveLockRequestMessage;
const result: ILockResponseMessage = { type: 'lock-result', id: request.id, from: this.id, to: request.from, ok: true, data: undefined };
try {
let movedLock: NodeLock;
// const lock = this._locks.get(request.data.id);
const lockRequest = this._locks.find(r => r.lock?.id === request.data.id);
if (request.data.move_to === 'parent') {
movedLock = await lockRequest.lock.moveToParent();
}
else {
throw new Error(`Unknown lock move_to "${request.data.move_to}"`);
}
// this._locks.delete(request.data.id);
// this._locks.set(movedLock.id, movedLock);
lockRequest.lock = movedLock;
result.data = {
id: movedLock.id,
path: movedLock.path,
tid: movedLock.tid,
write: movedLock.forWriting,
expires: movedLock.expires,
comment: movedLock.comment
};
}
catch(err) {
result.ok = false;
result.reason = err.stack || err.message || err;
}
return this.sendMessage(result);
}
case 'notification': {
// Custom notification received - raise event
return this.emit('notification', message);
}
case 'request': {
// Custom message received - raise event
return this.emit('request', message);
}
case 'result': {
// Result of custom request received - raise event
const result = message as IResponseMessage;
const request = this._requests.get(result.id);
console.assert(typeof request === 'object', `Result of unknown request received`);
if (result.ok) {
request.resolve(result.data);
}
else {
request.reject(new Error(result.reason));
}
}
}
}
protected _locks: Array<{ tid: string, granted: boolean, request: ILockRequestData, lock?: IAceBaseIPCLock }> = [];
/**
* Acquires a lock. If this peer is a worker, it will request the lock from the master
* @param details
*/
protected async lock(details:ILockRequestData): Promise<IAceBaseIPCLock> { // With methods release(), moveToParent() etc
if (this._exiting) {
// Peer is exiting. Do we have an existing lock with requested tid? If not, deny request.
const tidApproved = this._locks.find(l => l.tid === details.tid && l.granted);
if (!tidApproved) {
// We have no previously granted locks for this transaction. Deny.
throw new AceBaseIPCPeerExitingError('new transaction lock denied');
}
}
const removeLock = lockDetails => {
this._locks.splice(this._locks.indexOf(lockDetails), 1);
if (this._locks.length === 0) {
// this.storage.debug.log(`No more locks in worker ${this.id}`);
this.emit('locks-cleared');
}
};
if (this.isMaster) {
// Master
const lockInfo = { tid: details.tid, granted: false, request: details, lock: null };
this._locks.push(lockInfo);
const lock:NodeLock = await this._nodeLocker.lock(details.path, details.tid, details.write, details.comment);
lockInfo.tid = lock.tid;
lockInfo.granted = true;
const createIPCLock = (lock: NodeLock): IAceBaseIPCLock => {
return {
get id() { return lock.id; },
get tid() { return lock.tid },
get path() { return lock.path; },
get forWriting() { return lock.forWriting; },
get expires() { return lock.expires; },
get comment() { return lock.comment; },
get state() { return lock.state; },
release: async () => {
await lock.release();
removeLock(lockInfo);
},
moveToParent: async () => {
const parentLock = await lock.moveToParent();
lockInfo.lock = createIPCLock(parentLock);
return lockInfo.lock;
}
};
};
lockInfo.lock = createIPCLock(lock);
return lockInfo.lock;
}
else {
// Worker
const lockInfo = { tid: details.tid, granted: false, request: details, lock: null };
this._locks.push(lockInfo);
const createIPCLock = (result: ILockResponseData): IAceBaseIPCLock => {
lockInfo.granted = true;
lockInfo.tid = result.tid;
lockInfo.lock = {
id: result.id,
tid: result.tid,
path: result.path,
forWriting: result.write,
expires: result.expires,
comment: result.comment,
release: async () => {
const req: IUnlockRequestMessage = { type: 'unlock-request', id: ID.generate(), from: this.id, to: this.masterPeerId, data: { id: lockInfo.lock.id } };
const result = await this.request(req);
this.storage.debug.verbose(`Worker ${this.id} released lock ${lockInfo.lock.id} (tid ${lockInfo.lock.tid}, ${lockInfo.lock.comment}, "/${lockInfo.lock.path}", ${lockInfo.lock.forWriting ? 'write' : 'read'})`);
removeLock(lockInfo);
},
moveToParent: async () => {
const req: IMoveLockRequestMessage = { type: 'move-lock-request', id: ID.generate(), from: this.id, to: this.masterPeerId, data: { id: lockInfo.lock.id, move_to: 'parent' } };
let result;
try {
result = await this.request(req) as ILockResponseData;
}
catch(err) {
// We didn't get new lock?!
removeLock(lockInfo);
throw err;
}
lockInfo.lock = createIPCLock(result);
return lockInfo.lock;
}
};
// this.storage.debug.log(`Worker ${this.id} received lock ${lock.id} (tid ${lock.tid}, ${lock.comment}, "/${lock.path}", ${lock.forWriting ? 'write' : 'read'})`);
return lockInfo.lock;
};
const req: ILockRequestMessage = { type: 'lock-request', id: ID.generate(), from: this.id, to: this.masterPeerId, data: details };
let result:ILockResponseData, err: Error;
try {
result = await this.request(req) as ILockResponseData;
}
catch (e) {
err = e;
result = null;
}
if (err) {
removeLock(lockInfo);
throw err;
}
return createIPCLock(result);
}
}
private _requests:Map<string, { resolve: (result: any) => void, reject: (err: Error) => void, request: IRequestMessage }> = new Map();
private async request(req: IRequestMessage): Promise<any> {
// Send request, return result promise
let resolve, reject;
const promise = new Promise((rs, rj) => {
resolve = result => {
this._requests.delete(req.id);
rs(result);
};
reject = err => {
this._requests.delete(req.id);
rj(err);
};
});
this._requests.set(req.id, { resolve, reject, request: req });
this.sendMessage(req);
return promise;
}
protected abstract sendMessage(message: IMessage)
/**
* Sends a custom request to the IPC master
* @param request
* @returns
*/
public sendRequest(request: any) {
const req: ICustomRequestMessage = { type: 'request', from: this.id, to: this.masterPeerId, id: ID.generate(), data: request };
return this.request(req)
.catch(err => {
this.storage.debug.error(err);
throw err;
});
}
public replyRequest(requestMessage:IRequestMessage, result: any) {
const reply:IResponseMessage = { type: 'result', id: requestMessage.id, ok: true, from: this.id, to: requestMessage.from, data: result };
this.sendMessage(reply);
}
/**
* Sends a custom notification to all IPC peers
* @param notification
* @returns
*/
public sendNotification(notification: any) {
const msg: ICustomNotificationMessage = { type: 'notification', from: this.id, data: notification };
this.sendMessage(msg);
}
private _eventsEnabled: boolean = true;
/**
* If ipc event handling is currently enabled
*/
get eventsEnabled() { return this._eventsEnabled; }
/**
* Enables or disables ipc event handling. When disabled, incoming event messages will be ignored.
*/
set eventsEnabled(enabled: boolean) {
this.storage.debug.log(`ipc events ${enabled ? 'enabled' : 'disabled'}`);
this._eventsEnabled = enabled;
}
}
// interface IAceBasePrivateAPI {
// api: {
// subscribe(path: string, event: string, callback: (err: Error, path: string, value: any, previous: any, eventContext: any) => void): Promise<void>
// unsubscribe(path: string, event?: string, callback?: (err: Error, path: string, value: any, previous: any, eventContext: any) => void): Promise<void>
// }
// }
export interface IAceBaseIPCLock {
id: number
tid: string
path: string
forWriting: boolean
comment: string
expires: number
state: string
release(): Promise<void>
moveToParent(): Promise<IAceBaseIPCLock>
}
export type AceBaseSubscribeCallback = (error: Error, path: string, newValue: any, oldValue: any, eventContext: any) => void
export interface IMessage {
/**
* Message type, determines how to handle data
*/
type: string
/**
* Who sends this message
*/
from: string
/**
* Who is this message for (not present for broadcast messages)
*/
to?: string
/**
* Optional payload
*/
data?: any
}
export interface IHelloMessage extends IMessage {
type: 'hello'
data: void
}
export interface IByeMessage extends IMessage {
type: 'bye'
data: void
}
export interface IPulseMessage extends IMessage {
type: 'pulse'
data: void
}
export interface ICustomNotificationMessage extends IMessage {
type: 'notification'
data: any
}
export type AceBaseEventType = string; //'value' | 'child_added' | 'child_changed' | 'child_removed' | 'mutated' | 'mutations' | 'notify_value' | 'notify_child_added' | 'notify_child_changed' | 'notify_child_removed' | 'notify_mutated' | 'notify_mutations'
export interface ISubscriptionData {
path: string
event: AceBaseEventType
}
export interface ISubscribeMessage extends IMessage {
type: 'subscribe'
data: ISubscriptionData
}
export interface IUnsubscribeMessage extends IMessage {
type: 'unsubscribe',
data: ISubscriptionData
}
export interface IEventMessage extends IMessage {
type: 'event'
event: AceBaseEventType
/**
* Path the subscription is on
*/
path: string
data: {
/**
* The path the event fires on
*/
path: string
val?: any
previous?: any
context: any
}
}
export interface IRequestMessage extends IMessage {
id: string
}
export interface ILockRequestData {
path: string
write: boolean
tid: string
comment: string
}
export interface ILockRequestMessage extends IRequestMessage {
type: 'lock-request'
data: ILockRequestData
}
export interface IUnlockRequestData {
id: number
}
export interface IUnlockRequestMessage extends IRequestMessage {
type: 'unlock-request'
data: IUnlockRequestData
}
export interface IResponseMessage extends IMessage {
id: string
ok: boolean
reason?: string
}
export interface ILockResponseData {
id: number
path: string
write: boolean
tid: string
expires: number
comment: string
}
export interface ILockResponseMessage extends IResponseMessage {
type: 'lock-result'
data: ILockResponseData
}
export interface IUnlockResponseData {
id: number
}
export interface IUnlockResponseMessage extends IResponseMessage {
type: 'unlock-result'
data: IUnlockResponseData
}
export interface IMoveLockRequestData {
id: number
move_to: 'parent'|'path'
}
export interface IMoveLockRequestMessage extends IRequestMessage {
type: 'move-lock-request'
data: IMoveLockRequestData
}
export interface ICustomRequestMessage extends IRequestMessage {
type: 'request',
data: any
} | the_stack |
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.
*/
/* eslint-disable sort-keys, local/prefer-spread-eventually, local/prefer-rest-params-eventually */
import {AssertionError} from 'assert';
import {ErrorWithStack, isPromise} from 'jest-util';
import assertionErrorMessage from '../assertionErrorMessage';
import isError from '../isError';
import queueRunner, {
Options as QueueRunnerOptions,
QueueableFn,
} from '../queueRunner';
import treeProcessor, {TreeNode} from '../treeProcessor';
import type {
AssertionErrorWithStack,
Jasmine,
Reporter,
SpecDefinitionsFn,
Spy,
} from '../types';
import type {default as Spec, SpecResult} from './Spec';
import type Suite from './Suite';
export default function (j$: Jasmine) {
return class Env {
specFilter: (spec: Spec) => boolean;
catchExceptions: (value: unknown) => boolean;
throwOnExpectationFailure: (value: unknown) => void;
catchingExceptions: () => boolean;
topSuite: () => Suite;
fail: (error: Error | AssertionErrorWithStack) => void;
pending: (message: string) => void;
afterAll: (afterAllFunction: QueueableFn['fn'], timeout?: number) => void;
fit: (description: string, fn: QueueableFn['fn'], timeout?: number) => Spec;
throwingExpectationFailures: () => boolean;
randomizeTests: (value: unknown) => void;
randomTests: () => boolean;
seed: (value: unknown) => unknown;
execute: (
runnablesToRun?: Array<string>,
suiteTree?: Suite,
) => Promise<void>;
fdescribe: (
description: string,
specDefinitions: SpecDefinitionsFn,
) => Suite;
spyOn: (
obj: Record<string, Spy>,
methodName: string,
accessType?: keyof PropertyDescriptor,
) => Spy;
beforeEach: (
beforeEachFunction: QueueableFn['fn'],
timeout?: number,
) => void;
afterEach: (afterEachFunction: QueueableFn['fn'], timeout?: number) => void;
clearReporters: () => void;
addReporter: (reporterToAdd: Reporter) => void;
it: (description: string, fn: QueueableFn['fn'], timeout?: number) => Spec;
xdescribe: (
description: string,
specDefinitions: SpecDefinitionsFn,
) => Suite;
xit: (description: string, fn: QueueableFn['fn'], timeout?: number) => Spec;
beforeAll: (beforeAllFunction: QueueableFn['fn'], timeout?: number) => void;
todo: () => Spec;
provideFallbackReporter: (reporterToAdd: Reporter) => void;
allowRespy: (allow: boolean) => void;
describe: (
description: string,
specDefinitions: SpecDefinitionsFn,
) => Suite;
constructor() {
let totalSpecsDefined = 0;
let catchExceptions = true;
const realSetTimeout =
global.setTimeout as typeof globalThis['setTimeout'];
const realClearTimeout =
global.clearTimeout as typeof globalThis['clearTimeout'];
const runnableResources: Record<string, {spies: Array<Spy>}> = {};
const currentlyExecutingSuites: Array<Suite> = [];
let currentSpec: Spec | null = null;
let throwOnExpectationFailure = false;
let random = false;
let seed: unknown | null = null;
let nextSpecId = 0;
let nextSuiteId = 0;
const getNextSpecId = function () {
return 'spec' + nextSpecId++;
};
const getNextSuiteId = function () {
return 'suite' + nextSuiteId++;
};
const topSuite = new j$.Suite({
id: getNextSuiteId(),
description: '',
getTestPath() {
return j$.testPath;
},
});
let currentDeclarationSuite = topSuite;
const currentSuite = function () {
return currentlyExecutingSuites[currentlyExecutingSuites.length - 1];
};
const currentRunnable = function () {
return currentSpec || currentSuite();
};
const reporter = new j$.ReportDispatcher([
'jasmineStarted',
'jasmineDone',
'suiteStarted',
'suiteDone',
'specStarted',
'specDone',
]);
this.specFilter = function () {
return true;
};
const defaultResourcesForRunnable = function (
id: string,
_parentRunnableId?: string,
) {
const resources = {spies: []};
runnableResources[id] = resources;
};
const clearResourcesForRunnable = function (id: string) {
spyRegistry.clearSpies();
delete runnableResources[id];
};
const beforeAndAfterFns = function (suite: Suite) {
return function () {
let afters: Array<QueueableFn> = [];
let befores: Array<QueueableFn> = [];
while (suite) {
befores = befores.concat(suite.beforeFns);
afters = afters.concat(suite.afterFns);
suite = suite.parentSuite!;
}
return {
befores: befores.reverse(),
afters,
};
};
};
const getSpecName = function (spec: Spec, suite: Suite) {
const fullName = [spec.description];
const suiteFullName = suite.getFullName();
if (suiteFullName !== '') {
fullName.unshift(suiteFullName);
}
return fullName.join(' ');
};
this.catchExceptions = function (value) {
catchExceptions = !!value;
return catchExceptions;
};
this.catchingExceptions = function () {
return catchExceptions;
};
this.throwOnExpectationFailure = function (value) {
throwOnExpectationFailure = !!value;
};
this.throwingExpectationFailures = function () {
return throwOnExpectationFailure;
};
this.randomizeTests = function (value) {
random = !!value;
};
this.randomTests = function () {
return random;
};
this.seed = function (value) {
if (value) {
seed = value;
}
return seed;
};
const queueRunnerFactory = (options: QueueRunnerOptions) => {
options.clearTimeout = realClearTimeout;
options.fail = this.fail;
options.setTimeout = realSetTimeout;
return queueRunner(options);
};
this.topSuite = function () {
return topSuite;
};
const uncaught: NodeJS.UncaughtExceptionListener &
NodeJS.UnhandledRejectionListener = (err: any) => {
if (currentSpec) {
currentSpec.onException(err);
currentSpec.cancel();
} else {
console.error('Unhandled error');
console.error(err.stack);
}
};
let oldListenersException: Array<NodeJS.UncaughtExceptionListener>;
let oldListenersRejection: Array<NodeJS.UnhandledRejectionListener>;
const executionSetup = function () {
// Need to ensure we are the only ones handling these exceptions.
oldListenersException = process.listeners('uncaughtException').slice();
oldListenersRejection = process.listeners('unhandledRejection').slice();
j$.process.removeAllListeners('uncaughtException');
j$.process.removeAllListeners('unhandledRejection');
j$.process.on('uncaughtException', uncaught);
j$.process.on('unhandledRejection', uncaught);
};
const executionTeardown = function () {
j$.process.removeListener('uncaughtException', uncaught);
j$.process.removeListener('unhandledRejection', uncaught);
// restore previous exception handlers
oldListenersException.forEach(listener => {
j$.process.on('uncaughtException', listener);
});
oldListenersRejection.forEach(listener => {
j$.process.on('unhandledRejection', listener);
});
};
this.execute = async function (runnablesToRun, suiteTree = topSuite) {
if (!runnablesToRun) {
if (focusedRunnables.length) {
runnablesToRun = focusedRunnables;
} else {
runnablesToRun = [suiteTree.id];
}
}
if (currentlyExecutingSuites.length === 0) {
executionSetup();
}
const lastDeclarationSuite = currentDeclarationSuite;
await treeProcessor({
nodeComplete(suite) {
if (!suite.disabled) {
clearResourcesForRunnable(suite.id);
}
currentlyExecutingSuites.pop();
if (suite === topSuite) {
reporter.jasmineDone({
failedExpectations: topSuite.result.failedExpectations,
});
} else {
reporter.suiteDone(suite.getResult());
}
},
nodeStart(suite) {
currentlyExecutingSuites.push(suite as Suite);
defaultResourcesForRunnable(
suite.id,
suite.parentSuite && suite.parentSuite.id,
);
if (suite === topSuite) {
reporter.jasmineStarted({totalSpecsDefined});
} else {
reporter.suiteStarted(suite.result);
}
},
queueRunnerFactory,
runnableIds: runnablesToRun,
tree: suiteTree as TreeNode,
});
currentDeclarationSuite = lastDeclarationSuite;
if (currentlyExecutingSuites.length === 0) {
executionTeardown();
}
};
this.addReporter = function (reporterToAdd) {
reporter.addReporter(reporterToAdd);
};
this.provideFallbackReporter = function (reporterToAdd) {
reporter.provideFallbackReporter(reporterToAdd);
};
this.clearReporters = function () {
reporter.clearReporters();
};
const spyRegistry = new j$.SpyRegistry({
currentSpies() {
if (!currentRunnable()) {
throw new Error(
'Spies must be created in a before function or a spec',
);
}
return runnableResources[currentRunnable().id].spies;
},
});
this.allowRespy = function (allow) {
spyRegistry.allowRespy(allow);
};
this.spyOn = function (...args) {
return spyRegistry.spyOn.apply(spyRegistry, args);
};
const suiteFactory = function (description: string) {
const suite = new j$.Suite({
id: getNextSuiteId(),
description,
parentSuite: currentDeclarationSuite,
throwOnExpectationFailure,
getTestPath() {
return j$.testPath;
},
});
return suite;
};
this.describe = function (description: string, specDefinitions) {
const suite = suiteFactory(description);
if (specDefinitions === undefined) {
throw new Error(
`Missing second argument. It must be a callback function.`,
);
}
if (typeof specDefinitions !== 'function') {
throw new Error(
`Invalid second argument, ${specDefinitions}. It must be a callback function.`,
);
}
if (specDefinitions.length > 0) {
throw new Error('describe does not expect any arguments');
}
if (currentDeclarationSuite.markedPending) {
suite.pend();
}
if (currentDeclarationSuite.markedTodo) {
// @ts-expect-error TODO Possible error: Suite does not have todo method
suite.todo();
}
addSpecsToSuite(suite, specDefinitions);
return suite;
};
this.xdescribe = function (description, specDefinitions) {
const suite = suiteFactory(description);
suite.pend();
addSpecsToSuite(suite, specDefinitions);
return suite;
};
const focusedRunnables: Array<string> = [];
this.fdescribe = function (description, specDefinitions) {
const suite = suiteFactory(description);
suite.isFocused = true;
focusedRunnables.push(suite.id);
unfocusAncestor();
addSpecsToSuite(suite, specDefinitions);
return suite;
};
const addSpecsToSuite = (
suite: Suite,
specDefinitions: SpecDefinitionsFn,
) => {
const parentSuite = currentDeclarationSuite;
parentSuite.addChild(suite);
currentDeclarationSuite = suite;
let declarationError: undefined | Error = undefined;
let describeReturnValue: unknown | Error;
try {
describeReturnValue = specDefinitions.call(suite);
} catch (e: any) {
declarationError = e;
}
if (isPromise(describeReturnValue)) {
declarationError = new Error(
'Returning a Promise from "describe" is not supported. Tests must be defined synchronously.',
);
} else if (describeReturnValue !== undefined) {
declarationError = new Error(
'A "describe" callback must not return a value.',
);
}
if (declarationError) {
this.it('encountered a declaration exception', () => {
throw declarationError;
});
}
currentDeclarationSuite = parentSuite;
};
function findFocusedAncestor(suite: Suite) {
while (suite) {
if (suite.isFocused) {
return suite.id;
}
suite = suite.parentSuite!;
}
return null;
}
function unfocusAncestor() {
const focusedAncestor = findFocusedAncestor(currentDeclarationSuite);
if (focusedAncestor) {
for (let i = 0; i < focusedRunnables.length; i++) {
if (focusedRunnables[i] === focusedAncestor) {
focusedRunnables.splice(i, 1);
break;
}
}
}
}
const specFactory = (
description: string,
fn: QueueableFn['fn'],
suite: Suite,
timeout?: number,
): Spec => {
totalSpecsDefined++;
const spec = new j$.Spec({
id: getNextSpecId(),
beforeAndAfterFns: beforeAndAfterFns(suite),
resultCallback: specResultCallback,
getSpecName(spec: Spec) {
return getSpecName(spec, suite);
},
getTestPath() {
return j$.testPath;
},
onStart: specStarted,
description,
queueRunnerFactory,
userContext() {
return suite.clonedSharedUserContext();
},
queueableFn: {
fn,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
},
},
throwOnExpectationFailure,
});
if (!this.specFilter(spec)) {
spec.disable();
}
return spec;
function specResultCallback(result: SpecResult) {
clearResourcesForRunnable(spec.id);
currentSpec = null;
reporter.specDone(result);
}
function specStarted(spec: Spec) {
currentSpec = spec;
defaultResourcesForRunnable(spec.id, suite.id);
reporter.specStarted(spec.result);
}
};
this.it = function (description, fn, timeout) {
if (typeof description !== 'string') {
throw new Error(
`Invalid first argument, ${description}. It must be a string.`,
);
}
if (fn === undefined) {
throw new Error(
'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.',
);
}
if (typeof fn !== 'function') {
throw new Error(
`Invalid second argument, ${fn}. It must be a callback function.`,
);
}
const spec = specFactory(
description,
fn,
currentDeclarationSuite,
timeout,
);
if (currentDeclarationSuite.markedPending) {
spec.pend();
}
// When a test is defined inside another, jasmine will not run it.
// This check throws an error to warn the user about the edge-case.
if (currentSpec !== null) {
throw new Error(
`Tests cannot be nested. Test "${spec.description}" cannot run because it is nested within "${currentSpec.description}".`,
);
}
currentDeclarationSuite.addChild(spec);
return spec;
};
this.xit = function (...args) {
const spec = this.it.apply(this, args);
spec.pend('Temporarily disabled with xit');
return spec;
};
this.todo = function () {
const description = arguments[0];
if (arguments.length !== 1 || typeof description !== 'string') {
throw new ErrorWithStack(
'Todo must be called with only a description.',
this.todo,
);
}
const spec = specFactory(
description,
() => {},
currentDeclarationSuite,
);
if (currentDeclarationSuite.markedPending) {
spec.pend();
} else {
spec.todo();
}
currentDeclarationSuite.addChild(spec);
return spec;
};
this.fit = function (description, fn, timeout) {
const spec = specFactory(
description,
fn,
currentDeclarationSuite,
timeout,
);
currentDeclarationSuite.addChild(spec);
if (currentDeclarationSuite.markedPending) {
spec.pend();
} else {
focusedRunnables.push(spec.id);
}
unfocusAncestor();
return spec;
};
this.beforeEach = function (beforeEachFunction, timeout) {
currentDeclarationSuite.beforeEach({
fn: beforeEachFunction,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
},
});
};
this.beforeAll = function (beforeAllFunction, timeout) {
currentDeclarationSuite.beforeAll({
fn: beforeAllFunction,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
},
});
};
this.afterEach = function (afterEachFunction, timeout) {
currentDeclarationSuite.afterEach({
fn: afterEachFunction,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
},
});
};
this.afterAll = function (afterAllFunction, timeout) {
currentDeclarationSuite.afterAll({
fn: afterAllFunction,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
},
});
};
this.pending = function (message) {
let fullMessage = j$.Spec.pendingSpecExceptionMessage;
if (message) {
fullMessage += message;
}
throw fullMessage;
};
this.fail = function (error) {
let checkIsError;
let message;
if (
error instanceof AssertionError ||
(error && error.name === AssertionError.name)
) {
checkIsError = false;
// @ts-expect-error TODO Possible error: j$.Spec does not have expand property
message = assertionErrorMessage(error, {expand: j$.Spec.expand});
} else {
const check = isError(error);
checkIsError = check.isError;
message = check.message;
}
const errorAsErrorObject = checkIsError ? error : new Error(message!);
const runnable = currentRunnable();
if (!runnable) {
errorAsErrorObject.message =
'Caught error after test environment was torn down\n\n' +
errorAsErrorObject.message;
throw errorAsErrorObject;
}
runnable.addExpectationResult(false, {
matcherName: '',
passed: false,
expected: '',
actual: '',
message,
error: errorAsErrorObject,
});
};
}
};
} | the_stack |
import { Inject, Injectable } from '@angular/core';
import { DashboardService } from '@core/http/dashboard.service';
import { TranslateService } from '@ngx-translate/core';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { ActionNotificationShow } from '@core/notification/notification.actions';
import { Dashboard, DashboardLayoutId } from '@shared/models/dashboard.models';
import { deepClone, isDefined, isObject, isString, isUndefined } from '@core/utils';
import { WINDOW } from '@core/services/window.service';
import { DOCUMENT } from '@angular/common';
import {
AliasesInfo,
AliasFilterType,
EntityAlias,
EntityAliases,
EntityAliasFilter,
EntityAliasInfo
} from '@shared/models/alias.models';
import { MatDialog } from '@angular/material/dialog';
import { ImportDialogComponent, ImportDialogData } from '@home/components/import-export/import-dialog.component';
import { forkJoin, Observable, of } from 'rxjs';
import { catchError, map, mergeMap, tap } from 'rxjs/operators';
import { DashboardUtilsService } from '@core/services/dashboard-utils.service';
import { EntityService } from '@core/http/entity.service';
import { Widget, WidgetSize, WidgetType, WidgetTypeDetails } from '@shared/models/widget.models';
import {
EntityAliasesDialogComponent,
EntityAliasesDialogData
} from '@home/components/alias/entity-aliases-dialog.component';
import { ItemBufferService, WidgetItem } from '@core/services/item-buffer.service';
import { FileType, ImportWidgetResult, JSON_TYPE, WidgetsBundleItem, ZIP_TYPE, BulkImportRequest, BulkImportResult } from './import-export.models';
import { EntityType } from '@shared/models/entity-type.models';
import { UtilsService } from '@core/services/utils.service';
import { WidgetService } from '@core/http/widget.service';
import { NULL_UUID } from '@shared/models/id/has-uuid';
import { WidgetsBundle } from '@shared/models/widgets-bundle.model';
import { ImportEntitiesResultInfo, ImportEntityData } from '@shared/models/entity.models';
import { RequestConfig } from '@core/http/http-utils';
import { RuleChain, RuleChainImport, RuleChainMetaData, RuleChainType } from '@shared/models/rule-chain.models';
import { RuleChainService } from '@core/http/rule-chain.service';
import { FiltersInfo } from '@shared/models/query/query.models';
import { DeviceProfileService } from '@core/http/device-profile.service';
import { DeviceProfile } from '@shared/models/device.models';
import { TenantProfile } from '@shared/models/tenant.model';
import { TenantProfileService } from '@core/http/tenant-profile.service';
import { DeviceService } from '@core/http/device.service';
import { AssetService } from '@core/http/asset.service';
import { EdgeService } from '@core/http/edge.service';
// @dynamic
@Injectable()
export class ImportExportService {
constructor(@Inject(WINDOW) private window: Window,
@Inject(DOCUMENT) private document: Document,
private store: Store<AppState>,
private translate: TranslateService,
private dashboardService: DashboardService,
private dashboardUtils: DashboardUtilsService,
private widgetService: WidgetService,
private deviceProfileService: DeviceProfileService,
private tenantProfileService: TenantProfileService,
private entityService: EntityService,
private ruleChainService: RuleChainService,
private deviceService: DeviceService,
private assetService: AssetService,
private edgeService: EdgeService,
private utils: UtilsService,
private itembuffer: ItemBufferService,
private dialog: MatDialog) {
}
public exportDashboard(dashboardId: string) {
this.dashboardService.getDashboard(dashboardId).subscribe(
(dashboard) => {
let name = dashboard.title;
name = name.toLowerCase().replace(/\W/g, '_');
this.exportToPc(this.prepareDashboardExport(dashboard), name);
},
(e) => {
this.handleExportError(e, 'dashboard.export-failed-error');
}
);
}
public importDashboard(): Observable<Dashboard> {
return this.openImportDialog('dashboard.import', 'dashboard.dashboard-file').pipe(
mergeMap((dashboard: Dashboard) => {
if (!this.validateImportedDashboard(dashboard)) {
this.store.dispatch(new ActionNotificationShow(
{message: this.translate.instant('dashboard.invalid-dashboard-file-error'),
type: 'error'}));
throw new Error('Invalid dashboard file');
} else {
dashboard = this.dashboardUtils.validateAndUpdateDashboard(dashboard);
let aliasIds = null;
const entityAliases = dashboard.configuration.entityAliases;
if (entityAliases) {
aliasIds = Object.keys(entityAliases);
}
if (aliasIds && aliasIds.length > 0) {
return this.processEntityAliases(entityAliases, aliasIds).pipe(
mergeMap((missingEntityAliases) => {
if (Object.keys(missingEntityAliases).length > 0) {
return this.editMissingAliases(this.dashboardUtils.getWidgetsArray(dashboard),
false, 'dashboard.dashboard-import-missing-aliases-title',
missingEntityAliases).pipe(
mergeMap((updatedEntityAliases) => {
for (const aliasId of Object.keys(updatedEntityAliases)) {
entityAliases[aliasId] = updatedEntityAliases[aliasId];
}
return this.saveImportedDashboard(dashboard);
})
);
} else {
return this.saveImportedDashboard(dashboard);
}
}
));
} else {
return this.saveImportedDashboard(dashboard);
}
}
}),
catchError((err) => {
return of(null);
})
);
}
public exportWidget(dashboard: Dashboard, sourceState: string, sourceLayout: DashboardLayoutId, widget: Widget) {
const widgetItem = this.itembuffer.prepareWidgetItem(dashboard, sourceState, sourceLayout, widget);
let name = widgetItem.widget.config.title;
name = name.toLowerCase().replace(/\W/g, '_');
this.exportToPc(this.prepareExport(widgetItem), name);
}
public importWidget(dashboard: Dashboard, targetState: string,
targetLayoutFunction: () => Observable<DashboardLayoutId>,
onAliasesUpdateFunction: () => void,
onFiltersUpdateFunction: () => void): Observable<ImportWidgetResult> {
return this.openImportDialog('dashboard.import-widget', 'dashboard.widget-file').pipe(
mergeMap((widgetItem: WidgetItem) => {
if (!this.validateImportedWidget(widgetItem)) {
this.store.dispatch(new ActionNotificationShow(
{message: this.translate.instant('dashboard.invalid-widget-file-error'),
type: 'error'}));
throw new Error('Invalid widget file');
} else {
let widget = widgetItem.widget;
widget = this.dashboardUtils.validateAndUpdateWidget(widget);
const aliasesInfo = this.prepareAliasesInfo(widgetItem.aliasesInfo);
const filtersInfo: FiltersInfo = widgetItem.filtersInfo || {
datasourceFilters: {}
};
const originalColumns = widgetItem.originalColumns;
const originalSize = widgetItem.originalSize;
const datasourceAliases = aliasesInfo.datasourceAliases;
const targetDeviceAliases = aliasesInfo.targetDeviceAliases;
if (datasourceAliases || targetDeviceAliases) {
const entityAliases: EntityAliases = {};
const datasourceAliasesMap: {[aliasId: string]: number} = {};
const targetDeviceAliasesMap: {[aliasId: string]: number} = {};
let aliasId: string;
let datasourceIndex: number;
if (datasourceAliases) {
for (const strIndex of Object.keys(datasourceAliases)) {
datasourceIndex = Number(strIndex);
aliasId = this.utils.guid();
datasourceAliasesMap[aliasId] = datasourceIndex;
entityAliases[aliasId] = {id: aliasId, ...datasourceAliases[datasourceIndex]};
}
}
if (targetDeviceAliases) {
for (const strIndex of Object.keys(targetDeviceAliases)) {
datasourceIndex = Number(strIndex);
aliasId = this.utils.guid();
targetDeviceAliasesMap[aliasId] = datasourceIndex;
entityAliases[aliasId] = {id: aliasId, ...targetDeviceAliases[datasourceIndex]};
}
}
const aliasIds = Object.keys(entityAliases);
if (aliasIds.length > 0) {
return this.processEntityAliases(entityAliases, aliasIds).pipe(
mergeMap((missingEntityAliases) => {
if (Object.keys(missingEntityAliases).length > 0) {
return this.editMissingAliases([widget],
false, 'dashboard.widget-import-missing-aliases-title',
missingEntityAliases).pipe(
mergeMap((updatedEntityAliases) => {
for (const id of Object.keys(updatedEntityAliases)) {
const entityAlias = updatedEntityAliases[id];
let index;
if (isDefined(datasourceAliasesMap[id])) {
index = datasourceAliasesMap[id];
datasourceAliases[index] = entityAlias;
} else if (isDefined(targetDeviceAliasesMap[id])) {
index = targetDeviceAliasesMap[id];
targetDeviceAliases[index] = entityAlias;
}
}
return this.addImportedWidget(dashboard, targetState, targetLayoutFunction, widget,
aliasesInfo, filtersInfo, onAliasesUpdateFunction, onFiltersUpdateFunction, originalColumns, originalSize);
}
));
} else {
return this.addImportedWidget(dashboard, targetState, targetLayoutFunction, widget,
aliasesInfo, filtersInfo, onAliasesUpdateFunction, onFiltersUpdateFunction, originalColumns, originalSize);
}
}
)
);
} else {
return this.addImportedWidget(dashboard, targetState, targetLayoutFunction, widget,
aliasesInfo, filtersInfo, onAliasesUpdateFunction, onFiltersUpdateFunction, originalColumns, originalSize);
}
} else {
return this.addImportedWidget(dashboard, targetState, targetLayoutFunction, widget,
aliasesInfo, filtersInfo, onAliasesUpdateFunction, onFiltersUpdateFunction, originalColumns, originalSize);
}
}
}),
catchError((err) => {
return of(null);
})
);
}
public exportWidgetType(widgetTypeId: string) {
this.widgetService.getWidgetTypeById(widgetTypeId).subscribe(
(widgetTypeDetails) => {
if (isDefined(widgetTypeDetails.bundleAlias)) {
delete widgetTypeDetails.bundleAlias;
}
let name = widgetTypeDetails.name;
name = name.toLowerCase().replace(/\W/g, '_');
this.exportToPc(this.prepareExport(widgetTypeDetails), name);
},
(e) => {
this.handleExportError(e, 'widget-type.export-failed-error');
}
);
}
public importWidgetType(bundleAlias: string): Observable<WidgetType> {
return this.openImportDialog('widget-type.import', 'widget-type.widget-type-file').pipe(
mergeMap((widgetTypeDetails: WidgetTypeDetails) => {
if (!this.validateImportedWidgetTypeDetails(widgetTypeDetails)) {
this.store.dispatch(new ActionNotificationShow(
{message: this.translate.instant('widget-type.invalid-widget-type-file-error'),
type: 'error'}));
throw new Error('Invalid widget type file');
} else {
widgetTypeDetails.bundleAlias = bundleAlias;
return this.widgetService.saveImportedWidgetTypeDetails(widgetTypeDetails);
}
}),
catchError((err) => {
return of(null);
})
);
}
public exportWidgetsBundle(widgetsBundleId: string) {
this.widgetService.getWidgetsBundle(widgetsBundleId).subscribe(
(widgetsBundle) => {
const bundleAlias = widgetsBundle.alias;
const isSystem = widgetsBundle.tenantId.id === NULL_UUID;
this.widgetService.getBundleWidgetTypesDetails(bundleAlias, isSystem).subscribe(
(widgetTypesDetails) => {
widgetTypesDetails = widgetTypesDetails.sort((a, b) => a.createdTime - b.createdTime);
const widgetsBundleItem: WidgetsBundleItem = {
widgetsBundle: this.prepareExport(widgetsBundle),
widgetTypes: []
};
for (const widgetTypeDetails of widgetTypesDetails) {
if (isDefined(widgetTypeDetails.bundleAlias)) {
delete widgetTypeDetails.bundleAlias;
}
widgetsBundleItem.widgetTypes.push(this.prepareExport(widgetTypeDetails));
}
let name = widgetsBundle.title;
name = name.toLowerCase().replace(/\W/g, '_');
this.exportToPc(widgetsBundleItem, name);
},
(e) => {
this.handleExportError(e, 'widgets-bundle.export-failed-error');
}
);
},
(e) => {
this.handleExportError(e, 'widgets-bundle.export-failed-error');
}
);
}
public importWidgetsBundle(): Observable<WidgetsBundle> {
return this.openImportDialog('widgets-bundle.import', 'widgets-bundle.widgets-bundle-file').pipe(
mergeMap((widgetsBundleItem: WidgetsBundleItem) => {
if (!this.validateImportedWidgetsBundle(widgetsBundleItem)) {
this.store.dispatch(new ActionNotificationShow(
{message: this.translate.instant('widgets-bundle.invalid-widgets-bundle-file-error'),
type: 'error'}));
throw new Error('Invalid widgets bundle file');
} else {
const widgetsBundle = widgetsBundleItem.widgetsBundle;
return this.widgetService.saveWidgetsBundle(widgetsBundle).pipe(
mergeMap((savedWidgetsBundle) => {
const bundleAlias = savedWidgetsBundle.alias;
const widgetTypesDetails = widgetsBundleItem.widgetTypes;
if (widgetTypesDetails.length) {
const saveWidgetTypesObservables: Array<Observable<WidgetType>> = [];
for (const widgetTypeDetails of widgetTypesDetails) {
widgetTypeDetails.bundleAlias = bundleAlias;
saveWidgetTypesObservables.push(this.widgetService.saveImportedWidgetTypeDetails(widgetTypeDetails));
}
return forkJoin(saveWidgetTypesObservables).pipe(
map(() => savedWidgetsBundle)
);
} else {
return of(savedWidgetsBundle);
}
}
));
}
}),
catchError((err) => {
return of(null);
})
);
}
public bulkImportEntities(entitiesData: BulkImportRequest, entityType: EntityType, config?: RequestConfig): Observable<BulkImportResult> {
switch (entityType) {
case EntityType.DEVICE:
return this.deviceService.bulkImportDevices(entitiesData, config);
case EntityType.ASSET:
return this.assetService.bulkImportAssets(entitiesData, config);
case EntityType.EDGE:
return this.edgeService.bulkImportEdges(entitiesData, config);
}
}
public importEntities(entitiesData: ImportEntityData[], entityType: EntityType, updateData: boolean,
importEntityCompleted?: () => void, config?: RequestConfig): Observable<ImportEntitiesResultInfo> {
let partSize = 100;
partSize = entitiesData.length > partSize ? partSize : entitiesData.length;
let statisticalInfo: ImportEntitiesResultInfo = {};
const importEntitiesObservables: Observable<ImportEntitiesResultInfo>[] = [];
for (let i = 0; i < partSize; i++) {
let saveEntityPromise: Observable<ImportEntitiesResultInfo>;
saveEntityPromise = this.entityService.saveEntityParameters(entityType, entitiesData[i], updateData, config);
const importEntityPromise = saveEntityPromise.pipe(
tap((res) => {
if (importEntityCompleted) {
importEntityCompleted();
}
})
);
importEntitiesObservables.push(importEntityPromise);
}
return forkJoin(importEntitiesObservables).pipe(
mergeMap((responses) => {
for (const response of responses) {
statisticalInfo = this.sumObject(statisticalInfo, response);
}
entitiesData.splice(0, partSize);
if (entitiesData.length) {
return this.importEntities(entitiesData, entityType, updateData, importEntityCompleted, config).pipe(
map((response) => {
return this.sumObject(statisticalInfo, response) as ImportEntitiesResultInfo;
})
);
} else {
return of(statisticalInfo);
}
})
);
}
public exportRuleChain(ruleChainId: string) {
this.ruleChainService.getRuleChain(ruleChainId).pipe(
mergeMap(ruleChain => {
return this.ruleChainService.getRuleChainMetadata(ruleChainId).pipe(
map((ruleChainMetaData) => {
const ruleChainExport: RuleChainImport = {
ruleChain: this.prepareRuleChain(ruleChain),
metadata: this.prepareRuleChainMetaData(ruleChainMetaData)
};
return ruleChainExport;
})
);
})
).subscribe((ruleChainExport) => {
let name = ruleChainExport.ruleChain.name;
name = name.toLowerCase().replace(/\W/g, '_');
this.exportToPc(ruleChainExport, name);
},
(e) => {
this.handleExportError(e, 'rulechain.export-failed-error');
}
);
}
public importRuleChain(expectedRuleChainType: RuleChainType): Observable<RuleChainImport> {
return this.openImportDialog('rulechain.import', 'rulechain.rulechain-file').pipe(
map((ruleChainImport: RuleChainImport) => {
if (!this.validateImportedRuleChain(ruleChainImport)) {
this.store.dispatch(new ActionNotificationShow(
{message: this.translate.instant('rulechain.invalid-rulechain-file-error'),
type: 'error'}));
throw new Error('Invalid rule chain file');
} else if (ruleChainImport.ruleChain.type !== expectedRuleChainType) {
this.store.dispatch(new ActionNotificationShow(
{message: this.translate.instant('rulechain.invalid-rulechain-type-error', {expectedRuleChainType}),
type: 'error'}));
throw new Error('Invalid rule chain type');
} else {
return ruleChainImport;
}
}),
catchError((err) => {
return of(null);
})
);
}
public exportDeviceProfile(deviceProfileId: string) {
this.deviceProfileService.getDeviceProfile(deviceProfileId).subscribe(
(deviceProfile) => {
let name = deviceProfile.name;
name = name.toLowerCase().replace(/\W/g, '_');
this.exportToPc(this.prepareProfileExport(deviceProfile), name);
},
(e) => {
this.handleExportError(e, 'device-profile.export-failed-error');
}
);
}
public importDeviceProfile(): Observable<DeviceProfile> {
return this.openImportDialog('device-profile.import', 'device-profile.device-profile-file').pipe(
mergeMap((deviceProfile: DeviceProfile) => {
if (!this.validateImportedDeviceProfile(deviceProfile)) {
this.store.dispatch(new ActionNotificationShow(
{message: this.translate.instant('device-profile.invalid-device-profile-file-error'),
type: 'error'}));
throw new Error('Invalid device profile file');
} else {
return this.deviceProfileService.saveDeviceProfile(deviceProfile);
}
}),
catchError((err) => {
return of(null);
})
);
}
public exportTenantProfile(tenantProfileId: string) {
this.tenantProfileService.getTenantProfile(tenantProfileId).subscribe(
(tenantProfile) => {
let name = tenantProfile.name;
name = name.toLowerCase().replace(/\W/g, '_');
this.exportToPc(this.prepareProfileExport(tenantProfile), name);
},
(e) => {
this.handleExportError(e, 'tenant-profile.export-failed-error');
}
);
}
public importTenantProfile(): Observable<TenantProfile> {
return this.openImportDialog('tenant-profile.import', 'tenant-profile.tenant-profile-file').pipe(
mergeMap((tenantProfile: TenantProfile) => {
if (!this.validateImportedTenantProfile(tenantProfile)) {
this.store.dispatch(new ActionNotificationShow(
{message: this.translate.instant('tenant-profile.invalid-tenant-profile-file-error'),
type: 'error'}));
throw new Error('Invalid tenant profile file');
} else {
return this.tenantProfileService.saveTenantProfile(tenantProfile);
}
}),
catchError(() => {
return of(null);
})
);
}
public exportJSZip(data: object, filename: string) {
import('jszip').then((JSZip) => {
const jsZip = new JSZip.default();
for (const keyName in data) {
if (data.hasOwnProperty(keyName)) {
const valueData = data[keyName];
jsZip.file(keyName, valueData);
}
}
jsZip.generateAsync({type: 'blob'}).then(content => {
this.downloadFile(content, filename, ZIP_TYPE);
});
});
}
private prepareRuleChain(ruleChain: RuleChain): RuleChain {
ruleChain = this.prepareExport(ruleChain);
if (ruleChain.firstRuleNodeId) {
ruleChain.firstRuleNodeId = null;
}
ruleChain.root = false;
return ruleChain;
}
private prepareRuleChainMetaData(ruleChainMetaData: RuleChainMetaData) {
delete ruleChainMetaData.ruleChainId;
for (let i = 0; i < ruleChainMetaData.nodes.length; i++) {
const node = ruleChainMetaData.nodes[i];
delete node.ruleChainId;
ruleChainMetaData.nodes[i] = this.prepareExport(node);
}
return ruleChainMetaData;
}
private validateImportedRuleChain(ruleChainImport: RuleChainImport): boolean {
if (isUndefined(ruleChainImport.ruleChain)
|| isUndefined(ruleChainImport.metadata)
|| isUndefined(ruleChainImport.ruleChain.name)) {
return false;
}
if (isUndefined(ruleChainImport.ruleChain.type)) {
ruleChainImport.ruleChain.type = RuleChainType.CORE;
}
return true;
}
private validateImportedDeviceProfile(deviceProfile: DeviceProfile): boolean {
if (isUndefined(deviceProfile.name)
|| isUndefined(deviceProfile.type)
|| isUndefined(deviceProfile.transportType)
|| isUndefined(deviceProfile.provisionType)
|| isUndefined(deviceProfile.profileData)) {
return false;
}
return true;
}
private validateImportedTenantProfile(tenantProfile: TenantProfile): boolean {
return isDefined(tenantProfile.name)
&& isDefined(tenantProfile.profileData)
&& isDefined(tenantProfile.isolatedTbCore)
&& isDefined(tenantProfile.isolatedTbRuleEngine);
}
private sumObject(obj1: any, obj2: any): any {
Object.keys(obj2).map((key) => {
if (isObject(obj2[key])) {
obj1[key] = obj1[key] || {};
obj1[key] = {...obj1[key], ...this.sumObject(obj1[key], obj2[key])};
} else if (isString(obj2[key])) {
obj1[key] = (obj1[key] || '') + `${obj2[key]}\n`;
} else {
obj1[key] = (obj1[key] || 0) + obj2[key];
}
});
return obj1;
}
private handleExportError(e: any, errorDetailsMessageId: string) {
let message = e;
if (!message) {
message = this.translate.instant('error.unknown-error');
}
this.store.dispatch(new ActionNotificationShow(
{message: this.translate.instant(errorDetailsMessageId, {error: message}),
type: 'error'}));
}
private validateImportedDashboard(dashboard: Dashboard): boolean {
if (isUndefined(dashboard.title) || isUndefined(dashboard.configuration)) {
return false;
}
return true;
}
private validateImportedWidget(widgetItem: WidgetItem): boolean {
if (isUndefined(widgetItem.widget)
|| isUndefined(widgetItem.aliasesInfo)
|| isUndefined(widgetItem.originalColumns)) {
return false;
}
const widget = widgetItem.widget;
if (isUndefined(widget.isSystemType) ||
isUndefined(widget.bundleAlias) ||
isUndefined(widget.typeAlias) ||
isUndefined(widget.type)) {
return false;
}
return true;
}
private validateImportedWidgetTypeDetails(widgetTypeDetails: WidgetTypeDetails): boolean {
if (isUndefined(widgetTypeDetails.name)
|| isUndefined(widgetTypeDetails.descriptor)) {
return false;
}
return true;
}
private validateImportedWidgetsBundle(widgetsBundleItem: WidgetsBundleItem): boolean {
if (isUndefined(widgetsBundleItem.widgetsBundle)) {
return false;
}
if (isUndefined(widgetsBundleItem.widgetTypes)) {
return false;
}
const widgetsBundle = widgetsBundleItem.widgetsBundle;
if (isUndefined(widgetsBundle.title)) {
return false;
}
const widgetTypesDetails = widgetsBundleItem.widgetTypes;
for (const widgetTypeDetails of widgetTypesDetails) {
if (!this.validateImportedWidgetTypeDetails(widgetTypeDetails)) {
return false;
}
}
return true;
}
private saveImportedDashboard(dashboard: Dashboard): Observable<Dashboard> {
return this.dashboardService.saveDashboard(dashboard);
}
private addImportedWidget(dashboard: Dashboard, targetState: string,
targetLayoutFunction: () => Observable<DashboardLayoutId>,
widget: Widget, aliasesInfo: AliasesInfo,
filtersInfo: FiltersInfo,
onAliasesUpdateFunction: () => void,
onFiltersUpdateFunction: () => void,
originalColumns: number, originalSize: WidgetSize): Observable<ImportWidgetResult> {
return targetLayoutFunction().pipe(
mergeMap((targetLayout) => {
return this.itembuffer.addWidgetToDashboard(dashboard, targetState, targetLayout,
widget, aliasesInfo, filtersInfo, onAliasesUpdateFunction, onFiltersUpdateFunction,
originalColumns, originalSize, -1, -1).pipe(
map(() => ({widget, layoutId: targetLayout} as ImportWidgetResult))
);
}
));
}
private processEntityAliases(entityAliases: EntityAliases, aliasIds: string[]): Observable<EntityAliases> {
const tasks: Observable<EntityAlias>[] = [];
for (const aliasId of aliasIds) {
const entityAlias = entityAliases[aliasId];
tasks.push(
this.entityService.checkEntityAlias(entityAlias).pipe(
map((result) => {
if (!result) {
const missingEntityAlias = deepClone(entityAlias);
missingEntityAlias.filter = null;
return missingEntityAlias;
}
return null;
}
)
)
);
}
return forkJoin(tasks).pipe(
map((missingAliasesArray) => {
missingAliasesArray = missingAliasesArray.filter(alias => alias !== null);
const missingEntityAliases: EntityAliases = {};
for (const missingAlias of missingAliasesArray) {
missingEntityAliases[missingAlias.id] = missingAlias;
}
return missingEntityAliases;
}
)
);
}
private editMissingAliases(widgets: Array<Widget>, isSingleWidget: boolean,
customTitle: string, missingEntityAliases: EntityAliases): Observable<EntityAliases> {
return this.dialog.open<EntityAliasesDialogComponent, EntityAliasesDialogData,
EntityAliases>(EntityAliasesDialogComponent, {
disableClose: true,
panelClass: ['tb-dialog', 'tb-fullscreen-dialog'],
data: {
entityAliases: missingEntityAliases,
widgets,
customTitle,
isSingleWidget,
disableAdd: true
}
}).afterClosed().pipe(
map((updatedEntityAliases) => {
if (updatedEntityAliases) {
return updatedEntityAliases;
} else {
throw new Error('Unable to resolve missing entity aliases!');
}
}
));
}
private prepareAliasesInfo(aliasesInfo: AliasesInfo): AliasesInfo {
const datasourceAliases = aliasesInfo.datasourceAliases;
const targetDeviceAliases = aliasesInfo.targetDeviceAliases;
if (datasourceAliases || targetDeviceAliases) {
if (datasourceAliases) {
for (const strIndex of Object.keys(datasourceAliases)) {
const datasourceIndex = Number(strIndex);
datasourceAliases[datasourceIndex] = this.prepareEntityAlias(datasourceAliases[datasourceIndex]);
}
}
if (targetDeviceAliases) {
for (const strIndex of Object.keys(targetDeviceAliases)) {
const datasourceIndex = Number(strIndex);
targetDeviceAliases[datasourceIndex] = this.prepareEntityAlias(targetDeviceAliases[datasourceIndex]);
}
}
}
return aliasesInfo;
}
private prepareEntityAlias(aliasInfo: EntityAliasInfo): EntityAliasInfo {
let alias: string;
let filter: EntityAliasFilter;
if (aliasInfo.deviceId) {
alias = aliasInfo.aliasName;
filter = {
type: AliasFilterType.entityList,
entityType: EntityType.DEVICE,
entityList: [aliasInfo.deviceId],
resolveMultiple: false
};
} else if (aliasInfo.deviceFilter) {
alias = aliasInfo.aliasName;
filter = {
type: aliasInfo.deviceFilter.useFilter ? AliasFilterType.entityName : AliasFilterType.entityList,
entityType: EntityType.DEVICE,
resolveMultiple: false
};
if (filter.type === AliasFilterType.entityList) {
filter.entityList = aliasInfo.deviceFilter.deviceList;
} else {
filter.entityNameFilter = aliasInfo.deviceFilter.deviceNameFilter;
}
} else if (aliasInfo.entityFilter) {
alias = aliasInfo.aliasName;
filter = {
type: aliasInfo.entityFilter.useFilter ? AliasFilterType.entityName : AliasFilterType.entityList,
entityType: aliasInfo.entityType,
resolveMultiple: false
};
if (filter.type === AliasFilterType.entityList) {
filter.entityList = aliasInfo.entityFilter.entityList;
} else {
filter.entityNameFilter = aliasInfo.entityFilter.entityNameFilter;
}
} else {
alias = aliasInfo.alias;
filter = aliasInfo.filter;
}
return {
alias,
filter
};
}
private openImportDialog(importTitle: string, importFileLabel: string): Observable<any> {
return this.dialog.open<ImportDialogComponent, ImportDialogData,
any>(ImportDialogComponent, {
disableClose: true,
panelClass: ['tb-dialog', 'tb-fullscreen-dialog'],
data: {
importTitle,
importFileLabel
}
}).afterClosed().pipe(
map((importedData) => {
if (importedData) {
return importedData;
} else {
throw new Error('No file selected!');
}
}
));
}
private exportToPc(data: any, filename: string) {
if (!data) {
console.error('No data');
return;
}
this.exportJson(data, filename);
}
private exportJson(data: any, filename: string) {
if (isObject(data)) {
data = JSON.stringify(data, null, 2);
}
this.downloadFile(data, filename, JSON_TYPE);
}
private downloadFile(data: any, filename: string, fileType: FileType) {
if (!filename) {
filename = 'download';
}
filename += '.' + fileType.extension;
const blob = new Blob([data], {type: fileType.mimeType});
if (this.window.navigator && this.window.navigator.msSaveOrOpenBlob) {
this.window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const e = this.document.createEvent('MouseEvents');
const a = this.document.createElement('a');
a.download = filename;
a.href = URL.createObjectURL(blob);
a.dataset.downloadurl = [fileType.mimeType, a.download, a.href].join(':');
// @ts-ignore
e.initEvent('click', true, false, this.window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
}
private prepareDashboardExport(dashboard: Dashboard): Dashboard {
dashboard = this.prepareExport(dashboard);
delete dashboard.assignedCustomers;
return dashboard;
}
private prepareProfileExport<T extends DeviceProfile|TenantProfile>(profile: T): T {
profile = this.prepareExport(profile);
profile.default = false;
return profile;
}
private prepareExport(data: any): any {
const exportedData = deepClone(data);
if (isDefined(exportedData.id)) {
delete exportedData.id;
}
if (isDefined(exportedData.createdTime)) {
delete exportedData.createdTime;
}
if (isDefined(exportedData.tenantId)) {
delete exportedData.tenantId;
}
if (isDefined(exportedData.customerId)) {
delete exportedData.customerId;
}
return exportedData;
}
} | the_stack |
import {
createState,
PluginClient,
usePlugin,
useValue,
Panel,
theme,
Layout,
DetailSidebar,
DataTable,
DataTableColumn,
Toolbar,
} from 'flipper-plugin';
import adb from 'adbkit';
import TemperatureTable from './TemperatureTable';
import {Button, Typography, Switch} from 'antd';
import {PlayCircleOutlined, PauseCircleOutlined} from '@ant-design/icons';
import React, {useCallback, useState} from 'react';
// we keep vairable name with underline for to physical path mappings on device
type CPUFrequency = {
[index: string]: number | Array<number> | string | Array<string>;
cpu_id: number;
scaling_cur_freq: number;
scaling_min_freq: number;
scaling_max_freq: number;
scaling_available_freqs: Array<number>;
scaling_governor: string;
scaling_available_governors: Array<string>;
cpuinfo_max_freq: number;
cpuinfo_min_freq: number;
};
type CPUState = {
cpuFreq: Array<CPUFrequency>;
cpuCount: number;
monitoring: boolean;
hardwareInfo: string;
temperatureMap: any;
thermalAccessible: boolean;
displayThermalInfo: boolean;
displayCPUDetail: boolean;
};
// check if str is a number
function isNormalInteger(str: string) {
const n = Math.floor(Number(str));
return String(n) === str && n >= 0;
}
// format frequency to MHz, GHz
function formatFrequency(freq: number) {
if (freq == -1) {
return 'N/A';
} else if (freq == -2) {
return 'off';
} else if (freq > 1000 * 1000) {
return (freq / 1000 / 1000).toFixed(2) + ' GHz';
} else {
return freq / 1000 + ' MHz';
}
}
export function devicePlugin(client: PluginClient<{}, {}>) {
const device = client.device;
const executeShell = async (command: string) => device.executeShell(command);
let intervalID: NodeJS.Timer | null = null;
const cpuState = createState<CPUState>({
cpuCount: 0,
cpuFreq: [],
monitoring: false,
hardwareInfo: '',
temperatureMap: {},
thermalAccessible: true,
displayThermalInfo: false,
displayCPUDetail: true,
});
const updateCoreFrequency: (core: number, type: string) => Promise<void> =
async (core: number, type: string) => {
const output = await executeShell(
'cat /sys/devices/system/cpu/cpu' + core + '/cpufreq/' + type,
);
cpuState.update((draft) => {
const newFreq = isNormalInteger(output) ? parseInt(output, 10) : -1;
// update table only if frequency changed
if (draft.cpuFreq[core][type] != newFreq) {
draft.cpuFreq[core][type] = newFreq;
if (type == 'scaling_cur_freq' && draft.cpuFreq[core][type] < 0) {
// cannot find current freq means offline
draft.cpuFreq[core][type] = -2;
}
}
});
};
const updateAvailableFrequencies: (core: number) => Promise<void> = async (
core: number,
) => {
const output = await executeShell(
'cat /sys/devices/system/cpu/cpu' +
core +
'/cpufreq/scaling_available_frequencies',
);
cpuState.update((draft) => {
const freqs = output.split(' ').map((num: string) => {
return parseInt(num, 10);
});
draft.cpuFreq[core].scaling_available_freqs = freqs;
const maxFreq = draft.cpuFreq[core].scaling_max_freq;
if (maxFreq > 0 && freqs.indexOf(maxFreq) == -1) {
freqs.push(maxFreq); // always add scaling max to available frequencies
}
});
};
const updateCoreGovernor: (core: number) => Promise<void> = async (
core: number,
) => {
const output = await executeShell(
'cat /sys/devices/system/cpu/cpu' + core + '/cpufreq/scaling_governor',
);
cpuState.update((draft) => {
if (output.toLowerCase().includes('no such file')) {
draft.cpuFreq[core].scaling_governor = 'N/A';
} else {
draft.cpuFreq[core].scaling_governor = output;
}
});
};
const readAvailableGovernors: (core: number) => Promise<string[]> = async (
core: number,
) => {
const output = await executeShell(
'cat /sys/devices/system/cpu/cpu' +
core +
'/cpufreq/scaling_available_governors',
);
return output.split(' ');
};
const readCoreFrequency = async (core: number) => {
const freq = cpuState.get().cpuFreq[core];
const promises = [];
if (freq.cpuinfo_max_freq < 0) {
promises.push(updateCoreFrequency(core, 'cpuinfo_max_freq'));
}
if (freq.cpuinfo_min_freq < 0) {
promises.push(updateCoreFrequency(core, 'cpuinfo_min_freq'));
}
promises.push(updateCoreFrequency(core, 'scaling_cur_freq'));
promises.push(updateCoreFrequency(core, 'scaling_min_freq'));
promises.push(updateCoreFrequency(core, 'scaling_max_freq'));
return Promise.all(promises).then(() => {});
};
const updateHardwareInfo = async () => {
const output = await executeShell('getprop ro.board.platform');
let hwInfo = '';
if (
output.startsWith('msm') ||
output.startsWith('apq') ||
output.startsWith('sdm')
) {
hwInfo = 'QUALCOMM ' + output.toUpperCase();
} else if (output.startsWith('exynos')) {
const chipname = await executeShell('getprop ro.chipname');
if (chipname != null) {
cpuState.update((draft) => {
draft.hardwareInfo = 'SAMSUMG ' + chipname.toUpperCase();
});
}
return;
} else if (output.startsWith('mt')) {
hwInfo = 'MEDIATEK ' + output.toUpperCase();
} else if (output.startsWith('sc')) {
hwInfo = 'SPREADTRUM ' + output.toUpperCase();
} else if (output.startsWith('hi') || output.startsWith('kirin')) {
hwInfo = 'HISILICON ' + output.toUpperCase();
} else if (output.startsWith('rk')) {
hwInfo = 'ROCKCHIP ' + output.toUpperCase();
} else if (output.startsWith('bcm')) {
hwInfo = 'BROADCOM ' + output.toUpperCase();
}
cpuState.update((draft) => {
draft.hardwareInfo = hwInfo;
});
};
const readThermalZones = async () => {
const thermal_dir = '/sys/class/thermal/';
const map = {};
const output = await executeShell('ls ' + thermal_dir);
if (output.toLowerCase().includes('permission denied')) {
cpuState.update((draft) => {
draft.thermalAccessible = false;
});
return;
}
const dirs = output.split(/\s/);
const promises = [];
for (let d of dirs) {
d = d.trim();
if (d.length == 0) {
continue;
}
const path = thermal_dir + d;
promises.push(readThermalZone(path, d, map));
}
await Promise.all(promises);
cpuState.update((draft) => {
draft.temperatureMap = map;
draft.thermalAccessible = true;
});
if (cpuState.get().displayThermalInfo) {
setTimeout(readThermalZones, 1000);
}
};
const readThermalZone = async (path: string, dir: string, map: any) => {
const type = await executeShell('cat ' + path + '/type');
if (type.length == 0) {
return;
}
const temp = await executeShell('cat ' + path + '/temp');
if (Number.isNaN(Number(temp))) {
return;
}
map[type] = {
path: dir,
temp: parseInt(temp, 10),
};
};
const onStartMonitor = () => {
if (cpuState.get().monitoring) {
return;
}
cpuState.update((draft) => {
draft.monitoring = true;
});
for (let i = 0; i < cpuState.get().cpuCount; ++i) {
readAvailableGovernors(i)
.then((output) => {
cpuState.update((draft) => {
draft.cpuFreq[i].scaling_available_governors = output;
});
})
.catch((e) => {
console.error('Failed to read CPU governors:', e);
});
}
const update = async () => {
if (!cpuState.get().monitoring) {
return;
}
const promises = [];
for (let i = 0; i < cpuState.get().cpuCount; ++i) {
promises.push(readCoreFrequency(i));
promises.push(updateCoreGovernor(i));
promises.push(updateAvailableFrequencies(i)); // scaling max might change, so we also update this
}
await Promise.all(promises);
intervalID = setTimeout(update, 500);
};
intervalID = setTimeout(update, 500);
};
const onStopMonitor = () => {
intervalID && clearInterval(intervalID);
intervalID = null;
cpuState.update((draft) => {
draft.monitoring = false;
});
};
const cleanup = () => {
onStopMonitor();
cpuState.update((draft) => {
for (let i = 0; i < draft.cpuCount; ++i) {
draft.cpuFreq[i].scaling_cur_freq = -1;
draft.cpuFreq[i].scaling_min_freq = -1;
draft.cpuFreq[i].scaling_max_freq = -1;
draft.cpuFreq[i].scaling_available_freqs = [];
draft.cpuFreq[i].scaling_governor = 'N/A';
// we don't cleanup cpuinfo_min_freq, cpuinfo_max_freq
// because usually they are fixed (hardware)
}
});
};
const toggleThermalSidebar = () => {
if (!cpuState.get().displayThermalInfo) {
readThermalZones();
}
cpuState.update((draft) => {
draft.displayThermalInfo = !draft.displayThermalInfo;
draft.displayCPUDetail = false;
});
};
const toggleCPUSidebar = () => {
cpuState.update((draft) => {
draft.displayCPUDetail = !draft.displayCPUDetail;
draft.displayThermalInfo = false;
});
};
// check how many cores we have on this device
executeShell('cat /sys/devices/system/cpu/possible')
.then((output) => {
const idx = output.indexOf('-');
const cpuFreq = [];
const count = parseInt(output.substring(idx + 1), 10) + 1;
for (let i = 0; i < count; ++i) {
cpuFreq[i] = {
cpu_id: i,
scaling_cur_freq: -1,
scaling_min_freq: -1,
scaling_max_freq: -1,
cpuinfo_min_freq: -1,
cpuinfo_max_freq: -1,
scaling_available_freqs: [],
scaling_governor: 'N/A',
scaling_available_governors: [],
};
}
cpuState.set({
cpuCount: count,
cpuFreq: cpuFreq,
monitoring: false,
hardwareInfo: '',
temperatureMap: {},
thermalAccessible: true,
displayThermalInfo: false,
displayCPUDetail: true,
});
})
.catch((e) => {
console.error('Failed to read CPU cores:', e);
});
client.onDeactivate(() => cleanup());
client.onActivate(() => {
updateHardwareInfo();
readThermalZones();
});
return {
executeShell,
cpuState,
onStartMonitor,
onStopMonitor,
toggleCPUSidebar,
toggleThermalSidebar,
};
}
const columns: DataTableColumn[] = [
{key: 'cpu_id', title: 'CPU ID'},
{key: 'scaling_cur_freq', title: 'Current Frequency'},
{key: 'scaling_min_freq', title: 'Scaling min'},
{key: 'scaling_max_freq', title: 'Scaling max'},
{key: 'cpuinfo_min_freq', title: 'CPU min'},
{key: 'cpuinfo_max_freq', title: 'CPU max'},
{key: 'scaling_governor', title: 'Scaling governor'},
];
const cpuSidebarColumns: DataTableColumn[] = [
{
key: 'key',
title: 'key',
wrap: true,
},
{
key: 'value',
title: 'value',
wrap: true,
},
];
export function Component() {
const instance = usePlugin(devicePlugin);
const {
onStartMonitor,
onStopMonitor,
toggleCPUSidebar,
toggleThermalSidebar,
} = instance;
const cpuState = useValue(instance.cpuState);
const [selectedIds, setSelectedIds] = useState<number[]>([]);
const sidebarRows = (id: number) => {
let availableFreqTitle = 'Scaling Available Frequencies';
const selected = cpuState.cpuFreq[id];
if (selected.scaling_available_freqs.length > 0) {
availableFreqTitle +=
' (' + selected.scaling_available_freqs.length.toString() + ')';
}
const keys = [availableFreqTitle, 'Scaling Available Governors'];
const vals = [
buildAvailableFreqList(selected),
buildAvailableGovList(selected),
];
return keys.map<any>((key, idx) => {
return buildSidebarRow(key, vals[idx]);
});
};
const renderCPUSidebar = () => {
if (!cpuState.displayCPUDetail || selectedIds.length == 0) {
return null;
}
const id = selectedIds[0];
return (
<DetailSidebar width={500}>
<Layout.Container pad>
<Typography.Title>CPU Details: CPU_{id}</Typography.Title>
<DataTable
records={sidebarRows(id)}
columns={cpuSidebarColumns}
scrollable={false}
enableSearchbar={false}
/>
</Layout.Container>
</DetailSidebar>
);
};
const renderThermalSidebar = () => {
if (!cpuState.displayThermalInfo) {
return null;
}
return (
<DetailSidebar width={500}>
<Panel
pad={theme.space.small}
title="Thermal Information"
collapsible={false}>
{cpuState.thermalAccessible ? (
<TemperatureTable temperatureMap={cpuState.temperatureMap} />
) : (
'Temperature information not accessible on this device.'
)}
</Panel>
</DetailSidebar>
);
};
const setSelected = useCallback((selected: any) => {
setSelectedIds(selected ? [selected.core] : []);
}, []);
return (
<Layout.Container pad>
<Typography.Title>CPU Info</Typography.Title>
<Toolbar>
{cpuState.monitoring ? (
<Button onClick={onStopMonitor} icon={<PauseCircleOutlined />}>
Pause
</Button>
) : (
<Button onClick={onStartMonitor} icon={<PlayCircleOutlined />}>
Start
</Button>
)}
{cpuState.hardwareInfo}
<Switch
checked={cpuState.displayThermalInfo}
onClick={toggleThermalSidebar}
/>
Thermal Information
<Switch
onClick={toggleCPUSidebar}
checked={cpuState.displayCPUDetail}
/>
CPU Details
{cpuState.displayCPUDetail &&
selectedIds.length == 0 &&
' (Please select a core in the table below)'}
</Toolbar>
<DataTable
records={frequencyRows(cpuState.cpuFreq)}
columns={columns}
scrollable={false}
onSelect={setSelected}
onRowStyle={getRowStyle}
enableSearchbar={false}
/>
{renderCPUSidebar()}
{renderThermalSidebar()}
</Layout.Container>
);
}
function buildAvailableGovList(freq: CPUFrequency): string {
if (freq.scaling_available_governors.length == 0) {
return 'N/A';
}
return freq.scaling_available_governors.join(', ');
}
function buildSidebarRow(key: string, val: any) {
return {
key: key,
value: val,
};
}
function buildRow(freq: CPUFrequency) {
return {
core: freq.cpu_id,
cpu_id: `CPU_${freq.cpu_id}`,
scaling_cur_freq: formatFrequency(freq.scaling_cur_freq),
scaling_min_freq: formatFrequency(freq.scaling_min_freq),
scaling_max_freq: formatFrequency(freq.scaling_max_freq),
cpuinfo_min_freq: formatFrequency(freq.cpuinfo_min_freq),
cpuinfo_max_freq: formatFrequency(freq.cpuinfo_max_freq),
scaling_governor: freq.scaling_governor,
};
}
function frequencyRows(cpuFreqs: Array<CPUFrequency>) {
return cpuFreqs.map(buildRow);
}
function getRowStyle(freq: CPUFrequency) {
if (freq.scaling_cur_freq == -2) {
return {
backgroundColor: theme.backgroundWash,
color: theme.textColorPrimary,
fontWeight: 700,
};
} else if (
freq.scaling_min_freq != freq.cpuinfo_min_freq &&
freq.scaling_min_freq > 0 &&
freq.cpuinfo_min_freq > 0
) {
return {
backgroundColor: theme.warningColor,
color: theme.textColorPrimary,
fontWeight: 700,
};
} else if (
freq.scaling_max_freq != freq.cpuinfo_max_freq &&
freq.scaling_max_freq > 0 &&
freq.cpuinfo_max_freq > 0
) {
return {
backgroundColor: theme.backgroundWash,
color: theme.textColorSecondary,
fontWeight: 700,
};
}
}
function buildAvailableFreqList(freq: CPUFrequency) {
if (freq.scaling_available_freqs.length == 0) {
return <Typography.Text>N/A</Typography.Text>;
}
const info = freq;
return (
<Typography.Text>
{freq.scaling_available_freqs.map((freq, idx) => {
const bold =
freq == info.scaling_cur_freq ||
freq == info.scaling_min_freq ||
freq == info.scaling_max_freq;
return (
<Typography.Text key={idx} strong={bold}>
{formatFrequency(freq)}
{freq == info.scaling_cur_freq && (
<Typography.Text strong={bold}>
{' '}
(scaling current)
</Typography.Text>
)}
{freq == info.scaling_min_freq && (
<Typography.Text strong={bold}> (scaling min)</Typography.Text>
)}
{freq == info.scaling_max_freq && (
<Typography.Text strong={bold}> (scaling max)</Typography.Text>
)}
<br />
</Typography.Text>
);
})}
</Typography.Text>
);
} | the_stack |
import { createInstance, isUndefined, merge, extend, getValue } from './util';
/**
* Interface for Class Object
*/
interface ClassObject {
properties: Object & { [key: string]: Object };
setProperties: (arg: Object, muteOnChange?: boolean) => void;
}
/**
* Interface for Parent Options
*/
interface ParentOption {
context: EventListener;
prefix?: string;
}
/**
* Interface for Event Listener
*/
interface EventListener {
addEventListener: Function;
removeEventListener: Function;
}
/**
* Interface for builder options.
*/
interface BuildInfo {
/**
* Specifies the builder object used for component builder.
*/
builderObject: { [key: string]: Object };
props?: string[];
events?: string[];
propList: {
props: PropertyCollectionInfo[],
complexProps: PropertyCollectionInfo[],
colProps: PropertyCollectionInfo[],
events: PropertyCollectionInfo[],
propNames: PropertyCollectionInfo[],
complexPropNames: PropertyCollectionInfo[],
colPropNames: PropertyCollectionInfo[],
eventNames: PropertyCollectionInfo[]
};
}
/**
* Interface for property collection options.
*/
interface PropertyCollectionInfo {
/**
* Specifies name of the property
*/
propertyName: string;
/**
* Specifies type of the property
*/
propertyType: string;
type: FunctionConstructor | Object;
/**
* Specifies the default value
*/
defaultValue: Object;
/**
* Specifies if the property is complex.
*/
isComplex: boolean;
}
/**
* Interface for child builder options.
*/
interface ChildInfo {
/**
* Specifies the child properties.
*/
properties?: { [key: string]: Object };
/**
* Specifies whether the property value is array type.
*/
isPropertyArray?: boolean;
/**
* Specifies whether the array collection of the values.
*/
propCollections?: Object[];
[key: string]: Object;
}
/**
* Returns the Class Object
*
* @param {ClassObject} instance - instance of ClassObject
* @param {string} curKey - key of the current instance
* @param {Object} defaultValue - default Value
* @param {Object[]} type ?
* @returns {ClassObject} ?
*/
// eslint-disable-next-line
function getObject<T>(instance: ClassObject & Object, curKey: string, defaultValue: Object, type:
(...arg: Object[]) => void): ClassObject {
// eslint-disable-next-line
if (!instance.properties.hasOwnProperty(curKey) || !(instance.properties[curKey] instanceof type)) {
instance.properties[curKey] = createInstance(type, [instance, curKey, defaultValue]);
}
return <ClassObject>instance.properties[curKey];
}
/**
* Returns object array
*
* @param {ClassObject} instance ?
* @param {string} curKey ?
* @param {Object[]} defaultValue ?
* @param {Object} type ?
* @param {boolean} isSetter ?
* @param {boolean} isFactory ?
* @returns {Object[]} ?
*/
// eslint-disable-next-line
function getObjectArray<T>(
instance: ClassObject & Object,
curKey: string,
defaultValue: Object[],
type: (...arg: Object[]) => Object,
isSetter?: boolean,
isFactory?: boolean
): Object[] {
const result: Object[] = [];
const len: number = defaultValue ? defaultValue.length : 0;
for (let i: number = 0; i < len; i++) {
let curType: (...arg: Object[]) => void = type;
if (isFactory) {
curType = <(...arg: Object[]) => void>type(defaultValue[i], instance);
}
if (isSetter) {
const inst: ClassObject = createInstance(curType, [instance, curKey, {}, true]);
inst.setProperties(defaultValue[i], true);
result.push(inst);
} else {
result.push(createInstance(curType, [instance, curKey, defaultValue[i], false]));
}
}
return result;
}
/**
* Returns the properties of the object
*
* @param {Object} defaultValue ?
* @param {string} curKey ?
* @returns {void} ?
*/
function propertyGetter(defaultValue: Object, curKey: string): () => void {
return function (): Object {
// eslint-disable-next-line
if (!this.properties.hasOwnProperty(curKey)) {
this.properties[curKey] = defaultValue;
}
return this.properties[curKey];
};
}
/**
* Set the properties for the object
*
* @param {Object} defaultValue ?
* @param {string} curKey ?
* @returns {void} ?
*/
function propertySetter(defaultValue: Object, curKey: string): (arg: Object) => void {
return function (newValue: Object): void {
if (this.properties[curKey] !== newValue) {
// eslint-disable-next-line
let oldVal: Object = this.properties.hasOwnProperty(curKey) ? this.properties[curKey] : defaultValue;
this.saveChanges(curKey, newValue, oldVal);
this.properties[curKey] = newValue;
}
};
}
/**
* Returns complex objects
*
* @param {Object} defaultValue ?
* @param {string} curKey ?
* @param {Object[]} type ?
* @returns {void} ?
*/
// eslint-disable-next-line
function complexGetter<T>(defaultValue: Object, curKey: string, type: (...arg: Object[]) => void): () => void {
return function (): Object {
return getObject(this, curKey, defaultValue, type);
};
}
/**
* Sets complex objects
*
* @param {Object} defaultValue ?
* @param {string} curKey ?
* @param {Object[]} type ?
* @returns {void} ?
*/
function complexSetter(defaultValue: Object, curKey: string, type: (...arg: Object[]) => void): (arg: Object) => void {
return function (newValue: Object): void {
getObject(this, curKey, defaultValue, type).setProperties(newValue);
};
}
/**
*
* @param {Object} defaultValue ?
* @param {string} curKey ?
* @param {FunctionConstructor} type ?
* @returns {void} ?
*/
// eslint-disable-next-line
function complexFactoryGetter<T>(defaultValue: Object, curKey: string, type: FunctionConstructor): () => void {
return function (): Object {
const curType: Function = (<(arg: Object) => Function>type)({});
// eslint-disable-next-line
if (this.properties.hasOwnProperty(curKey)) {
return this.properties[curKey];
} else {
return getObject(this, curKey, defaultValue, <FunctionConstructor>curType);
}
};
}
/**
*
* @param {Object} defaultValue ?
* @param {string} curKey ?
* @param {Object[]} type ?
* @returns {void} ?
*/
function complexFactorySetter(
defaultValue: Object,
curKey: string,
type: (...arg: Object[]) => Object): (arg: Object) => void {
return function (newValue: Object): void {
const curType: (...arg: Object[]) => void = <(...arg: Object[]) => void>type(newValue, this);
getObject(this, curKey, defaultValue, curType).setProperties(newValue);
};
}
/**
*
* @param {Object[]} defaultValue ?
* @param {string} curKey ?
* @param {Object[]} type ?
* @returns {void} ?
*/
function complexArrayGetter(defaultValue: Object[], curKey: string, type: (...arg: Object[]) => object): () => void {
return function (): Object[] {
// eslint-disable-next-line
if (!this.properties.hasOwnProperty(curKey)) {
const defCollection: Object[] = getObjectArray(this, curKey, defaultValue, type, false);
this.properties[curKey] = defCollection;
}
const ignore: boolean = ((this.controlParent !== undefined && this.controlParent.ignoreCollectionWatch)
|| this.ignoreCollectionWatch);
// eslint-disable-next-line
if (!this.properties[curKey].hasOwnProperty('push') && !ignore) {
['push', 'pop'].forEach((extendFunc: string) => {
const descriptor: PropertyDescriptor = {
value: complexArrayDefinedCallback(extendFunc, curKey, type, this.properties[curKey]).bind(this),
configurable: true
};
Object.defineProperty(this.properties[curKey], extendFunc, descriptor);
});
}
// eslint-disable-next-line
if (!this.properties[curKey].hasOwnProperty('isComplexArray')) {
Object.defineProperty(this.properties[curKey], 'isComplexArray', { value: true });
}
return this.properties[curKey];
};
}
/**
*
* @param {Object[]} defaultValue ?
* @param {string} curKey ?
* @param {Object[]} type ?
* @returns {void} ?
*/
function complexArraySetter(defaultValue: Object[], curKey: string, type: (...arg: Object[]) => object): (arg: Object) => void {
return function (newValue: Object[]): void {
this.isComplexArraySetter = true;
const oldValueCollection: Object[] = getObjectArray(this, curKey, defaultValue, type, false);
const newValCollection: Object[] = getObjectArray(this, curKey, newValue, type, true);
this.isComplexArraySetter = false;
this.saveChanges(curKey, newValCollection, oldValueCollection);
this.properties[curKey] = newValCollection;
};
}
/**
*
* @param {Object[]} defaultValue ?
* @param {string} curKey ?
* @param {Object[]} type ?
* @returns {void} ?
*/
function complexArrayFactorySetter(
defaultValue: Object[],
curKey: string,
type: (...arg: Object[]) => void): (arg: Object) => void {
return function (newValue: Object[]): void {
// eslint-disable-next-line
const oldValueCollection: Object[] = this.properties.hasOwnProperty(curKey) ? this.properties[curKey] : defaultValue;
const newValCollection: Object[] = getObjectArray(this, curKey, newValue, <(...arg: Object[]) => object>type, true, true);
this.saveChanges(curKey, newValCollection, oldValueCollection);
this.properties[curKey] = newValCollection;
};
}
/**
*
* @param {Object[]} defaultValue ?
* @param {string} curKey ?
* @param {FunctionConstructor} type ?
* @returns {void} ?
*/
function complexArrayFactoryGetter(
defaultValue: Object[],
curKey: string,
type: FunctionConstructor
): () => void {
return function (): Object[] {
const curType: Function = (<(arg: Object) => Function>type)({});
// eslint-disable-next-line
if (!this.properties.hasOwnProperty(curKey)) {
const defCollection: Object[] = getObjectArray(this, curKey, defaultValue, <FunctionConstructor>curType, false);
this.properties[curKey] = defCollection;
}
return this.properties[curKey];
};
}
/**
*
* @param {string} dFunc ?
* @param {string} curKey ?
* @param {Object} type ?
* @param {Object} prop ?
* @returns {Object} ?
*/
function complexArrayDefinedCallback(
dFunc: string, curKey: string, type: (...arg: Object[]) => object, prop: Object[]): (arg: Object) => Object[] {
/* tslint:disable no-function-expression */
return function (...newValue: Object[]): Object[] {
const keyString: string = this.propName ? this.getParentKey() + '.' + curKey + '-' : curKey + '-';
switch (dFunc) {
case 'push':
for (let i: number = 0; i < newValue.length; i++) {
Array.prototype[dFunc].apply(prop, [newValue[i]]);
const model: Object = getArrayModel(keyString + (prop.length - 1), newValue[i], !this.controlParent, dFunc);
this.serverDataBind(model, newValue[i], false, dFunc);
}
break;
case 'pop':
Array.prototype[dFunc].apply(prop);
// eslint-disable-next-line
let model: Object = getArrayModel(keyString + prop.length, null, !this.controlParent, dFunc);
this.serverDataBind(model, { ejsAction: 'pop' }, false, dFunc);
break;
}
return prop;
};
}
/**
*
* @param {string} keyString ?
* @param {Object} value ?
* @param {boolean} isControlParent ?
* @param {string} arrayFunction ?
* @returns {Object} ?
*/
function getArrayModel(keyString: string, value: Object, isControlParent: boolean, arrayFunction: string): Object {
let modelObject: Object = keyString;
if (isControlParent) {
modelObject = {};
modelObject[keyString] = value;
if (value && typeof value === 'object') {
const action: string = 'ejsAction';
modelObject[keyString][action] = arrayFunction;
}
}
return modelObject;
}
// eslint-disable-next-line
/**
* Method used to create property. General syntax below.
*
* @param {Object} defaultValue - Specifies the default value of property.
* @returns {PropertyDecorator} ?
* ```
* @Property('TypeScript')
* propertyName: Type;
* ```
* @private
*/
export function Property<T>(defaultValue?: T | Object): PropertyDecorator {
return (target: Object, key: string) => {
const propertyDescriptor: Object = {
set: propertySetter(defaultValue, key),
get: propertyGetter(defaultValue, key),
enumerable: true,
configurable: true
};
//new property creation
Object.defineProperty(target, key, propertyDescriptor);
addPropertyCollection(<BuildInfo>target, key, 'prop', defaultValue);
};
}
/**
* Method used to create complex property. General syntax below.
*
* @param {any} defaultValue - Specifies the default value of property.
* @param {Function} type - Specifies the class type of complex object.
* @returns {PropertyDecorator} ?
* ```
* @Complex<Type>({},Type)
* propertyName: Type;
* ```
* @private
*/
export function Complex<T>(defaultValue: T, type: Function): PropertyDecorator {
return (target: Object, key: string) => {
const propertyDescriptor: Object = {
set: complexSetter(defaultValue, key, <FunctionConstructor>type),
get: complexGetter(defaultValue, key, <FunctionConstructor>type),
enumerable: true,
configurable: true
};
//new property creation
Object.defineProperty(target, key, propertyDescriptor);
addPropertyCollection(<BuildInfo>target, key, 'complexProp', defaultValue, <Function>type);
};
}
/**
* Method used to create complex Factory property. General syntax below.
*
* @param {Function} type - Specifies the class factory type of complex object.
* @returns {PropertyDecorator} ?
* ```
* @ComplexFactory(defaultType, factoryFunction)
* propertyName: Type1 | Type2;
* ```
* @private
*/
export function ComplexFactory(type: Function): PropertyDecorator {
return (target: Object, key: string) => {
const propertyDescriptor: Object = {
set: complexFactorySetter({}, key, <FunctionConstructor>type),
get: complexFactoryGetter({}, key, <FunctionConstructor>type),
enumerable: true,
configurable: true
};
//new property creation
Object.defineProperty(target, key, propertyDescriptor);
addPropertyCollection(<BuildInfo>target, key, 'complexProp', {}, <Function>type);
};
}
/**
* Method used to create complex array property. General syntax below.
*
* @param {any} defaultValue - Specifies the default value of property.
* @param {Function} type - Specifies the class type of complex object.
* @returns {PropertyDecorator} ?
* ```
* @Collection([], Type);
* propertyName: Type;
* ```
* @private
*/
export function Collection<T>(defaultValue: T[], type: Function): PropertyDecorator {
return (target: Object, key: string) => {
const propertyDescriptor: Object = {
set: complexArraySetter(defaultValue, key, <FunctionConstructor>type),
get: complexArrayGetter(defaultValue, key, <FunctionConstructor>type),
enumerable: true,
configurable: true
};
//new property creation
Object.defineProperty(target, key, propertyDescriptor);
addPropertyCollection(<BuildInfo>target, key, 'colProp', defaultValue, <Function>type);
};
}
/**
* Method used to create complex factory array property. General syntax below.
*
* @param {Function} type - Specifies the class type of complex object.
* @returns {PropertyCollectionInfo} ?
* ```
* @Collection([], Type);
* propertyName: Type;
* ```
* @private
*/
export function CollectionFactory(type: Function): PropertyDecorator {
return (target: Object, key: string) => {
const propertyDescriptor: Object = {
set: complexArrayFactorySetter([], key, <FunctionConstructor>type),
get: complexArrayFactoryGetter([], key, <FunctionConstructor>type),
enumerable: true,
configurable: true
};
//new property creation
Object.defineProperty(target, key, propertyDescriptor);
addPropertyCollection(<BuildInfo>target, key, 'colProp', {}, <Function>type);
};
}
/**
* Method used to create event property. General syntax below.
*
* @returns {PropertyDecorator} ?
* ```
* @Event(()=>{return true;})
* ```
* @private
*/
export function Event(): PropertyDecorator {
return (target: Object, key: string) => {
const eventDescriptor: Object = {
set: function (newValue: Function): void {
const oldValue: Function = this.properties[key];
if (oldValue !== newValue) {
const finalContext: ParentOption = getParentContext(this, key);
if (isUndefined(oldValue) === false) {
finalContext.context.removeEventListener(finalContext.prefix, oldValue);
}
finalContext.context.addEventListener(finalContext.prefix, newValue);
this.properties[key] = newValue;
}
},
get: propertyGetter(undefined, key),
enumerable: true,
configurable: true
};
Object.defineProperty(target, key, eventDescriptor);
addPropertyCollection(<BuildInfo>target, key, 'event');
};
}
/**
* NotifyPropertyChanges is triggers the call back when the property has been changed.
*
* @param {Function} classConstructor ?
* @returns {void} ?
* ```
* @NotifyPropertyChanges
* class DemoClass implements INotifyPropertyChanged {
*
* @Property()
* property1: string;
*
* dataBind: () => void;
*
* constructor() { }
*
* onPropertyChanged(newProp: any, oldProp: any) {
* // Called when property changed
* }
* }
* ```
* @private
*/
// eslint-disable-next-line
export function NotifyPropertyChanges(classConstructor: Function): void {
/** Need to code */
}
/**
* Method used to create the builderObject for the target component.
*
* @param {BuildInfo} target ?
* @param {string} key ?
* @param {string} propertyType ?
* @param {Object} defaultValue ?
* @param {Function} type ?
* @returns {void} ?
* @private
*/
function addPropertyCollection<T>(
target: BuildInfo, key: string, propertyType: string, defaultValue?: Object,
type?: T & Function): void {
if (isUndefined(target.propList)) {
target.propList = {
props: [],
complexProps: [],
colProps: [],
events: [],
propNames: [],
complexPropNames: [],
colPropNames: [],
eventNames: []
};
}
// eslint-disable-next-line
(<any>target).propList[propertyType + 's'].push({
propertyName: key,
defaultValue: defaultValue,
type: type
});
// eslint-disable-next-line
(<any>target).propList[propertyType + 'Names'].push(key);
}
/**
* Returns an object containing the builder properties
*
* @param {Function} component ?
* @returns {Object} ?
* @private
*/
function getBuilderProperties(component: Function): Object {
if (isUndefined(component.prototype.builderObject)) {
component.prototype.builderObject = {
properties: {}, propCollections: [], add: function (): void {
this.isPropertyArray = true;
this.propCollections.push(extend({}, this.properties, {}));
}
};
const rex: RegExp = /complex/;
for (const key of Object.keys(component.prototype.propList)) {
for (const prop of component.prototype.propList[key]) {
if (rex.test(key)) {
component.prototype.builderObject[prop.propertyName] = function (value: Function): Object {
const childType: ChildInfo = {};
merge(childType, getBuilderProperties(prop.type));
value(childType);
let tempValue: Object;
if (!childType.isPropertyArray) {
tempValue = extend({}, childType.properties, {});
} else {
tempValue = childType.propCollections;
}
this.properties[prop.propertyName] = tempValue;
childType.properties = {};
childType.propCollections = [];
childType.isPropertyArray = false;
return this;
};
} else {
component.prototype.builderObject[prop.propertyName] = function (value: Object): Object {
this.properties[prop.propertyName] = value;
return this;
};
}
}
}
}
return component.prototype.builderObject;
}
/**
* Interface to notify the changed properties
*/
export interface INotifyPropertyChanged {
onPropertyChanged(newProperties: Object, oldProperties?: Object): void;
}
/**
* Method used to create builder for the components
*
* @param {any} component -specifies the target component for which builder to be created.
* @returns {Object} ?
* @private
*/
export function CreateBuilder<T>(component: T): Object {
const builderFunction: Function = function (element: string | HTMLElement | HTMLInputElement | HTMLButtonElement): void {
this.element = element;
return this;
};
const instanceFunction: Function = (element: string | HTMLElement | HTMLInputElement | HTMLButtonElement): Object => {
// eslint-disable-next-line
if (!builderFunction.prototype.hasOwnProperty('create')) {
builderFunction.prototype = getBuilderProperties(<Function & T>component);
builderFunction.prototype.create = function (): Object {
const temp: string = <string>extend({}, {}, this.properties);
this.properties = {};
return new (<FunctionConstructor & T>component)(temp, this.element);
};
}
return new (builderFunction as FunctionConstructor)(<string>element);
};
return instanceFunction;
}
/**
* Returns parent options for the object
*
* @param {Object} context ?
* @param {string} prefix ?
* @returns {ParentOption} ?
* @private
*/
function getParentContext(context: Object, prefix: string): ParentOption {
// eslint-disable-next-line
if (context.hasOwnProperty('parentObj') === false) {
return { context: <EventListener>context, prefix: prefix };
} else {
const curText: string = getValue('propName', context);
if (curText) {
prefix = curText + '-' + prefix;
}
return getParentContext(getValue('parentObj', context), prefix);
}
} | the_stack |
import type {
NonDeletedExcalidrawElement,
NonDeleted,
ExcalidrawFreeDrawElement,
} from "@excalidraw/excalidraw/types/element/types";
import { getFreeDrawSvgPath } from "@excalidraw/excalidraw";
type AnimateOptions = {
startMs?: number;
pointerImg?: string;
pointerWidth?: string;
pointerHeight?: string;
};
const SVG_NS = "http://www.w3.org/2000/svg";
const findNode = (ele: SVGElement, name: string) => {
const childNodes = ele.childNodes as NodeListOf<SVGElement>;
for (let i = 0; i < childNodes.length; ++i) {
if (childNodes[i].tagName === name) {
return childNodes[i];
}
}
return null;
};
const hideBeforeAnimation = (
svg: SVGSVGElement,
ele: SVGElement,
currentMs: number,
durationMs: number,
freeze?: boolean
) => {
ele.setAttribute("opacity", "0");
const animate = svg.ownerDocument.createElementNS(SVG_NS, "animate");
animate.setAttribute("attributeName", "opacity");
animate.setAttribute("from", "1");
animate.setAttribute("to", "1");
animate.setAttribute("begin", `${currentMs}ms`);
animate.setAttribute("dur", `${durationMs}ms`);
if (freeze) {
animate.setAttribute("fill", "freeze");
}
ele.appendChild(animate);
};
const pickOnePathItem = (path: string) => {
const items = path.match(/(M[^C]*C[^M]*)/g);
if (!items) {
return path;
}
if (items.length <= 2) {
return items[items.length - 1];
}
const [longestIndex] = items.reduce(
(prev, item, index) => {
const [, x1, y1, x2, y2] =
item.match(/M([\d.-]+) ([\d.-]+) C([\d.-]+) ([\d.-]+)/) || [];
const d = Math.hypot(Number(x2) - Number(x1), Number(y2) - Number(y1));
if (d > prev[1]) {
return [index, d];
}
return prev;
},
[0, 0]
);
return items[longestIndex];
};
const animatePointer = (
svg: SVGSVGElement,
ele: SVGElement,
path: string,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
if (!options.pointerImg) return;
const img = svg.ownerDocument.createElementNS(SVG_NS, "image");
img.setAttribute("href", options.pointerImg);
if (options.pointerWidth) {
img.setAttribute("width", options.pointerWidth);
}
if (options.pointerHeight) {
img.setAttribute("height", options.pointerHeight);
}
hideBeforeAnimation(svg, img, currentMs, durationMs);
const animateMotion = svg.ownerDocument.createElementNS(
SVG_NS,
"animateMotion"
);
animateMotion.setAttribute("path", pickOnePathItem(path));
animateMotion.setAttribute("begin", `${currentMs}ms`);
animateMotion.setAttribute("dur", `${durationMs}ms`);
img.appendChild(animateMotion);
ele.parentNode?.appendChild(img);
};
const animatePath = (
svg: SVGSVGElement,
ele: SVGElement,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
const dTo = ele.getAttribute("d") || "";
const mCount = dTo.match(/M/g)?.length || 0;
const cCount = dTo.match(/C/g)?.length || 0;
const repeat = cCount / mCount;
let dLast = dTo;
for (let i = repeat - 1; i >= 0; i -= 1) {
const dFrom = dTo.replace(
new RegExp(
[
"M(\\S+) (\\S+)",
"((?: C\\S+ \\S+, \\S+ \\S+, \\S+ \\S+){",
`${i}`, // skip count
"})",
"(?: C\\S+ \\S+, \\S+ \\S+, \\S+ \\S+){1,}",
].join(""),
"g"
),
(...a) => {
const [x, y] = a[3]
? a[3].match(/.* (\S+) (\S+)$/).slice(1, 3)
: [a[1], a[2]];
return (
`M${a[1]} ${a[2]}${a[3]}` +
` C${x} ${y}, ${x} ${y}, ${x} ${y}`.repeat(repeat - i)
);
}
);
if (i === 0) {
ele.setAttribute("d", dFrom);
}
const animate = svg.ownerDocument.createElementNS(SVG_NS, "animate");
animate.setAttribute("attributeName", "d");
animate.setAttribute("from", dFrom);
animate.setAttribute("to", dLast);
animate.setAttribute("begin", `${currentMs + i * (durationMs / repeat)}ms`);
animate.setAttribute("dur", `${durationMs / repeat}ms`);
animate.setAttribute("fill", "freeze");
ele.appendChild(animate);
dLast = dFrom;
}
animatePointer(svg, ele, dTo, currentMs, durationMs, options);
hideBeforeAnimation(svg, ele, currentMs, durationMs, true);
};
const animateFillPath = (
svg: SVGSVGElement,
ele: SVGElement,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
const dTo = ele.getAttribute("d") || "";
if (dTo.includes("C")) {
animatePath(svg, ele, currentMs, durationMs, options);
return;
}
const dFrom = dTo.replace(
new RegExp(["M(\\S+) (\\S+)", "((?: L\\S+ \\S+){1,})"].join("")),
(...a) => {
return `M${a[1]} ${a[2]}` + a[3].replace(/L\S+ \S+/g, `L${a[1]} ${a[2]}`);
}
);
ele.setAttribute("d", dFrom);
const animate = svg.ownerDocument.createElementNS(SVG_NS, "animate");
animate.setAttribute("attributeName", "d");
animate.setAttribute("from", dFrom);
animate.setAttribute("to", dTo);
animate.setAttribute("begin", `${currentMs}ms`);
animate.setAttribute("dur", `${durationMs}ms`);
animate.setAttribute("fill", "freeze");
ele.appendChild(animate);
};
const animatePolygon = (
svg: SVGSVGElement,
ele: SVGElement,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
let dTo = ele.getAttribute("d") || "";
let mCount = dTo.match(/M/g)?.length || 0;
let cCount = dTo.match(/C/g)?.length || 0;
if (mCount === cCount + 1) {
// workaround for round rect
dTo = dTo.replace(/^M\S+ \S+ M/, "M");
mCount = dTo.match(/M/g)?.length || 0;
cCount = dTo.match(/C/g)?.length || 0;
}
if (mCount !== cCount) throw new Error("unexpected m/c counts");
const dups = ele.getAttribute("stroke-dasharray") ? 1 : Math.min(2, mCount);
const repeat = mCount / dups;
let dLast = dTo;
for (let i = repeat - 1; i >= 0; i -= 1) {
const dFrom = dTo.replace(
new RegExp(
[
"((?:",
"M(\\S+) (\\S+) C\\S+ \\S+, \\S+ \\S+, \\S+ \\S+ ?".repeat(dups),
"){",
`${i}`, // skip count
"})",
"M(\\S+) (\\S+) C\\S+ \\S+, \\S+ \\S+, \\S+ \\S+ ?".repeat(dups),
".*",
].join("")
),
(...a) => {
return (
`${a[1]}` +
[...Array(dups).keys()]
.map((d) => {
const [x, y] = a.slice(2 + dups * 2 + d * 2);
return `M${x} ${y} C${x} ${y}, ${x} ${y}, ${x} ${y} `;
})
.join("")
.repeat(repeat - i)
);
}
);
if (i === 0) {
ele.setAttribute("d", dFrom);
}
const animate = svg.ownerDocument.createElementNS(SVG_NS, "animate");
animate.setAttribute("attributeName", "d");
animate.setAttribute("from", dFrom);
animate.setAttribute("to", dLast);
animate.setAttribute("begin", `${currentMs + i * (durationMs / repeat)}ms`);
animate.setAttribute("dur", `${durationMs / repeat}ms`);
animate.setAttribute("fill", "freeze");
ele.appendChild(animate);
dLast = dFrom;
animatePointer(
svg,
ele,
dTo.replace(
new RegExp(
[
"(?:",
"M\\S+ \\S+ C\\S+ \\S+, \\S+ \\S+, \\S+ \\S+ ?".repeat(dups),
"){",
`${i}`, // skip count
"}",
"(M\\S+ \\S+ C\\S+ \\S+, \\S+ \\S+, \\S+ \\S+) ?".repeat(dups),
".*",
].join("")
),
"$1"
),
currentMs + i * (durationMs / repeat),
durationMs / repeat,
options
);
}
hideBeforeAnimation(svg, ele, currentMs, durationMs, true);
};
let pathForTextIndex = 0;
const animateText = (
svg: SVGSVGElement,
width: number,
ele: SVGElement,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
const anchor = ele.getAttribute("text-anchor") || "start";
if (anchor !== "start") {
// Not sure how to support it, fallback with opacity
const toOpacity = ele.getAttribute("opacity") || "1.0";
const animate = svg.ownerDocument.createElementNS(SVG_NS, "animate");
animate.setAttribute("attributeName", "opacity");
animate.setAttribute("from", "0.0");
animate.setAttribute("to", toOpacity);
animate.setAttribute("begin", `${currentMs}ms`);
animate.setAttribute("dur", `${durationMs}ms`);
animate.setAttribute("fill", "freeze");
ele.appendChild(animate);
ele.setAttribute("opacity", "0.0");
return;
}
const x = Number(ele.getAttribute("x") || 0);
const y = Number(ele.getAttribute("y") || 0);
pathForTextIndex += 1;
const path = svg.ownerDocument.createElementNS(SVG_NS, "path");
path.setAttribute("id", "pathForText" + pathForTextIndex);
const animate = svg.ownerDocument.createElementNS(SVG_NS, "animate");
animate.setAttribute("attributeName", "d");
animate.setAttribute("from", `m${x} ${y} h0`);
animate.setAttribute("to", `m${x} ${y} h${width}`);
animate.setAttribute("begin", `${currentMs}ms`);
animate.setAttribute("dur", `${durationMs}ms`);
animate.setAttribute("fill", "freeze");
path.appendChild(animate);
const textPath = svg.ownerDocument.createElementNS(SVG_NS, "textPath");
textPath.setAttribute("href", "#pathForText" + pathForTextIndex);
textPath.textContent = ele.textContent;
ele.textContent = " "; // HACK for Firebox as `null` does not work
findNode(svg, "defs")?.appendChild(path);
ele.appendChild(textPath);
animatePointer(
svg,
ele,
`m${x} ${y} h${width}`,
currentMs,
durationMs,
options
);
};
const animateFromToPath = (
svg: SVGSVGElement,
ele: SVGElement,
dFrom: string,
dTo: string,
currentMs: number,
durationMs: number
) => {
const path = svg.ownerDocument.createElementNS(SVG_NS, "path");
const animate = svg.ownerDocument.createElementNS(SVG_NS, "animate");
animate.setAttribute("attributeName", "d");
animate.setAttribute("from", dFrom);
animate.setAttribute("to", dTo);
animate.setAttribute("begin", `${currentMs}ms`);
animate.setAttribute("dur", `${durationMs}ms`);
path.appendChild(animate);
ele.appendChild(path);
};
const patchSvgLine = (
svg: SVGSVGElement,
ele: SVGElement,
strokeSharpness: string,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
const animateLine =
strokeSharpness !== "sharp" ? animatePath : animatePolygon;
const childNodes = ele.childNodes as NodeListOf<SVGElement>;
if (childNodes[0].getAttribute("fill-rule")) {
animateLine(
svg,
childNodes[0].childNodes[1] as SVGElement,
currentMs,
durationMs * 0.75,
options
);
currentMs += durationMs * 0.75;
animateFillPath(
svg,
childNodes[0].childNodes[0] as SVGElement,
currentMs,
durationMs * 0.25,
options
);
} else {
animateLine(
svg,
childNodes[0].childNodes[0] as SVGElement,
currentMs,
durationMs,
options
);
}
};
const patchSvgArrow = (
svg: SVGSVGElement,
ele: SVGElement,
strokeSharpness: string,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
const animateLine =
strokeSharpness !== "sharp" ? animatePath : animatePolygon;
const numParts = ele.childNodes.length;
animateLine(
svg,
ele.childNodes[0].childNodes[0] as SVGElement,
currentMs,
(durationMs / (numParts + 2)) * 3,
options
);
currentMs += (durationMs / (numParts + 2)) * 3;
for (let i = 1; i < numParts; i += 1) {
const numChildren = ele.childNodes[i].childNodes.length;
for (let j = 0; j < numChildren; j += 1) {
animatePath(
svg,
ele.childNodes[i].childNodes[j] as SVGElement,
currentMs,
durationMs / (numParts + 2) / numChildren,
options
);
currentMs += durationMs / (numParts + 2) / numChildren;
}
}
};
const patchSvgRectangle = (
svg: SVGSVGElement,
ele: SVGElement,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
if (ele.childNodes[1]) {
animatePolygon(
svg,
ele.childNodes[1] as SVGElement,
currentMs,
durationMs * 0.75,
options
);
currentMs += durationMs * 0.75;
animateFillPath(
svg,
ele.childNodes[0] as SVGElement,
currentMs,
durationMs * 0.25,
options
);
} else {
animatePolygon(
svg,
ele.childNodes[0] as SVGElement,
currentMs,
durationMs,
options
);
}
};
const patchSvgEllipse = (
svg: SVGSVGElement,
ele: SVGElement,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
if (ele.childNodes[1]) {
animatePath(
svg,
ele.childNodes[1] as SVGElement,
currentMs,
durationMs * 0.75,
options
);
currentMs += durationMs * 0.75;
animateFillPath(
svg,
ele.childNodes[0] as SVGElement,
currentMs,
durationMs * 0.25,
options
);
} else {
animatePath(
svg,
ele.childNodes[0] as SVGElement,
currentMs,
durationMs,
options
);
}
};
const patchSvgText = (
svg: SVGSVGElement,
ele: SVGElement,
width: number,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
const childNodes = ele.childNodes as NodeListOf<SVGElement>;
const len = childNodes.length;
childNodes.forEach((child) => {
animateText(svg, width, child, currentMs, durationMs / len, options);
currentMs += durationMs / len;
});
};
const patchSvgFreedraw = (
svg: SVGSVGElement,
ele: SVGElement,
freeDrawElement: NonDeleted<ExcalidrawFreeDrawElement>,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
const childNode = ele.childNodes[0] as SVGPathElement;
childNode.setAttribute("opacity", "0");
const animate = svg.ownerDocument.createElementNS(SVG_NS, "animate");
animate.setAttribute("attributeName", "opacity");
animate.setAttribute("from", "0");
animate.setAttribute("to", "1");
animate.setAttribute("calcMode", "discrete");
animate.setAttribute("begin", `${currentMs + durationMs - 1}ms`);
animate.setAttribute("dur", `${1}ms`);
animate.setAttribute("fill", "freeze");
childNode.appendChild(animate);
animatePointer(
svg,
childNode,
freeDrawElement.points.reduce(
(p, [x, y]) => (p ? p + ` T ${x} ${y}` : `M ${x} ${y}`),
""
),
currentMs,
durationMs,
options
);
// interporation
const repeat = freeDrawElement.points.length;
let dTo = childNode.getAttribute("d") as string;
for (let i = repeat - 1; i >= 0; i -= 1) {
const dFrom =
i > 0
? getFreeDrawSvgPath({
...freeDrawElement,
points: freeDrawElement.points.slice(0, i),
})
: "M 0 0";
animateFromToPath(
svg,
ele,
dFrom,
dTo,
currentMs + i * (durationMs / repeat),
durationMs / repeat
);
dTo = dFrom;
}
};
const patchSvgEle = (
svg: SVGSVGElement,
ele: SVGElement,
excalidraElement: NonDeletedExcalidrawElement,
currentMs: number,
durationMs: number,
options: AnimateOptions
) => {
const { type, strokeSharpness, width } = excalidraElement;
if (type === "line") {
patchSvgLine(svg, ele, strokeSharpness, currentMs, durationMs, options);
} else if (type === "arrow") {
patchSvgArrow(svg, ele, strokeSharpness, currentMs, durationMs, options);
} else if (type === "rectangle" || type === "diamond") {
patchSvgRectangle(svg, ele, currentMs, durationMs, options);
} else if (type === "ellipse") {
patchSvgEllipse(svg, ele, currentMs, durationMs, options);
} else if (type === "text") {
patchSvgText(svg, ele, width, currentMs, durationMs, options);
} else if (excalidraElement.type === "freedraw") {
patchSvgFreedraw(
svg,
ele,
excalidraElement,
currentMs,
durationMs,
options
);
}
};
const createGroups = (
svg: SVGSVGElement,
elements: readonly NonDeletedExcalidrawElement[]
) => {
const groups: { [groupId: string]: (readonly [SVGElement, number])[] } = {};
let index = 0;
const childNodes = svg.childNodes as NodeListOf<SVGElement>;
childNodes.forEach((ele) => {
if (ele.tagName === "g") {
const { groupIds } = elements[index];
if (groupIds.length >= 1) {
const groupId = groupIds[0];
groups[groupId] = groups[groupId] || [];
groups[groupId].push([ele, index] as const);
}
index += 1;
}
});
return groups;
};
const filterGroupNodes = (nodes: NodeListOf<SVGElement>) =>
[...nodes].filter((node) => node.tagName === "g");
const extractNumberFromElement = (
element: NonDeletedExcalidrawElement,
key: string
) => {
const match = element.id.match(new RegExp(`${key}:(-?\\d+)`));
return (match && Number(match[1])) || 0;
};
const sortSvgNodes = (
nodes: SVGElement[],
elements: readonly NonDeletedExcalidrawElement[]
) =>
[...nodes].sort((a, b) => {
const aIndex = nodes.indexOf(a);
const bIndex = nodes.indexOf(b);
const aOrder = extractNumberFromElement(elements[aIndex], "animateOrder");
const bOrder = extractNumberFromElement(elements[bIndex], "animateOrder");
return aOrder - bOrder;
});
export const animateSvg = (
svg: SVGSVGElement,
elements: readonly NonDeletedExcalidrawElement[],
options: AnimateOptions = {}
) => {
let finishedMs;
const groups = createGroups(svg, elements);
const finished = new Map();
let current = options.startMs ?? 1000; // 1 sec margin
const groupDur = 5000;
const individualDur = 500;
const groupNodes = filterGroupNodes(svg.childNodes as NodeListOf<SVGElement>);
if (groupNodes.length !== elements.length) {
throw new Error("element length mismatch");
}
const groupElement2Element = new Map(
groupNodes.map((ele, index) => [ele, elements[index]])
);
sortSvgNodes(groupNodes, elements).forEach((ele) => {
const element = groupElement2Element.get(
ele
) as NonDeletedExcalidrawElement;
const { groupIds } = element;
if (!finished.has(ele)) {
if (groupIds.length >= 1) {
const groupId = groupIds[0];
const group = groups[groupId];
const dur =
extractNumberFromElement(element, "animateDuration") ||
groupDur / (group.length + 1);
patchSvgEle(svg, ele, element, current, dur, options);
current += dur;
finished.set(ele, true);
group.forEach(([childEle, childIndex]) => {
const dur =
extractNumberFromElement(elements[childIndex], "animateDuration") ||
groupDur / (group.length + 1);
if (!finished.has(childEle)) {
patchSvgEle(
svg,
childEle,
elements[childIndex],
current,
dur,
options
);
current += dur;
finished.set(childEle, true);
}
});
delete groups[groupId];
} else {
const dur =
extractNumberFromElement(element, "animateDuration") || individualDur;
patchSvgEle(svg, ele, element, current, dur, options);
current += dur;
finished.set(ele, true);
}
}
});
finishedMs = current + 1000; // 1 sec margin
return { finishedMs };
};
export const getBeginTimeList = (svg: SVGSVGElement) => {
const beginTimeList: number[] = [];
const tmpTimeList: number[] = [];
const findAnimate = (ele: SVGElement) => {
if (ele.tagName === "animate") {
const match = /([0-9.]+)ms/.exec(ele.getAttribute("begin") || "");
if (match) {
tmpTimeList.push(Number(match[1]));
}
}
(ele.childNodes as NodeListOf<SVGElement>).forEach((ele) => {
findAnimate(ele);
});
};
(svg.childNodes as NodeListOf<SVGElement>).forEach((ele) => {
if (ele.tagName === "g") {
findAnimate(ele);
if (tmpTimeList.length) {
beginTimeList.push(Math.min(...tmpTimeList));
tmpTimeList.splice(0);
}
} else if (ele.tagName === "defs") {
(ele.childNodes as NodeListOf<SVGElement>).forEach((ele) => {
findAnimate(ele);
if (tmpTimeList.length) {
beginTimeList.push(Math.min(...tmpTimeList));
tmpTimeList.splice(0);
}
});
}
});
return beginTimeList;
}; | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Manages an Automation Runbook's Webhook.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAccount = new azure.automation.Account("exampleAccount", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* skuName: "Basic",
* });
* const exampleRunBook = new azure.automation.RunBook("exampleRunBook", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* automationAccountName: exampleAccount.name,
* logVerbose: "true",
* logProgress: "true",
* description: "This is an example runbook",
* runbookType: "PowerShellWorkflow",
* publishContentLink: {
* uri: "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/c4935ffb69246a6058eb24f54640f53f69d3ac9f/101-automation-runbook-getvms/Runbooks/Get-AzureVMTutorial.ps1",
* },
* });
* const exampleWebhook = new azure.automation.Webhook("exampleWebhook", {
* resourceGroupName: exampleResourceGroup.name,
* automationAccountName: exampleAccount.name,
* expiryTime: "2021-12-31T00:00:00Z",
* enabled: true,
* runbookName: exampleRunBook.name,
* parameters: {
* input: "parameter",
* },
* });
* ```
*
* ## Import
*
* Automation Webhooks can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:automation/webhook:Webhook TestRunbook_webhook /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Automation/automationAccounts/account1/webhooks/TestRunbook_webhook
* ```
*/
export class Webhook extends pulumi.CustomResource {
/**
* Get an existing Webhook 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?: WebhookState, opts?: pulumi.CustomResourceOptions): Webhook {
return new Webhook(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:automation/webhook:Webhook';
/**
* Returns true if the given object is an instance of Webhook. 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 Webhook {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Webhook.__pulumiType;
}
/**
* The name of the automation account in which the Webhook is created. Changing this forces a new resource to be created.
*/
public readonly automationAccountName!: pulumi.Output<string>;
/**
* Controls if Webhook is enabled. Defaults to `true`.
*/
public readonly enabled!: pulumi.Output<boolean | undefined>;
/**
* Timestamp when the webhook expires. Changing this forces a new resource to be created.
*/
public readonly expiryTime!: pulumi.Output<string>;
/**
* Specifies the name of the Webhook. Changing this forces a new resource to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* Map of input parameters passed to runbook.
*/
public readonly parameters!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The name of the resource group in which the Webhook is created. Changing this forces a new resource to be created.
*/
public readonly resourceGroupName!: pulumi.Output<string>;
/**
* Name of the hybrid worker group the Webhook job will run on.
*/
public readonly runOnWorkerGroup!: pulumi.Output<string | undefined>;
/**
* Name of the Automation Runbook to execute by Webhook.
*/
public readonly runbookName!: pulumi.Output<string>;
/**
* URI to initiate the webhook. Can be generated using [Generate URI API](https://docs.microsoft.com/en-us/rest/api/automation/webhook/generate-uri). By default, new URI is generated on each new resource creation.
*/
public readonly uri!: pulumi.Output<string>;
/**
* Create a Webhook 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: WebhookArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: WebhookArgs | WebhookState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as WebhookState | undefined;
inputs["automationAccountName"] = state ? state.automationAccountName : undefined;
inputs["enabled"] = state ? state.enabled : undefined;
inputs["expiryTime"] = state ? state.expiryTime : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["parameters"] = state ? state.parameters : undefined;
inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined;
inputs["runOnWorkerGroup"] = state ? state.runOnWorkerGroup : undefined;
inputs["runbookName"] = state ? state.runbookName : undefined;
inputs["uri"] = state ? state.uri : undefined;
} else {
const args = argsOrState as WebhookArgs | undefined;
if ((!args || args.automationAccountName === undefined) && !opts.urn) {
throw new Error("Missing required property 'automationAccountName'");
}
if ((!args || args.expiryTime === undefined) && !opts.urn) {
throw new Error("Missing required property 'expiryTime'");
}
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
if ((!args || args.runbookName === undefined) && !opts.urn) {
throw new Error("Missing required property 'runbookName'");
}
inputs["automationAccountName"] = args ? args.automationAccountName : undefined;
inputs["enabled"] = args ? args.enabled : undefined;
inputs["expiryTime"] = args ? args.expiryTime : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["parameters"] = args ? args.parameters : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["runOnWorkerGroup"] = args ? args.runOnWorkerGroup : undefined;
inputs["runbookName"] = args ? args.runbookName : undefined;
inputs["uri"] = args ? args.uri : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Webhook.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Webhook resources.
*/
export interface WebhookState {
/**
* The name of the automation account in which the Webhook is created. Changing this forces a new resource to be created.
*/
automationAccountName?: pulumi.Input<string>;
/**
* Controls if Webhook is enabled. Defaults to `true`.
*/
enabled?: pulumi.Input<boolean>;
/**
* Timestamp when the webhook expires. Changing this forces a new resource to be created.
*/
expiryTime?: pulumi.Input<string>;
/**
* Specifies the name of the Webhook. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* Map of input parameters passed to runbook.
*/
parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The name of the resource group in which the Webhook is created. Changing this forces a new resource to be created.
*/
resourceGroupName?: pulumi.Input<string>;
/**
* Name of the hybrid worker group the Webhook job will run on.
*/
runOnWorkerGroup?: pulumi.Input<string>;
/**
* Name of the Automation Runbook to execute by Webhook.
*/
runbookName?: pulumi.Input<string>;
/**
* URI to initiate the webhook. Can be generated using [Generate URI API](https://docs.microsoft.com/en-us/rest/api/automation/webhook/generate-uri). By default, new URI is generated on each new resource creation.
*/
uri?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Webhook resource.
*/
export interface WebhookArgs {
/**
* The name of the automation account in which the Webhook is created. Changing this forces a new resource to be created.
*/
automationAccountName: pulumi.Input<string>;
/**
* Controls if Webhook is enabled. Defaults to `true`.
*/
enabled?: pulumi.Input<boolean>;
/**
* Timestamp when the webhook expires. Changing this forces a new resource to be created.
*/
expiryTime: pulumi.Input<string>;
/**
* Specifies the name of the Webhook. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* Map of input parameters passed to runbook.
*/
parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The name of the resource group in which the Webhook is created. Changing this forces a new resource to be created.
*/
resourceGroupName: pulumi.Input<string>;
/**
* Name of the hybrid worker group the Webhook job will run on.
*/
runOnWorkerGroup?: pulumi.Input<string>;
/**
* Name of the Automation Runbook to execute by Webhook.
*/
runbookName: pulumi.Input<string>;
/**
* URI to initiate the webhook. Can be generated using [Generate URI API](https://docs.microsoft.com/en-us/rest/api/automation/webhook/generate-uri). By default, new URI is generated on each new resource creation.
*/
uri?: pulumi.Input<string>;
} | the_stack |
import minimatch from 'minimatch';
import {
isFilePath,
isModuleName,
PackageStructure,
Path,
PathResolver,
toArray,
} from '@boost/common';
import { Blueprint, Schemas } from '@boost/common/optimal';
import { color } from '@boost/internal';
import { ConfigError } from './ConfigError';
import { CONFIG_FOLDER, DEFAULT_EXTS, PACKAGE_FILE } from './constants';
import { Finder } from './Finder';
import { createFileName } from './helpers/createFileName';
import { getEnv } from './helpers/getEnv';
import { loadCjs } from './loaders/cjs';
import { loadJs } from './loaders/js';
import { loadJson } from './loaders/json';
import { loadMjs } from './loaders/mjs';
import { loadTs } from './loaders/ts';
import { loadYaml } from './loaders/yaml';
import { ConfigFile, ConfigFinderOptions, ExtType, FileSource, OverridesSetting } from './types';
export class ConfigFinder<T extends object> extends Finder<ConfigFile<T>, ConfigFinderOptions<T>> {
blueprint(schemas: Schemas): Blueprint<ConfigFinderOptions<T>> {
const { array, bool, func, shape, string } = schemas;
return {
extendsSetting: string(),
extensions: array(DEFAULT_EXTS).of(string<ExtType>()),
includeEnv: bool(true),
loaders: shape({
cjs: func(() => loadCjs).notNullable(),
js: func(() => loadJs).notNullable(),
json: func(() => loadJson).notNullable(),
json5: func(() => loadJson).notNullable(),
mjs: func(() => loadMjs).notNullable(),
ts: func(() => loadTs).notNullable(),
yaml: func(() => loadYaml).notNullable(),
yml: func(() => loadYaml).notNullable(),
}).exact(),
name: string().required().camelCase(),
overridesSetting: string(),
resolver: func(() => PathResolver.defaultResolver).notNullable(),
};
}
/**
* Determine a files package scope by finding the first parent `package.json`
* when traversing up directories. We will leverage the cache as much as
* possible for performance.
*
* @see https://nodejs.org/api/esm.html#esm_package_scope_and_file_extensions
*/
async determinePackageScope(dir: Path): Promise<PackageStructure> {
let currentDir = dir.isDirectory() ? dir : dir.parent();
this.debug('Determining package scope for %s', color.filePath(dir.path()));
while (!this.isFileSystemRoot(currentDir)) {
const pkgPath = currentDir.append(PACKAGE_FILE);
const cache = this.cache.getFileCache<PackageStructure>(pkgPath);
if (cache) {
if (cache.exists) {
this.debug('Scope found at %s', color.filePath(pkgPath.path()));
return cache.content;
}
// Fall-through
} else if (pkgPath.exists()) {
this.debug('Scope found at %s', color.filePath(pkgPath.path()));
return this.cache.cacheFileContents(pkgPath, () => loadJson(pkgPath));
} else {
this.cache.markMissingFile(pkgPath);
}
currentDir = currentDir.parent();
}
throw new ConfigError('PACKAGE_UNKNOWN_SCOPE');
}
/**
* Find all configuration and environment specific files in a directory
* by looping through all the defined extension options.
* Will only search until the first file is found, and will not return multiple extensions.
*/
async findFilesInDir(dir: Path): Promise<Path[]> {
const isRoot = this.isRootDir(dir);
const baseDir = isRoot ? dir.append(CONFIG_FOLDER) : dir;
return this.cache.cacheFilesInDir(baseDir, async () => {
const paths: Path[] = [];
for (const ext of this.options.extensions) {
const files = [baseDir.append(this.getFileName(ext, !isRoot, false))];
if (this.options.includeEnv) {
files.push(baseDir.append(this.getFileName(ext, !isRoot, true)));
}
await Promise.all(
files.map((configPath) => {
if (configPath.exists()) {
paths.push(configPath);
}
return configPath;
}),
);
// Once we find any file, we abort looking for others
if (paths.length > 0) {
break;
}
}
this.debug.invariant(
paths.length > 0,
`Finding config files in ${color.filePath(baseDir.path())}`,
paths.map((path) => path.name()).join(', '),
'No files',
);
// Make sure env takes higher precedence
paths.sort((a, b) => a.path().length - b.path().length);
return paths;
});
}
/**
* Create and return a config file name, with optional branch and environment variants.
*/
getFileName(ext: string, isBranch: boolean, isEnv: boolean): string {
const { name } = this.options;
return createFileName(name, ext, {
envSuffix: isEnv ? getEnv(name) : '',
leadingDot: isBranch,
});
}
/**
* Load file and package contents from a list of file paths.
* Extract and apply extended and override configs based on the base path.
*/
async resolveFiles(basePath: Path, foundFiles: Path[]): Promise<ConfigFile<T>[]> {
this.debug('Resolving %d config files', foundFiles.length);
const configs = await Promise.all(foundFiles.map((filePath) => this.loadConfig(filePath)));
// Overrides take the highest precedence and must appear after everything,
// including branch level configs. However, they must extract first so that
// extends functionality can be inherited (below).
if (this.options.overridesSetting) {
const overriddenConfigs = await this.extractOverriddenConfigs(basePath, configs);
this.debug('Overriding %d configs', overriddenConfigs.length);
if (overriddenConfigs.length > 0) {
configs.push(...overriddenConfigs);
}
}
// Configs that have been extended from root configs must
// appear before everything else, in the order they were defined
if (this.options.extendsSetting) {
const extendedConfigs = await this.extractExtendedConfigs(configs);
this.debug('Extending %d configs', extendedConfigs.length);
if (extendedConfigs.length > 0) {
configs.unshift(...extendedConfigs);
}
}
return configs;
}
/**
* Extract a list of config files to extend, in order, from the list of previously loaded
* config files, which is typically from the root. The list to extract can be located within
* a property that matches the `extendsSetting` option.
*/
protected async extractExtendedConfigs(configs: ConfigFile<T>[]): Promise<ConfigFile<T>[]> {
const { name, extendsSetting, resolver } = this.options;
const extendsPaths: Path[] = [];
this.debug('Extracting configs to extend from');
for (const { config, path, source } of configs) {
const key = extendsSetting as keyof typeof config;
const extendsFrom = config[key];
if (source === 'root' || source === 'overridden') {
delete config[key];
} else if (extendsFrom) {
throw new ConfigError('EXTENDS_ONLY_ROOT', [key]);
} else {
// eslint-disable-next-line no-continue
continue;
}
const extendedPaths = await Promise.all(
(toArray(extendsFrom) as unknown as string[]).map(async (extendsPath) => {
// Node module
if (isModuleName(extendsPath)) {
const modulePath = new Path(
extendsPath,
createFileName(name, 'js', { envSuffix: 'preset' }),
);
this.debug(
'Extending config from node module: %s',
color.moduleName(modulePath.path()),
);
return new Path(await resolver(modulePath.path()));
}
// File path
if (isFilePath(extendsPath)) {
let filePath = new Path(extendsPath);
// Relative to the config file its defined in
if (!filePath.isAbsolute()) {
filePath = path.parent().append(extendsPath);
}
this.debug('Extending config from file path: %s', color.filePath(filePath.path()));
return filePath;
}
// Unknown
throw new ConfigError('EXTENDS_UNKNOWN_PATH', [extendsPath]);
}),
);
extendsPaths.push(...extendedPaths);
}
return Promise.all(extendsPaths.map((path) => this.loadConfig(path, 'extended')));
}
/**
* Extract all root config overrides that match the current path used to load with.
* Overrides are located within a property that matches the `overridesSetting` option.
*/
protected extractOverriddenConfigs(basePath: Path, configs: ConfigFile<T>[]): ConfigFile<T>[] {
const { overridesSetting } = this.options;
const overriddenConfigs: ConfigFile<T>[] = [];
this.debug(
'Extracting configs to override with (matching against %s)',
color.filePath(basePath.path()),
);
configs.forEach(({ config, path, source }) => {
const key = overridesSetting as keyof typeof config;
const overrides = config[key];
if (source === 'root') {
delete config[key];
} else if (overrides) {
throw new ConfigError('ROOT_ONLY_OVERRIDES', [key]);
} else {
return;
}
(toArray(overrides) as unknown as OverridesSetting<T>).forEach(
({ exclude, include, settings }) => {
const options = { dot: true, matchBase: true };
const excludePatterns = toArray(exclude);
const excluded = excludePatterns.some((pattern) =>
minimatch(basePath.path(), pattern, options),
);
const includePatterns = toArray(include);
const included = includePatterns.some((pattern) =>
minimatch(basePath.path(), pattern, options),
);
const passes = included && !excluded;
this.debug.invariant(
passes,
`Matching with includes "${includePatterns}" and excludes "${excludePatterns}"`,
'Matched',
// eslint-disable-next-line no-nested-ternary
excluded ? 'Excluded' : included ? 'Not matched' : 'Not included',
);
if (passes) {
overriddenConfigs.push({
config: settings,
path,
source: 'overridden',
});
}
},
);
});
return overriddenConfigs;
}
/**
* Load config contents from the provided file path using one of the defined loaders.
*/
protected async loadConfig(path: Path, source?: FileSource): Promise<ConfigFile<T>> {
const pkg = await this.determinePackageScope(path);
const config = await this.cache.cacheFileContents(path, async () => {
const { loaders } = this.options;
const ext = path.ext(true);
this.debug('Loading config %s with type %s', color.filePath(path.path()), color.symbol(ext));
switch (ext) {
case 'cjs':
return loaders.cjs(path, pkg);
case 'js':
return loaders.js(path, pkg);
case 'json':
case 'json5':
return loaders.json(path, pkg);
case 'mjs':
// Not easily testable yet
// istanbul ignore next
return loaders.mjs(path, pkg);
case 'ts':
case 'tsx':
return loaders.ts(path, pkg);
case 'yaml':
case 'yml':
return loaders.yaml(path, pkg);
default:
throw new ConfigError('LOADER_UNSUPPORTED', [ext]);
}
});
return {
config,
path,
source: source ?? (path.path().includes(CONFIG_FOLDER) ? 'root' : 'branch'),
};
}
} | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import Outputs from '../../../../../resources/outputs';
import { Responses } from '../../../../../resources/responses';
import Util from '../../../../../resources/util';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
beganMonitoringHp?: boolean;
garotte?: boolean;
seenFinalPhase: boolean;
dragons?: number[];
tetherCount: number;
naelDiveMarkerCount: number;
naelMarks?: string[];
safeZone?: string;
}
const diveDirections = {
unknown: Outputs.unknown,
north: Outputs.dirN,
northeast: Outputs.dirNE,
east: Outputs.dirE,
southeast: Outputs.dirSE,
south: Outputs.dirS,
southwest: Outputs.dirSW,
west: Outputs.dirW,
northwest: Outputs.dirNW,
};
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.TheSecondCoilOfBahamutTurn4,
timelineFile: 't9.txt',
initData: () => {
return {
monitoringHP: false,
seenFinalPhase: false,
tetherCount: 0,
naelDiveMarkerCount: 0,
};
},
timelineTriggers: [
{
id: 'T9 Claw',
regex: /Bahamut's Claw x5/,
beforeSeconds: 5,
response: Responses.tankBuster(),
},
{
id: 'T9 Dalamud Dive',
regex: /Dalamud Dive/,
beforeSeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Dive on Main Tank',
de: 'Sturz auf den Main Tank',
fr: 'Plongeon sur le Main Tank',
ja: 'MTに飛んでくる',
cn: '凶鸟跳点MT',
ko: '광역 탱버',
},
},
},
{
id: 'T9 Super Nova',
regex: /Super Nova x3/,
beforeSeconds: 4,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Bait Super Novas Outside',
de: 'Köder Supernova draußen',
fr: 'Attirez les Supernovas à l\'extérieur',
ja: 'スーパーノヴァを外に設置',
cn: '人群外放黑洞',
ko: '초신성 외곽으로 유도',
},
},
},
],
triggers: [
{
id: 'T9 Raven Blight You',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '1CA' }),
condition: Conditions.targetIsYou(),
delaySeconds: (_data, matches) => parseFloat(matches.duration) - 5,
durationSeconds: 5,
alarmText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Blight on YOU',
de: 'Pestschwinge auf DIR',
fr: 'Bile de rapace sur VOUS',
ja: '自分に凶鳥毒気',
cn: '毒气点名',
ko: '5초후 디버프 폭발',
},
},
},
{
id: 'T9 Raven Blight Not You',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '1CA' }),
condition: Conditions.targetIsNotYou(),
delaySeconds: (_data, matches) => parseFloat(matches.duration) - 5,
durationSeconds: 5,
infoText: (data, matches, output) => output.text!({ player: data.ShortName(matches.target) }),
outputStrings: {
text: {
en: 'Blight on ${player}',
de: 'Pestschwinge auf ${player}',
fr: 'Bile de rapace sur ${player}',
ja: '${player}に凶鳥毒気',
cn: '毒气点${player}',
ko: '광역폭발 디버프 ${player}',
},
},
},
{
id: 'T9 Meteor',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '000[7A9]' }),
condition: Conditions.targetIsYou(),
response: Responses.meteorOnYou(),
},
{
id: 'T9 Meteor Stream',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0008' }),
condition: Conditions.targetIsYou(),
response: Responses.spread(),
},
{
id: 'T9 Stack',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '000F' }),
alertText: (data, matches, output) => {
if (data.me === matches.target)
return output.thermoOnYou!();
return output.stackOn!({ player: data.ShortName(matches.target) });
},
outputStrings: {
thermoOnYou: {
en: 'Thermo on YOU',
de: 'Thermo auf DIR',
fr: 'Thermo sur VOUS',
ja: '自分に頭割り',
cn: '分摊点名',
ko: '쉐어징 대상자',
},
stackOn: Outputs.stackOnPlayer,
},
},
{
id: 'T9 Phase 2',
type: 'Ability',
// Ravensclaw
netRegex: NetRegexes.ability({ id: '7D5', source: 'Nael Deus Darnus' }),
netRegexDe: NetRegexes.ability({ id: '7D5', source: 'Nael Deus Darnus' }),
netRegexFr: NetRegexes.ability({ id: '7D5', source: 'Nael Deus Darnus' }),
netRegexJa: NetRegexes.ability({ id: '7D5', source: 'ネール・デウス・ダーナス' }),
netRegexCn: NetRegexes.ability({ id: '7D5', source: '奈尔·神·达纳斯' }),
netRegexKo: NetRegexes.ability({ id: '7D5', source: '넬 데우스 다르누스' }),
condition: (data) => !data.beganMonitoringHp,
preRun: (data) => data.beganMonitoringHp = true,
promise: (_data, matches) =>
Util.watchCombatant({
ids: [parseInt(matches.sourceId, 16)],
}, (ret) => {
return ret.combatants.some((c) => {
return c.CurrentHP / c.MaxHP <= 0.64;
});
}),
sound: 'Long',
},
{
id: 'T9 Earthshock',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '7F5', source: 'Dalamud Spawn', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '7F5', source: 'Dalamud-Golem', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '7F5', source: 'Golem De Dalamud', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '7F5', source: 'ダラガブゴーレム', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '7F5', source: '卫月巨像', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '7F5', source: '달라가브 골렘', capture: false }),
condition: (data) => data.CanSilence(),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Silence Blue Golem',
de: 'Blauen Golem verstummen',
fr: 'Interrompez le Golem bleu',
ja: '沈黙:青ゴーレム',
cn: '沉默蓝色小怪',
ko: '파란골렘 기술끊기',
},
},
},
{
id: 'T9 Heavensfall',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '83B', source: 'Nael Deus Darnus', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '83B', source: 'Nael Deus Darnus', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '83B', source: 'Nael Deus Darnus', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '83B', source: 'ネール・デウス・ダーナス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '83B', source: '奈尔·神·达纳斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '83B', source: '넬 데우스 다르누스', capture: false }),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Heavensfall',
de: 'Himmelssturz',
fr: 'Destruction universelle',
ja: '天地崩壊',
cn: '击退AOE',
ko: '천지붕괴',
},
},
},
{
id: 'T9 Garotte Twist Gain',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '1CE' }),
condition: (data, matches) => data.me === matches.target && !data.garotte,
infoText: (_data, _matches, output) => output.text!(),
run: (data) => data.garotte = true,
outputStrings: {
text: {
en: 'Garotte on YOU',
de: 'Leicht fixierbar auf DIR',
fr: 'Sangle accélérée sur VOUS',
ja: '自分に拘束加速',
cn: '连坐点名',
ko: '구속 가속',
},
},
},
{
id: 'T9 Ghost Death',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '7FA', source: 'The Ghost Of Meracydia', capture: false }),
netRegexDe: NetRegexes.ability({ id: '7FA', source: 'Geist Von Meracydia', capture: false }),
netRegexFr: NetRegexes.ability({ id: '7FA', source: 'Fantôme Méracydien', capture: false }),
netRegexJa: NetRegexes.ability({ id: '7FA', source: 'メラシディアン・ゴースト', capture: false }),
netRegexCn: NetRegexes.ability({ id: '7FA', source: '美拉西迪亚幽龙', capture: false }),
netRegexKo: NetRegexes.ability({ id: '7FA', source: '메라시디아의 유령', capture: false }),
condition: (data) => data.garotte,
alarmText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Cleanse Garotte',
de: 'reinige Leicht fixierbar',
fr: 'Dissipez Sangle accélérée',
ja: '白い床に乗る',
cn: '踩白圈',
ko: '흰색 장판 밟기',
},
},
},
{
id: 'T9 Garotte Twist Lose',
type: 'LosesEffect',
netRegex: NetRegexes.losesEffect({ effectId: '1CE' }),
condition: (data, matches) => data.me === matches.target && data.garotte,
run: (data) => delete data.garotte,
},
{
id: 'T9 Final Phase',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '7E6', source: 'Nael Deus Darnus', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '7E6', source: 'Nael Deus Darnus', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '7E6', source: 'Nael Deus Darnus', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '7E6', source: 'ネール・デウス・ダーナス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '7E6', source: '奈尔·神·达纳斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '7E6', source: '넬 데우스 다르누스', capture: false }),
condition: (data) => !data.seenFinalPhase,
sound: 'Long',
run: (data) => data.seenFinalPhase = true,
},
{
id: 'T9 Dragon Locations',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ name: ['Firehorn', 'Iceclaw', 'Thunderwing'] }),
netRegexDe: NetRegexes.addedCombatantFull({ name: ['Feuerhorn', 'Eisklaue', 'Donnerschwinge'] }),
netRegexFr: NetRegexes.addedCombatantFull({ name: ['Corne-De-Feu', 'Griffe-De-Glace', 'Aile-De-Foudre'] }),
netRegexJa: NetRegexes.addedCombatantFull({ name: ['ファイアホーン', 'アイスクロウ', 'サンダーウィング'] }),
netRegexCn: NetRegexes.addedCombatantFull({ name: ['火角', '冰爪', '雷翼'] }),
netRegexKo: NetRegexes.addedCombatantFull({ name: ['화염뿔', '얼음발톱', '번개날개'] }),
run: (data, matches) => {
// Lowercase all of the names here for case insensitive matching.
const allNames = {
en: ['firehorn', 'iceclaw', 'thunderwing'],
de: ['feuerhorn', 'eisklaue', 'donnerschwinge'],
fr: ['corne-de-feu', 'griffe-de-glace ', 'aile-de-foudre'],
ja: ['ファイアホーン', 'アイスクロウ', 'サンダーウィング'],
cn: ['火角', '冰爪', '雷翼'],
ko: ['화염뿔', '얼음발톱', '번개날개'],
};
const names = allNames[data.parserLang];
const idx = names.indexOf(matches.name.toLowerCase());
if (idx === -1)
return;
const x = parseFloat(matches.x);
const y = parseFloat(matches.y);
// Most dragons are out on a circle of radius=~28.
// Ignore spurious dragons like "Pos: (0.000919255,0.006120025,2.384186E-07)"
if (x * x + y * y < 20 * 20)
return;
// Positions are the 8 cardinals + numerical slop on a radius=28 circle.
// N = (0, -28), E = (28, 0), S = (0, 28), W = (-28, 0)
// Map N = 0, NE = 1, ..., NW = 7
const dir = Math.round(4 - 4 * Math.atan2(x, y) / Math.PI) % 8;
data.dragons ??= [0, 0, 0];
data.dragons[idx] = dir;
},
},
{
id: 'T9 Final Phase Reset',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '7E6', source: 'Nael Deus Darnus', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '7E6', source: 'Nael Deus Darnus', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '7E6', source: 'Nael Deus Darnus', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '7E6', source: 'ネール・デウス・ダーナス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '7E6', source: '奈尔·神·达纳斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '7E6', source: '넬 데우스 다르누스', capture: false }),
run: (data) => {
data.tetherCount = 0;
data.naelDiveMarkerCount = 0;
data.naelMarks = ['unknown', 'unknown'];
data.safeZone = 'unknown';
// Missing dragons??
if (!data.dragons || data.dragons.length !== 3)
return;
// T9 normal dragons are easy.
// The first two are always split, so A is the first dragon + 1.
// The last one is single, so B is the last dragon + 1.
const dragons = data.dragons.sort();
const [d0, d1, d2] = dragons;
if (d0 === undefined || d1 === undefined || d2 === undefined)
return;
const dirNames = [
'north',
'northeast',
'east',
'southeast',
'south',
'southwest',
'west',
'northwest',
];
data.naelMarks = [d0, d2].map((i) => dirNames[(i + 1) % 8] ?? 'unknown');
// Safe zone is one to the left of the first dragon, unless
// the last dragon is diving there. If that's true, use
// one to the right of the second dragon.
let possibleSafe = (d0 - 1 + 8) % 8;
if ((d2 + 2) % 8 === possibleSafe)
possibleSafe = (d1 + 1) % 8;
data.safeZone = dirNames[possibleSafe];
},
},
{
id: 'T9 Dragon Marks',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '7E6', source: 'Nael Deus Darnus', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '7E6', source: 'Nael Deus Darnus', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '7E6', source: 'Nael Deus Darnus', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '7E6', source: 'ネール・デウス・ダーナス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '7E6', source: '奈尔·神·达纳斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '7E6', source: '넬 데우스 다르누스', capture: false }),
durationSeconds: 12,
infoText: (data, _matches, output) =>
output.marks!({
dir1: output[data.naelMarks?.[0] ?? 'unknown']!(),
dir2: output[data.naelMarks?.[1] ?? 'unknown']!(),
}),
outputStrings: {
...diveDirections,
marks: {
en: 'Marks: ${dir1}, ${dir2}',
de: 'Markierungen : ${dir1}, ${dir2}',
fr: 'Marques : ${dir1}, ${dir2}',
ja: 'マーカー: ${dir1}, ${dir2}',
cn: '标记: ${dir1}, ${dir2}',
ko: '카탈징: ${dir1}, ${dir2}',
},
},
},
{
id: 'T9 Tether',
type: 'Tether',
netRegex: NetRegexes.tether({ id: '0005', source: 'Firehorn' }),
netRegexDe: NetRegexes.tether({ id: '0005', source: 'Feuerhorn' }),
netRegexFr: NetRegexes.tether({ id: '0005', source: 'Corne-De-Feu' }),
netRegexJa: NetRegexes.tether({ id: '0005', source: 'ファイアホーン' }),
netRegexCn: NetRegexes.tether({ id: '0005', source: '火角' }),
netRegexKo: NetRegexes.tether({ id: '0005', source: '화염뿔' }),
preRun: (data) => {
data.tetherCount++;
},
alertText: (data, matches, output) => {
if (data.me !== matches.target)
return;
// Out, In, Out, In
if (data.tetherCount % 2)
return output.fireOutOnYou!();
return output.fireInOnYou!();
},
infoText: (data, matches, output) => {
if (data.me === matches.target)
return;
// Out, In, Out, In
if (data.tetherCount % 2)
return output.fireOutOn!({ player: data.ShortName(matches.target) });
return output.fireInOn!({ player: data.ShortName(matches.target) });
},
outputStrings: {
fireOutOnYou: {
en: 'Fire Out (on YOU)',
de: 'Feuer raus (auf DIR)',
fr: 'Feu extérieur (sur VOUS)',
ja: 'ファイヤ、外に (自分)',
cn: '火球单吃点名',
},
fireInOnYou: {
en: 'Fire In (on YOU)',
de: 'Feuer rein (auf DIR)',
fr: 'Feu intérieur (sur VOUS)',
ja: 'ファイヤ、頭割り (自分)',
cn: '火球集合点名',
},
fireOutOn: {
en: 'Fire Out (on ${player})',
de: 'Feuer raus (auf ${player})',
fr: 'Feu extérieur (sur ${player})',
ja: 'ファイヤ、外に (${player})',
cn: '火球单吃点${player}',
},
fireInOn: {
en: 'Fire In (on ${player})',
de: 'Feuer rein (auf ${player})',
fr: 'Feu intérieur (sur ${player})',
ja: 'ファイヤ、頭割り (${player})',
cn: '火球集合点${player}',
},
},
},
{
id: 'T9 Thunder',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Thunderwing', id: '7FD' }),
netRegexDe: NetRegexes.ability({ source: 'Donnerschwinge', id: '7FD' }),
netRegexFr: NetRegexes.ability({ source: 'Aile-De-Foudre', id: '7FD' }),
netRegexJa: NetRegexes.ability({ source: 'サンダーウィング', id: '7FD' }),
netRegexCn: NetRegexes.ability({ source: '雷翼', id: '7FD' }),
netRegexKo: NetRegexes.ability({ source: '번개날개', id: '7FD' }),
condition: Conditions.targetIsYou(),
alarmText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Thunder on YOU',
de: 'Blitz auf DIR',
fr: 'Foudre sur VOUS',
ja: '自分にサンダー',
cn: '雷点名',
ko: '번개 대상자',
},
},
},
{
id: 'T9 Dragon Safe Zone',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0014', capture: false }),
delaySeconds: 3,
durationSeconds: 6,
suppressSeconds: 20,
infoText: (data, _matches, output) => output.safeZone!({ dir: output[data.safeZone ?? 'unknown']!() }),
outputStrings: {
...diveDirections,
safeZone: {
en: 'Safe zone: ${dir}',
de: 'Sichere Zone: ${dir}',
fr: 'Zone sûre : ${dir}',
ja: '安置: ${dir}',
cn: '安全点在:${dir}',
ko: '안전 지대: ${dir}',
},
},
},
{
id: 'T9 Dragon Marker',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0014' }),
condition: Conditions.targetIsYou(),
alarmText: (data, matches, output) => {
data.naelDiveMarkerCount ??= 0;
if (matches.target !== data.me)
return;
const marker = ['A', 'B', 'C'][data.naelDiveMarkerCount];
const dir = data.naelMarks?.[data.naelDiveMarkerCount];
return output.goToMarkerInDir!({ marker: marker, dir: dir });
},
tts: (data, matches, output) => {
data.naelDiveMarkerCount ??= 0;
if (matches.target !== data.me)
return;
return output.goToMarker!({ marker: ['A', 'B', 'C'][data.naelDiveMarkerCount] });
},
outputStrings: {
goToMarkerInDir: {
en: 'Go To ${marker} (in ${dir})',
de: 'Gehe zu ${marker} (im ${dir})',
fr: 'Allez en ${marker} (au ${dir})',
ja: '${marker}に行く' + ' (あと ${dir}秒)',
cn: '去${marker} (在 ${dir}秒)',
ko: '${marker}로 이동' + ' (${dir}쪽)',
},
goToMarker: {
en: 'Go To ${marker}',
de: 'Gehe zu ${marker}',
fr: 'Allez en ${marker}',
ja: '${marker}行くよ',
cn: '去${marker}',
ko: '${marker}로 이동',
},
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Astral Debris': 'Lichtgestein',
'Dalamud Fragment': 'Dalamud-Bruchstück',
'Dalamud Spawn': 'Dalamud-Golem',
'Firehorn': 'Feuerhorn',
'Iceclaw': 'Eisklaue',
'Nael Geminus': 'Nael Geminus',
'Nael deus Darnus': 'Nael deus Darnus',
'Ragnarok': 'Ragnarök',
'The Ghost Of Meracydia': 'Geist von Meracydia',
'Thunderwing': 'Donnerschwinge',
'Umbral Debris': 'Schattengestein',
},
'replaceText': {
'(?<! )Meteor(?! Stream)': 'Meteor',
'Bahamut\'s Claw': 'Klauen Bahamuts',
'Bahamut\'s Favor': 'Bahamuts Segen',
'Binding Coil': 'Verschlungene Schatten',
'Cauterize': 'Kauterisieren',
'Chain Lightning': 'Kettenblitz',
'Dalamud Dive': 'Dalamud-Sturzflug',
'Divebomb': 'Sturzbombe',
'Fireball': 'Feuerball',
'Ghost': 'Geist',
'Golem Meteors': 'Golem Meteore',
'Heavensfall': 'Himmelssturz',
'Iron Chariot': 'Eiserner Streitwagen',
'Lunar Dynamo': 'Lunarer Dynamo',
'Megaflare': 'Megaflare',
'Meteor Stream': 'Meteorflug',
'Raven Dive': 'Bahamuts Schwinge',
'Ravensbeak': 'Bradamante',
'Ravensclaw': 'Silberklauen',
'Stardust': 'Sternenstaub',
'Super Nova': 'Supernova',
'Thermionic Beam': 'Thermionischer Strahl',
},
},
{
'locale': 'fr',
'replaceSync': {
'Astral Debris': 'Débris Astral',
'Dalamud Fragment': 'Débris De Dalamud',
'Dalamud Spawn': 'Golem De Dalamud',
'Firehorn': 'Corne-De-Feu',
'Iceclaw': 'Griffe-De-Glace',
'Nael Geminus': 'Nael Geminus',
'Nael deus Darnus': 'Nael Deus Darnus',
'Ragnarok': 'Ragnarok',
'The Ghost Of Meracydia': 'Fantôme Méracydien',
'Thunderwing': 'Aile-De-Foudre',
'Umbral Debris': 'Débris Ombral',
},
'replaceText': {
'(?<! )Meteor(?! Stream)': 'Météore',
'Bahamut\'s Claw': 'Griffe de Bahamut',
'Bahamut\'s Favor': 'Auspice du dragon',
'Binding Coil': 'Écheveau entravant',
'Cauterize': 'Cautérisation',
'Chain Lightning': 'Chaîne d\'éclairs',
'Dalamud Dive': 'Chute de Dalamud',
'Divebomb Mark': 'Bombe plongeante, marque',
'Fireball': 'Boule de feu',
'Ghost Add': 'Add Fantôme',
'Golem Meteors': 'Golem de Dalamud',
'Heavensfall': 'Destruction universelle',
'Iron Chariot': 'Char de fer',
'Lunar Dynamo': 'Dynamo lunaire',
'Megaflare': 'MégaBrasier',
'Meteor Stream': 'Rayon météore',
'Raven Dive': 'Fonte du rapace',
'Ravensbeak': 'Bec du rapace',
'Ravensclaw': 'Serre du rapace',
'Stardust': 'Poussière d\'étoile',
'Super Nova': 'Supernova',
'Thermionic Beam': 'Rayon thermoïonique',
},
},
{
'locale': 'ja',
'replaceSync': {
'Astral Debris': 'アストラルデブリ',
'Dalamud Fragment': 'ダラガブデブリ',
'Dalamud Spawn': 'ダラガブゴーレム',
'Firehorn': 'ファイアホーン',
'Iceclaw': 'アイスクロウ',
'Nael Geminus': 'ネール・ジェミナス',
'Nael deus Darnus': 'ネール・デウス・ダーナス',
'Ragnarok': 'ラグナロク',
'The Ghost Of Meracydia': 'メラシディアン・ゴースト',
'Thunderwing': 'サンダーウィング',
'Umbral Debris': 'アンブラルデブリ',
},
'replaceText': {
'(?<! )Meteor(?! Stream)': 'メテオ',
'Bahamut\'s Claw': 'バハムートクロウ',
'Bahamut\'s Favor': '龍神の加護',
'Binding Coil': 'バインディングコイル',
'Cauterize': 'カータライズ',
'Chain Lightning': 'チェインライトニング',
'Dalamud Dive': 'ダラガブダイブ',
'Divebomb': 'ダイブボム',
'Fireball': 'ファイアボール',
'Ghost Add': '雑魚: ゴースト',
'Golem Meteors': 'ゴーレムメテオ',
'Heavensfall': '天地崩壊',
'Iron Chariot': 'アイアンチャリオット',
'Lunar Dynamo': 'ルナダイナモ',
'(?<= )Mark(?= \\w)': 'マーク',
'Megaflare': 'メガフレア',
'Meteor Stream': 'メテオストリーム',
'Raven Dive': 'レイヴンダイブ',
'Ravensbeak': 'レイヴェンズビーク',
'Ravensclaw': 'レイヴェンズクロウ',
'Stardust': 'スターダスト',
'Super Nova': 'スーパーノヴァ',
'Thermionic Beam': 'サーミオニックビーム',
},
},
{
'locale': 'cn',
'replaceSync': {
'Astral Debris': '星极岩屑',
'Dalamud Fragment': '卫月岩屑',
'Dalamud Spawn': '卫月巨像',
'Firehorn': '火角',
'Iceclaw': '冰爪',
'Nael Geminus': '奈尔双生子',
'Nael deus Darnus': '奈尔·神·达纳斯',
'Ragnarok': '诸神黄昏',
'The Ghost Of Meracydia': '美拉西迪亚幽龙',
'Thunderwing': '雷翼',
'Umbral Debris': '灵极岩屑',
},
'replaceText': {
'(?<! )Meteor(?! Stream)': '陨石',
'Bahamut\'s Claw': '巴哈姆特之爪',
'Bahamut\'s Favor': '龙神的加护',
'Binding Coil': '拘束圈',
'Cauterize': '低温俯冲',
'Chain Lightning': '雷光链',
'Dalamud Dive': '月华冲',
'Divebomb': '爆破俯冲',
'Fireball': '烈火球',
'Ghost': '幽灵',
'Golem Meteors': '石头人陨石',
'Heavensfall': '天崩地裂',
'Iron Chariot': '钢铁战车',
'Lunar Dynamo': '月流电圈',
'Megaflare': '百万核爆',
'Meteor Stream': '陨石流',
'Raven Dive': '凶鸟冲',
'Ravensbeak': '凶鸟尖喙',
'Ravensclaw': '凶鸟利爪',
'Stardust': '星尘',
'Super Nova': '超新星',
'Thermionic Beam': '热离子光束',
},
},
{
'locale': 'ko',
'replaceSync': {
'Astral Debris': '천상의 잔해',
'Dalamud Fragment': '달라가브의 잔해',
'Dalamud Spawn': '달라가브 골렘',
'Firehorn': '화염뿔',
'Iceclaw': '얼음발톱',
'Nael Geminus': '넬 게미누스',
'Nael deus Darnus': '넬 데우스 다르누스',
'Ragnarok': '라그나로크',
'The Ghost Of Meracydia': '메라시디아의 유령',
'Thunderwing': '번개날개',
'Umbral Debris': '저승의 잔해',
},
'replaceText': {
'(?<! )Meteor(?! Stream)': '메테오',
'Bahamut\'s Claw': '바하무트의 발톱',
'Bahamut\'s Favor': '용신의 가호',
'Binding Coil': '구속의 고리',
'Cauterize': '인두질',
'Chain Lightning': '번개 사슬',
'Dalamud Dive': '달라가브 강하',
'Divebomb': '급강하 폭격',
'Fireball': '화염구',
'Ghost Add': '유령 쫄',
'Golem Meteors': '골렘 메테오',
'Heavensfall': '천지붕괴',
'Iron Chariot': '강철 전차',
'Lunar Dynamo': '달의 원동력',
'Megaflare': '메가플레어',
'Meteor Stream': '유성 폭풍',
'Raven Dive': '흉조의 강하',
'Ravensbeak': '흉조의 부리',
'Ravensclaw': '흉조의 발톱',
'Stardust': '별조각',
'Super Nova': '초신성',
'Thermionic Beam': '열전자 광선',
'Mark A': 'A징',
'Mark B': 'B징',
},
},
],
};
export default triggerSet; | the_stack |
import { AbortController } from "@aws-sdk/abort-controller";
import { HttpRequest } from "@aws-sdk/protocol-http";
import { Server as HttpServer } from "http";
import http from "http";
import { Server as HttpsServer } from "https";
import https from "https";
import { AddressInfo } from "net";
import { NodeHttpHandler } from "./node-http-handler";
import { ReadFromBuffers } from "./readable.mock";
import {
createContinueResponseFunction,
createMockHttpServer,
createMockHttpsServer,
createResponseFunction,
} from "./server.mock";
describe("NodeHttpHandler", () => {
describe("constructor", () => {
it("sets keepAlive=true by default", () => {
const nodeHttpHandler = new NodeHttpHandler();
expect((nodeHttpHandler as any).httpAgent.keepAlive).toEqual(true);
});
it("sets maxSockets=50 by default", () => {
const nodeHttpHandler = new NodeHttpHandler();
expect((nodeHttpHandler as any).httpAgent.maxSockets).toEqual(50);
});
it("can set httpAgent and httpsAgent", () => {
let keepAlive = false;
let maxSockets = Math.round(Math.random() * 50) + 1;
let nodeHttpHandler = new NodeHttpHandler({
httpAgent: new http.Agent({ keepAlive, maxSockets }),
});
expect((nodeHttpHandler as any).httpAgent.keepAlive).toEqual(keepAlive);
expect((nodeHttpHandler as any).httpAgent.maxSockets).toEqual(maxSockets);
keepAlive = true;
maxSockets = Math.round(Math.random() * 50) + 1;
nodeHttpHandler = new NodeHttpHandler({
httpsAgent: new https.Agent({ keepAlive, maxSockets }),
});
expect((nodeHttpHandler as any).httpsAgent.keepAlive).toEqual(keepAlive);
expect((nodeHttpHandler as any).httpsAgent.maxSockets).toEqual(maxSockets);
});
});
describe("http", () => {
const mockHttpServer: HttpServer = createMockHttpServer().listen(54321);
afterEach(() => {
mockHttpServer.removeAllListeners("request");
mockHttpServer.removeAllListeners("checkContinue");
});
afterAll(() => {
mockHttpServer.close();
});
it("has metadata", () => {
const nodeHttpHandler = new NodeHttpHandler();
expect(nodeHttpHandler.metadata.handlerProtocol).toContain("http/1.1");
});
it("can send http requests", async () => {
const mockResponse = {
statusCode: 200,
headers: {},
body: "test",
};
mockHttpServer.addListener("request", createResponseFunction(mockResponse));
const nodeHttpHandler = new NodeHttpHandler();
const { response } = await nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "GET",
port: (mockHttpServer.address() as AddressInfo).port,
protocol: "http:",
path: "/",
headers: {},
}),
{}
);
expect(response.statusCode).toEqual(mockResponse.statusCode);
expect(response.headers).toBeDefined();
expect(response.headers).toMatchObject(mockResponse.headers);
expect(response.body).toBeDefined();
});
it("can send requests with bodies", async () => {
const body = Buffer.from("test");
const mockResponse = {
statusCode: 200,
headers: {},
};
mockHttpServer.addListener("request", createResponseFunction(mockResponse));
const spy = jest.spyOn(http, "request").mockImplementationOnce(() => {
const calls = spy.mock.calls;
const currentIndex = calls.length - 1;
return http.request(calls[currentIndex][0], calls[currentIndex][1]);
});
const nodeHttpHandler = new NodeHttpHandler();
const { response } = await nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "PUT",
port: (mockHttpServer.address() as AddressInfo).port,
protocol: "http:",
path: "/",
headers: {},
body,
}),
{}
);
expect(response.statusCode).toEqual(mockResponse.statusCode);
expect(response.headers).toBeDefined();
expect(response.headers).toMatchObject(mockResponse.headers);
});
it("can handle expect 100-continue", async () => {
const body = Buffer.from("test");
const mockResponse = {
statusCode: 200,
headers: {},
};
mockHttpServer.addListener("checkContinue", createContinueResponseFunction(mockResponse));
let endSpy: jest.SpyInstance<any>;
let continueWasTriggered = false;
const spy = jest.spyOn(http, "request").mockImplementationOnce(() => {
const calls = spy.mock.calls;
const currentIndex = calls.length - 1;
const request = http.request(calls[currentIndex][0], calls[currentIndex][1]);
request.on("continue", () => {
continueWasTriggered = true;
});
endSpy = jest.spyOn(request, "end");
return request;
});
const nodeHttpHandler = new NodeHttpHandler();
const { response } = await nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "PUT",
port: (mockHttpServer.address() as AddressInfo).port,
protocol: "http:",
path: "/",
headers: {
Expect: "100-continue",
},
body,
}),
{}
);
expect(response.statusCode).toEqual(mockResponse.statusCode);
expect(response.headers).toBeDefined();
expect(response.headers).toMatchObject(mockResponse.headers);
expect(endSpy!.mock.calls.length).toBe(1);
expect(endSpy!.mock.calls[0][0]).toStrictEqual(body);
expect(continueWasTriggered).toBe(true);
});
it("can send requests with streaming bodies", async () => {
const body = new ReadFromBuffers({
buffers: [Buffer.from("t"), Buffer.from("e"), Buffer.from("s"), Buffer.from("t")],
});
const inputBodySpy = jest.spyOn(body, "pipe");
const mockResponse = {
statusCode: 200,
headers: {},
};
mockHttpServer.addListener("request", createResponseFunction(mockResponse));
const nodeHttpHandler = new NodeHttpHandler();
const { response } = await nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "PUT",
port: (mockHttpServer.address() as AddressInfo).port,
protocol: "http:",
path: "/",
headers: {},
body,
}),
{}
);
expect(response.statusCode).toEqual(mockResponse.statusCode);
expect(response.headers).toBeDefined();
expect(response.headers).toMatchObject(mockResponse.headers);
expect(inputBodySpy.mock.calls.length).toBeTruthy();
});
it("can send requests with Uint8Array bodies", async () => {
const body = Buffer.from([0, 1, 2, 3]);
const mockResponse = {
statusCode: 200,
headers: {},
};
mockHttpServer.addListener("request", createResponseFunction(mockResponse));
let endSpy: jest.SpyInstance<any>;
const spy = jest.spyOn(http, "request").mockImplementationOnce(() => {
const calls = spy.mock.calls;
const currentIndex = calls.length - 1;
const request = http.request(calls[currentIndex][0], calls[currentIndex][1]);
endSpy = jest.spyOn(request, "end");
return request;
});
const nodeHttpHandler = new NodeHttpHandler();
const { response } = await nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "PUT",
port: (mockHttpServer.address() as AddressInfo).port,
protocol: "http:",
path: "/",
headers: {},
body,
}),
{}
);
expect(response.statusCode).toEqual(mockResponse.statusCode);
expect(response.headers).toBeDefined();
expect(response.headers).toMatchObject(mockResponse.headers);
expect(endSpy!.mock.calls.length).toBe(1);
expect(endSpy!.mock.calls[0][0]).toStrictEqual(body);
});
});
describe("https", () => {
const mockHttpsServer: HttpsServer = createMockHttpsServer().listen(54322);
/*beforeEach(() => {
// Setting the NODE_TLS_REJECT_UNAUTHORIZED will allow the unconfigurable
// HTTPS client in getCertificate to skip cert validation, which the
// self-signed cert used for this test's server would fail. The variable
// will be reset to its original value at the end of the test.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
});*/
afterEach(() => {
mockHttpsServer.removeAllListeners("request");
mockHttpsServer.removeAllListeners("checkContinue");
//process.env.NODE_TLS_REJECT_UNAUTHORIZED = rejectUnauthorizedEnv;
});
afterAll(() => {
mockHttpsServer.close();
});
/*it("can send https requests", async () => {
const mockResponse = {
statusCode: 200,
headers: {},
body: "test"
};
mockHttpsServer.addListener(
"request",
createResponseFunction(mockResponse)
);
const nodeHttpHandler = new NodeHttpHandler();
let { response } = await nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "GET",
port: (mockHttpsServer.address() as AddressInfo).port,
protocol: "https:",
path: "/",
headers: {}
}),
{}
);
expect(response.statusCode).toEqual(mockResponse.statusCode);
expect(response.headers).toBeDefined();
expect(response.headers).toMatchObject(mockResponse.headers);
expect(response.body).toBeDefined();
});
it("can send requests with bodies", async () => {
const body = Buffer.from("test");
const mockResponse = {
statusCode: 200,
headers: {}
};
mockHttpsServer.addListener(
"request",
createResponseFunction(mockResponse)
);
const spy = jest.spyOn(https, "request").mockImplementationOnce(() => {
let calls = spy.mock.calls;
let currentIndex = calls.length - 1;
return https.request(calls[currentIndex][0], calls[currentIndex][1]);
});
const nodeHttpHandler = new NodeHttpHandler();
let { response } = await nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "PUT",
port: (mockHttpsServer.address() as AddressInfo).port,
protocol: "https:",
path: "/",
headers: {},
body
}),
{}
);
expect(response.statusCode).toEqual(mockResponse.statusCode);
expect(response.headers).toBeDefined();
expect(response.headers).toMatchObject(mockResponse.headers);
});
it("can handle expect 100-continue", async () => {
const body = Buffer.from("test");
const mockResponse = {
statusCode: 200,
headers: {}
};
mockHttpsServer.addListener(
"checkContinue",
createContinueResponseFunction(mockResponse)
);
let endSpy: jest.SpyInstance<any>;
let continueWasTriggered = false;
const spy = jest.spyOn(https, "request").mockImplementationOnce(() => {
let calls = spy.mock.calls;
let currentIndex = calls.length - 1;
const request = https.request(
calls[currentIndex][0],
calls[currentIndex][1]
);
request.on("continue", () => {
continueWasTriggered = true;
});
endSpy = jest.spyOn(request, "end");
return request;
});
const nodeHttpHandler = new NodeHttpHandler();
let response = await nodeHttpHandler.handle(
{
hostname: "localhost",
method: "PUT",
port: (mockHttpServer.address() as AddressInfo).port,
protocol: "https:",
path: "/",
headers: {
Expect: "100-continue"
},
body
},
{}
);
expect(response.statusCode).toEqual(mockResponse.statusCode);
expect(response.headers).toBeDefined();
expect(response.headers).toMatchObject(mockResponse.headers);
expect(endSpy!.mock.calls.length).toBe(1);
expect(endSpy!.mock.calls[0][0]).toBe(body);
expect(continueWasTriggered).toBe(true);
});
it("can send requests with streaming bodies", async () => {
const body = new ReadFromBuffers({
buffers: [
Buffer.from("t"),
Buffer.from("e"),
Buffer.from("s"),
Buffer.from("t")
]
});
let inputBodySpy = jest.spyOn(body, "pipe");
const mockResponse = {
statusCode: 200,
headers: {}
};
mockHttpsServer.addListener(
"request",
createResponseFunction(mockResponse)
);
const nodeHttpHandler = new NodeHttpHandler();
let { response } = await nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "PUT",
port: (mockHttpsServer.address() as AddressInfo).port,
protocol: "https:",
path: "/",
headers: {},
body
}),
{}
);
expect(response.statusCode).toEqual(mockResponse.statusCode);
expect(response.headers).toBeDefined();
expect(response.headers).toMatchObject(mockResponse.headers);
expect(inputBodySpy.mock.calls.length).toBeTruthy();
});*/
it("rejects if the request encounters an error", async () => {
const mockResponse = {
statusCode: 200,
headers: {},
body: "test",
};
mockHttpsServer.addListener("request", createResponseFunction(mockResponse));
const nodeHttpHandler = new NodeHttpHandler();
await expect(
nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "GET",
port: (mockHttpsServer.address() as AddressInfo).port,
protocol: "fake:", // trigger a request error
path: "/",
headers: {},
}),
{}
)
).rejects.toHaveProperty("message");
});
it("will not make request if already aborted", async () => {
const mockResponse = {
statusCode: 200,
headers: {},
body: "test",
};
mockHttpsServer.addListener("request", createResponseFunction(mockResponse));
const spy = jest.spyOn(https, "request").mockImplementationOnce(() => {
const calls = spy.mock.calls;
const currentIndex = calls.length - 1;
return https.request(calls[currentIndex][0], calls[currentIndex][1]);
});
// clear data held from previous tests
spy.mockClear();
const nodeHttpHandler = new NodeHttpHandler();
await expect(
nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "GET",
port: (mockHttpsServer.address() as AddressInfo).port,
protocol: "https:",
path: "/",
headers: {},
}),
{
abortSignal: {
aborted: true,
onabort: null,
},
}
)
).rejects.toHaveProperty("name", "AbortError");
expect(spy.mock.calls.length).toBe(0);
});
it("will destroy the request when aborted", async () => {
const mockResponse = {
statusCode: 200,
headers: {},
body: "test",
};
mockHttpsServer.addListener("request", createResponseFunction(mockResponse));
let httpRequest: http.ClientRequest;
let reqAbortSpy: any;
const spy = jest.spyOn(https, "request").mockImplementationOnce(() => {
const calls = spy.mock.calls;
const currentIndex = calls.length - 1;
httpRequest = https.request(calls[currentIndex][0], calls[currentIndex][1]);
reqAbortSpy = jest.spyOn(httpRequest, "abort");
return httpRequest;
});
const nodeHttpHandler = new NodeHttpHandler();
const abortController = new AbortController();
setTimeout(() => {
abortController.abort();
}, 0);
await expect(
nodeHttpHandler.handle(
new HttpRequest({
hostname: "localhost",
method: "GET",
port: (mockHttpsServer.address() as AddressInfo).port,
protocol: "https:",
path: "/",
headers: {},
}),
{
abortSignal: abortController.signal,
}
)
).rejects.toHaveProperty("name", "AbortError");
expect(reqAbortSpy.mock.calls.length).toBe(1);
});
});
describe("#destroy", () => {
it("should be callable and return nothing", () => {
const nodeHttpHandler = new NodeHttpHandler();
expect(nodeHttpHandler.destroy()).toBeUndefined();
});
});
}); | the_stack |
import * as path from "path";
import { TreeItem, TreeItemCollapsibleState, Command, TextEditor, TreeView, ProviderResult } from "vscode";
import { AntlrTreeDataProvider } from "./AntlrTreeDataProvider";
import { LexicalRange, CodeActionType } from "../backend/facade";
import { Utils, RangeHolder } from "./Utils";
export class RootEntry extends TreeItem {
public contextValue = "actions";
public constructor(label: string, id: string) {
super(label, TreeItemCollapsibleState.Expanded);
this.id = id;
}
}
export class ChildEntry extends TreeItem implements RangeHolder {
private static imageBaseNames: Map<CodeActionType, string> = new Map([
[CodeActionType.GlobalNamed, "named-action"],
[CodeActionType.LocalNamed, "named-action"],
[CodeActionType.ParserAction, "parser-action"],
[CodeActionType.LexerAction, "parser-action"],
[CodeActionType.ParserPredicate, "predicate"],
[CodeActionType.LexerPredicate, "predicate"],
]);
public contextValue = "action";
public constructor(
public readonly parent: RootEntry,
label: string,
type: CodeActionType,
public readonly range?: LexicalRange,
command?: Command) {
super(label, TreeItemCollapsibleState.None);
this.command = command;
const baseName = ChildEntry.imageBaseNames.get(type);
if (baseName) {
this.contextValue = baseName;
this.iconPath = {
light: path.join(__dirname, "..", "..", "..", "misc", baseName + "-light.svg"),
dark: path.join(__dirname, "..", "..", "..", "misc", baseName + "-dark.svg"),
};
}
}
}
export class ActionsProvider extends AntlrTreeDataProvider<TreeItem> {
public actionTree: TreeView<TreeItem>;
private globalNamedActionsRoot: RootEntry;
private localNamedActionsRoot: RootEntry;
private parserActionsRoot: RootEntry;
private lexerActionsRoot: RootEntry;
private parserPredicatesRoot: RootEntry;
private lexerPredicatesRoot: RootEntry;
private globalNamedActions: ChildEntry[] = [];
private localNamedActions: ChildEntry[] = [];
private parserActions: ChildEntry[] = [];
private lexerActions: ChildEntry[] = [];
private parserPredicates: ChildEntry[] = [];
private lexerPredicates: ChildEntry[] = [];
public update(editor: TextEditor): void {
const position = editor.selection.active;
let action = Utils.findInListFromPosition(this.globalNamedActions, position.character, position.line + 1);
if (!action) {
action = Utils.findInListFromPosition(this.localNamedActions, position.character, position.line + 1);
}
if (!action) {
action = Utils.findInListFromPosition(this.parserActions, position.character, position.line + 1);
}
if (!action) {
action = Utils.findInListFromPosition(this.lexerActions, position.character, position.line + 1);
}
if (!action) {
action = Utils.findInListFromPosition(this.parserPredicates, position.character, position.line + 1);
}
if (!action) {
action = Utils.findInListFromPosition(this.lexerPredicates, position.character, position.line + 1);
}
if (action) {
void this.actionTree.reveal(action, { select: true });
}
}
public getParent?(element: TreeItem): ProviderResult<TreeItem> {
if (element instanceof RootEntry) {
return undefined;
}
return (element as ChildEntry).parent;
}
public getChildren(element?: TreeItem): ProviderResult<TreeItem[]> {
if (!this.currentFile) {
return null;
}
if (!element) {
return this.createRootEntries();
}
return new Promise((resolve, reject) => {
if (!this.currentFile) {
resolve(undefined);
return;
}
try {
let listType: CodeActionType;
let parent: RootEntry;
let list: ChildEntry[];
switch (element.id) {
case "parserActions": {
this.parserActions = [];
list = this.parserActions;
listType = CodeActionType.ParserAction;
parent = this.parserActionsRoot;
break;
}
case "lexerActions": {
this.lexerActions = [];
list = this.lexerActions;
listType = CodeActionType.LexerAction;
parent = this.lexerActionsRoot;
break;
}
case "parserPredicates": {
this.parserPredicates = [];
list = this.parserPredicates;
listType = CodeActionType.ParserPredicate;
parent = this.parserPredicatesRoot;
break;
}
case "lexerPredicates": {
this.lexerPredicates = [];
list = this.lexerPredicates;
listType = CodeActionType.LexerPredicate;
parent = this.lexerPredicatesRoot;
break;
}
case "globalNamedActions": {
this.globalNamedActions = [];
list = this.globalNamedActions;
listType = CodeActionType.GlobalNamed;
parent = this.globalNamedActionsRoot;
break;
}
default: {
this.localNamedActions = [];
list = this.localNamedActions;
listType = CodeActionType.LocalNamed;
parent = this.localNamedActionsRoot;
break;
}
}
const actions = this.backend.listActions(this.currentFile, listType);
actions.forEach((action, index) => {
let caption = action.name.length > 0 ? action.name : String(index);
if (action.description) {
if (action.description.includes("\n")) {
caption += ": <multi line block>";
} else {
caption += ": " + action.description;
}
}
const range = action && action.definition ? action.definition.range : undefined;
const command = action ? {
title: "Select Grammar Range",
command: "antlr.selectGrammarRange",
arguments: [range],
} : undefined;
const item = new ChildEntry(parent, caption.trim(), listType, range, command);
list.push(item);
});
resolve(list);
} catch (e) {
reject(e);
}
});
}
/**
* Generates the root entries for the actions treeview.
*
* @returns A promise resolving to a list of root tree items.
*/
private createRootEntries(): ProviderResult<TreeItem[]> {
return new Promise((resolve, reject) => {
if (!this.currentFile) {
return null;
}
try {
const rootList: RootEntry[] = [];
const counts = this.backend.getActionCounts(this.currentFile);
if ((counts.get(CodeActionType.GlobalNamed) ?? 0) > 0) {
this.globalNamedActionsRoot = new RootEntry("Global Named Actions", "globalNamedActions");
this.globalNamedActionsRoot.tooltip = "Code which is embedded into the generated files " +
"at specific locations (like the head of the file).\n\n" +
"This code does not take part in the parsing process and is not represented in the ATN.";
rootList.push(this.globalNamedActionsRoot);
}
if ((counts.get(CodeActionType.LocalNamed) ?? 0) > 0) {
this.localNamedActionsRoot = new RootEntry("Local Named Actions", "localNamedActions");
this.localNamedActionsRoot.tooltip = "Code which is embedded into the generated parser code " +
"for a rule, like initialization code (@init). \n\n" +
"This code is directly executed during the parsing process, but is not represented in the ATN.";
rootList.push(this.localNamedActionsRoot);
}
if ((counts.get(CodeActionType.ParserAction) ?? 0) > 0) {
this.parserActionsRoot = new RootEntry("Parser Actions", "parserActions");
this.parserActionsRoot.tooltip = "Code which is embedded into the generated parser " +
"code and executed as part of the parsing process. There are also transitions in the ATN for " +
"each action, but they are not used from the generated parser (all action indices are -1).";
rootList.push(this.parserActionsRoot);
}
if ((counts.get(CodeActionType.LexerAction) ?? 0) > 0) {
this.lexerActionsRoot = new RootEntry("Lexer Actions", "lexerActions");
this.lexerActionsRoot.tooltip = "Lexer rules are executed in a state machine without " +
"any embedded code. However lexer actions are held in generated private methods addressed " +
"by an action index given in the action transition between 2 ATN nodes.";
rootList.push(this.lexerActionsRoot);
}
if ((counts.get(CodeActionType.ParserPredicate) ?? 0) > 0) {
this.parserPredicatesRoot = new RootEntry("Parser Predicates", "parserPredicates");
this.parserPredicatesRoot.tooltip = "Semantic predicates are code snippets which can enable or " +
"disable a specific alternative in a rule. They are generated in separate methods and are " +
"addressed by an index just like lexer actions.\n\n" +
"The ATN representation of a predicate is a predicate transition between 2 ATN nodes.";
rootList.push(this.parserPredicatesRoot);
}
if ((counts.get(CodeActionType.LexerPredicate) ?? 0) > 0) {
this.lexerPredicatesRoot = new RootEntry("Lexer Predicates", "lexerPredicates");
this.lexerPredicatesRoot.tooltip = "Semantic predicates are code snippets which can enable or " +
"disable a specific alternative in a rule. They are generated in separate methods and are " +
"addressed by an index just like lexer actions.\n\n" +
"The ATN representation of a predicate is a predicate transition between 2 ATN nodes.";
rootList.push(this.lexerPredicatesRoot);
}
resolve(rootList);
} catch (e) {
reject(e);
}
});
}
} | the_stack |
import * as Expr from "./Expression";
import { Token, Identifier, Location, Lexeme } from "../lexer";
import { BrsType, BrsInvalid } from "../brsTypes";
import { InvalidZone } from "luxon";
import { AstNode } from "./AstNode";
/** A set of reasons why a `Block` stopped executing. */
export * from "./BlockEndReason";
export interface Visitor<T> {
visitAssignment(statement: Assignment): BrsType;
visitDim(statement: Dim): BrsType;
visitExpression(statement: Expression): BrsType;
visitExitFor(statement: ExitFor): never;
visitExitWhile(statement: ExitWhile): never;
visitPrint(statement: Print): BrsType;
visitIf(statement: If): BrsType;
visitBlock(block: Block): BrsType;
visitFor(statement: For): BrsType;
visitForEach(statement: ForEach): BrsType;
visitWhile(statement: While): BrsType;
visitNamedFunction(statement: Function): BrsType;
visitReturn(statement: Return): never;
visitDottedSet(statement: DottedSet): BrsType;
visitIndexedSet(statement: IndexedSet): BrsType;
visitIncrement(expression: Increment): BrsInvalid;
visitLibrary(statement: Library): BrsInvalid;
}
let statementTypes = new Set<string>([
"Assignment",
"Expression",
"ExitFor",
"ExitWhile",
"Print",
"If",
"Block",
"For",
"ForEach",
"While",
"Stmt_Function",
"Return",
"DottedSet",
"IndexedSet",
"Increment",
"Library",
"Dim",
]);
/**
* Returns a boolean of whether or not the given object is a Statement.
* @param obj object to check
*/
export function isStatement(obj: Expr.Expression | Statement): obj is Statement {
return statementTypes.has(obj.type);
}
/** A BrightScript statement */
export interface Statement extends AstNode {
/**
* Handles the enclosing `Statement` with `visitor`.
* @param visitor the `Visitor` that will handle the enclosing `Statement`
* @returns a BrightScript value (typically `invalid`) and the reason why
* the statement exited (typically `StopReason.End`)
*/
accept<R>(visitor: Visitor<R>): BrsType;
}
export class Assignment extends AstNode implements Statement {
constructor(
readonly tokens: {
equals: Token;
},
readonly name: Identifier,
readonly value: Expr.Expression
) {
super("Assignment");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitAssignment(this);
}
get location() {
return {
file: this.name.location.file,
start: this.name.location.start,
end: this.value.location.end,
};
}
}
export class Dim extends AstNode implements Statement {
constructor(
readonly tokens: {
dim: Token;
closingBrace: Token;
},
readonly name: Identifier,
readonly dimensions: Expr.Expression[]
) {
super("Dim");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitDim(this);
}
get location() {
return {
file: this.tokens.dim.location.file,
start: this.tokens.dim.location.start,
end: this.tokens.closingBrace.location.end,
};
}
}
export class Block extends AstNode implements Statement {
constructor(readonly statements: ReadonlyArray<Statement>, readonly location: Location) {
super("Block");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitBlock(this);
}
}
export class Expression extends AstNode implements Statement {
constructor(readonly expression: Expr.Expression) {
super("Expression");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitExpression(this);
}
get location() {
return this.expression.location;
}
}
export class ExitFor extends AstNode implements Statement {
constructor(
readonly tokens: {
exitFor: Token;
}
) {
super("ExitFor");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitExitFor(this);
}
get location() {
return this.tokens.exitFor.location;
}
}
export class ExitWhile extends AstNode implements Statement {
constructor(
readonly tokens: {
exitWhile: Token;
}
) {
super("ExitWhile");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitExitWhile(this);
}
get location() {
return this.tokens.exitWhile.location;
}
}
export class Function extends AstNode implements Statement {
constructor(readonly name: Identifier, readonly func: Expr.Function) {
super("Stmt_Function");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitNamedFunction(this);
}
get location() {
return {
file: this.name.location.file,
start: this.func.location.start,
end: this.func.location.end,
};
}
}
export interface ElseIf {
condition: Expr.Expression;
thenBranch: Block;
/** Signal to ESLint to walk condition and thenBranch */
type: string;
}
export class If extends AstNode implements Statement {
constructor(
readonly tokens: {
if: Token;
then?: Token;
// TODO: figure a decent way to represent the if/then + elseif/then pairs to enable a
// linter to check for the lack of `then` with this AST. maybe copy ESTree's format?
elseIfs?: Token[];
else?: Token;
endIf?: Token;
},
readonly condition: Expr.Expression,
readonly thenBranch: Block,
readonly elseIfs: ElseIf[],
readonly elseBranch?: Block
) {
super("If");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitIf(this);
}
private getEndLocation(): Location {
if (this.tokens.endIf) {
return this.tokens.endIf.location;
} else if (this.elseBranch) {
return this.elseBranch.location;
} else if (this.elseIfs.length) {
return this.elseIfs[this.elseIfs.length - 1].thenBranch.location;
} else {
return this.thenBranch.location;
}
}
get location() {
return {
file: this.tokens.if.location.file,
start: this.tokens.if.location.start,
end: this.getEndLocation().end,
};
}
}
export class Increment extends AstNode implements Statement {
constructor(readonly value: Expr.Expression, readonly token: Token) {
super("Increment");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitIncrement(this);
}
get location() {
return {
file: this.value.location.file,
start: this.value.location.start,
end: this.token.location.end,
};
}
}
/** The set of all accepted `print` statement separators. */
export namespace PrintSeparator {
/** Used to indent the current `print` position to the next 16-character-width output zone. */
export interface Tab extends Token {
kind: Lexeme.Comma;
}
/** Used to insert a single whitespace character at the current `print` position. */
export interface Space extends Token {
kind: Lexeme.Semicolon;
}
}
/**
* Represents a `print` statement within BrightScript.
*/
export class Print extends AstNode implements Statement {
/**
* Creates a new internal representation of a BrightScript `print` statement.
* @param expressions an array of expressions or `PrintSeparator`s to be
* evaluated and printed.
*/
constructor(
readonly tokens: {
print: Token;
},
readonly expressions: (Expr.Expression | Token)[]
) {
super("Print");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitPrint(this);
}
get location() {
let end = this.expressions.length
? this.expressions[this.expressions.length - 1].location.end
: this.tokens.print.location.end;
return {
file: this.tokens.print.location.file,
start: this.tokens.print.location.start,
end: end,
};
}
}
export class Goto extends AstNode implements Statement {
constructor(
readonly tokens: {
goto: Token;
label: Token;
}
) {
super("Goto");
}
accept<R>(_visitor: Visitor<R>): BrsType {
//should search the code for the corresponding label, and set that as the next line to execute
throw new Error("Not implemented");
}
get location() {
return {
file: this.tokens.goto.location.file,
start: this.tokens.goto.location.start,
end: this.tokens.label.location.end,
};
}
}
export class Label extends AstNode implements Statement {
constructor(
readonly tokens: {
identifier: Token;
colon: Token;
}
) {
super("Label");
}
accept<R>(_visitor: Visitor<R>): BrsType {
throw new Error("Not implemented");
}
get location() {
return {
file: this.tokens.identifier.location.file,
start: this.tokens.identifier.location.start,
end: this.tokens.colon.location.end,
};
}
}
export class Return extends AstNode implements Statement {
constructor(
readonly tokens: {
return: Token;
},
readonly value?: Expr.Expression
) {
super("Return");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitReturn(this);
}
get location() {
return {
file: this.tokens.return.location.file,
start: this.tokens.return.location.start,
end: (this.value && this.value.location.end) || this.tokens.return.location.end,
};
}
}
export class End extends AstNode implements Statement {
constructor(
readonly tokens: {
end: Token;
}
) {
super("End");
}
accept<R>(_visitor: Visitor<R>): BrsType {
//TODO implement this in the runtime. It should immediately terminate program execution, without error
throw new Error("Not implemented");
}
get location() {
return {
file: this.tokens.end.location.file,
start: this.tokens.end.location.start,
end: this.tokens.end.location.end,
};
}
}
export class Stop extends AstNode implements Statement {
constructor(
readonly tokens: {
stop: Token;
}
) {
super("Stop");
}
accept<R>(_visitor: Visitor<R>): BrsType {
//TODO implement this in the runtime. It should pause code execution until a `c` command is issued from the console
throw new Error("Not implemented");
}
get location() {
return {
file: this.tokens.stop.location.file,
start: this.tokens.stop.location.start,
end: this.tokens.stop.location.end,
};
}
}
export class For extends AstNode implements Statement {
constructor(
readonly tokens: {
for: Token;
to: Token;
step?: Token;
endFor: Token;
},
readonly counterDeclaration: Assignment,
readonly finalValue: Expr.Expression,
readonly increment: Expr.Expression,
readonly body: Block
) {
super("For");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitFor(this);
}
get location() {
return {
file: this.tokens.for.location.file,
start: this.tokens.for.location.start,
end: this.tokens.endFor.location.end,
};
}
}
export class ForEach extends AstNode implements Statement {
constructor(
readonly tokens: {
forEach: Token;
in: Token;
endFor: Token;
},
readonly item: Token,
readonly target: Expr.Expression,
readonly body: Block
) {
super("ForEach");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitForEach(this);
}
get location() {
return {
file: this.tokens.forEach.location.file,
start: this.tokens.forEach.location.start,
end: this.tokens.endFor.location.end,
};
}
}
export class While extends AstNode implements Statement {
constructor(
readonly tokens: {
while: Token;
endWhile: Token;
},
readonly condition: Expr.Expression,
readonly body: Block
) {
super("While");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitWhile(this);
}
get location() {
return {
file: this.tokens.while.location.file,
start: this.tokens.while.location.start,
end: this.tokens.endWhile.location.end,
};
}
}
export class DottedSet extends AstNode implements Statement {
constructor(
readonly obj: Expr.Expression,
readonly name: Identifier,
readonly value: Expr.Expression
) {
super("DottedSet");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitDottedSet(this);
}
get location() {
return {
file: this.obj.location.file,
start: this.obj.location.start,
end: this.value.location.end,
};
}
}
export class IndexedSet extends AstNode implements Statement {
constructor(
readonly obj: Expr.Expression,
readonly index: Expr.Expression,
readonly value: Expr.Expression,
readonly closingSquare: Token
) {
super("IndexedSet");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitIndexedSet(this);
}
get location() {
return {
file: this.obj.location.file,
start: this.obj.location.start,
end: this.value.location.end,
};
}
}
export class Library extends AstNode implements Statement {
constructor(
readonly tokens: {
library: Token;
filePath: Token | undefined;
}
) {
super("Library");
}
accept<R>(visitor: Visitor<R>): BrsType {
return visitor.visitLibrary(this);
}
get location() {
return {
file: this.tokens.library.location.file,
start: this.tokens.library.location.start,
end: this.tokens.filePath
? this.tokens.filePath.location.end
: this.tokens.library.location.end,
};
}
} | the_stack |
import assert from 'assert';
import { getLogger, Logger } from 'common/log';
import { randomSelect } from 'common/utils';
import { RemoteMachineConfig } from 'common/experimentConfig';
import { GPUInfo, ScheduleResultType } from '../common/gpuData';
import { ExecutorManager, RemoteMachineMeta, RemoteMachineScheduleResult, RemoteMachineTrialJobDetail } from './remoteMachineData';
type SCHEDULE_POLICY_NAME = 'random' | 'round-robin';
/**
* A simple GPU scheduler implementation
*/
export class GPUScheduler {
private readonly machineExecutorMap: Map<RemoteMachineConfig, ExecutorManager>;
private readonly log: Logger = getLogger('GPUScheduler');
private readonly policyName: SCHEDULE_POLICY_NAME = 'round-robin';
private roundRobinIndex: number = 0;
private configuredRMs: RemoteMachineMeta[] = [];
/**
* Constructor
* @param machineExecutorMap map from remote machine to executor
*/
constructor(machineExecutorMap: Map<RemoteMachineConfig, ExecutorManager>) {
assert(machineExecutorMap.size > 0);
this.machineExecutorMap = machineExecutorMap;
this.configuredRMs = Array.from(machineExecutorMap.values(), manager => manager.rmMeta);
}
/**
* Schedule a machine according to the constraints (requiredGPUNum)
* @param requiredGPUNum required GPU number
*/
public scheduleMachine(requiredGPUNum: number | undefined, trialJobDetail: RemoteMachineTrialJobDetail): RemoteMachineScheduleResult {
if (requiredGPUNum === undefined) {
requiredGPUNum = 0;
}
assert(requiredGPUNum >= 0);
const allRMs: RemoteMachineMeta[] = Array.from(this.machineExecutorMap.values(), manager => manager.rmMeta);
assert(allRMs.length > 0);
// Step 1: Check if required GPU number not exceeds the total GPU number in all machines
const eligibleRM: RemoteMachineMeta[] = allRMs.filter((rmMeta: RemoteMachineMeta) =>
rmMeta.gpuSummary === undefined || requiredGPUNum === 0 || (requiredGPUNum !== undefined && rmMeta.gpuSummary.gpuCount >= requiredGPUNum));
if (eligibleRM.length === 0) {
// If the required gpu number exceeds the upper limit of all machine's GPU number
// Return REQUIRE_EXCEED_TOTAL directly
return ({
resultType: ScheduleResultType.REQUIRE_EXCEED_TOTAL,
scheduleInfo: undefined
});
}
// Step 2: Allocate Host/GPU for specified trial job
// Currenty the requireGPUNum parameter for all trial jobs are identical.
if (requiredGPUNum > 0) {
// Trial job requires GPU
const result: RemoteMachineScheduleResult | undefined = this.scheduleGPUHost(requiredGPUNum, trialJobDetail);
if (result !== undefined) {
return result;
}
} else {
// Trail job does not need GPU
const allocatedRm: RemoteMachineMeta = this.selectMachine(allRMs);
return this.allocateHost(requiredGPUNum, allocatedRm, [], trialJobDetail);
}
this.log.warning(`Scheduler: trialJob id ${trialJobDetail.id}, no machine can be scheduled, return TMP_NO_AVAILABLE_GPU `);
return {
resultType: ScheduleResultType.TMP_NO_AVAILABLE_GPU,
scheduleInfo: undefined
};
}
/**
* remove the job's gpu reversion
*/
public removeGpuReservation(trialJobId: string, trialJobMap: Map<string, RemoteMachineTrialJobDetail>): void {
const trialJobDetail: RemoteMachineTrialJobDetail | undefined = trialJobMap.get(trialJobId);
if (trialJobDetail === undefined) {
throw new Error(`could not get trialJobDetail by id ${trialJobId}`);
}
if (trialJobDetail.rmMeta !== undefined &&
trialJobDetail.rmMeta.occupiedGpuIndexMap !== undefined &&
trialJobDetail.gpuIndices !== undefined &&
trialJobDetail.gpuIndices.length > 0) {
for (const gpuInfo of trialJobDetail.gpuIndices) {
const num: number | undefined = trialJobDetail.rmMeta.occupiedGpuIndexMap.get(gpuInfo.index);
if (num !== undefined) {
if (num === 1) {
trialJobDetail.rmMeta.occupiedGpuIndexMap.delete(gpuInfo.index);
} else {
trialJobDetail.rmMeta.occupiedGpuIndexMap.set(gpuInfo.index, num - 1);
}
}
}
}
trialJobDetail.gpuIndices = [];
trialJobMap.set(trialJobId, trialJobDetail);
}
private scheduleGPUHost(requiredGPUNum: number, trialJobDetail: RemoteMachineTrialJobDetail): RemoteMachineScheduleResult | undefined {
const totalResourceMap: Map<RemoteMachineMeta, GPUInfo[]> = this.gpuResourceDetection();
const qualifiedRMs: RemoteMachineMeta[] = [];
totalResourceMap.forEach((gpuInfos: GPUInfo[], rmMeta: RemoteMachineMeta) => {
if (gpuInfos !== undefined && gpuInfos.length >= requiredGPUNum) {
qualifiedRMs.push(rmMeta);
}
});
if (qualifiedRMs.length > 0) {
const allocatedRm: RemoteMachineMeta = this.selectMachine(qualifiedRMs);
const gpuInfos: GPUInfo[] | undefined = totalResourceMap.get(allocatedRm);
if (gpuInfos !== undefined) { // should always true
return this.allocateHost(requiredGPUNum, allocatedRm, gpuInfos, trialJobDetail);
} else {
assert(false, 'gpuInfos is undefined');
}
}
return undefined;
}
/**
* Detect available GPU resource for a remote machine
* @param rmMeta Remote machine metadata
* @param requiredGPUNum required GPU number by application
* @param availableGPUMap available GPU resource filled by this detection
* @returns Available GPU number on this remote machine
*/
private gpuResourceDetection(): Map<RemoteMachineMeta, GPUInfo[]> {
const totalResourceMap: Map<RemoteMachineMeta, GPUInfo[]> = new Map<RemoteMachineMeta, GPUInfo[]>();
this.machineExecutorMap.forEach((executorManager: ExecutorManager, machineConfig: RemoteMachineConfig) => {
const rmMeta = executorManager.rmMeta;
// Assgin totoal GPU count as init available GPU number
if (rmMeta.gpuSummary !== undefined) {
const availableGPUs: GPUInfo[] = [];
const designatedGpuIndices: number[] | undefined = machineConfig.gpuIndices;
if (designatedGpuIndices !== undefined) {
for (const gpuIndex of designatedGpuIndices) {
if (gpuIndex >= rmMeta.gpuSummary.gpuCount) {
throw new Error(`Specified GPU index not found: ${gpuIndex}`);
}
}
}
this.log.debug(`designated gpu indices: ${designatedGpuIndices}`);
rmMeta.gpuSummary.gpuInfos.forEach((gpuInfo: GPUInfo) => {
// if the GPU has active process, OR be reserved by a job,
// or index not in gpuIndices configuration in machineList,
// or trial number on a GPU reach max number,
// We should NOT allocate this GPU
// if users set useActiveGpu, use the gpu whether there is another activeProcess
if (designatedGpuIndices === undefined || designatedGpuIndices.includes(gpuInfo.index)) {
if (rmMeta.occupiedGpuIndexMap !== undefined) {
const num: number | undefined = rmMeta.occupiedGpuIndexMap.get(gpuInfo.index);
if ((num === undefined && (!machineConfig.useActiveGpu && gpuInfo.activeProcessNum === 0 || machineConfig.useActiveGpu)) ||
(num !== undefined && num < machineConfig.maxTrialNumberPerGpu)) {
availableGPUs.push(gpuInfo);
}
} else {
throw new Error(`occupiedGpuIndexMap initialize error!`);
}
}
});
totalResourceMap.set(rmMeta, availableGPUs);
}
});
return totalResourceMap;
}
private selectMachine(rmMetas: RemoteMachineMeta[]): RemoteMachineMeta {
assert(rmMetas !== undefined && rmMetas.length > 0);
if (this.policyName === 'random') {
return randomSelect(rmMetas);
} else if (this.policyName === 'round-robin') {
return this.roundRobinSelect(rmMetas);
} else {
throw new Error(`Unsupported schedule policy: ${this.policyName}`);
}
}
private roundRobinSelect(rmMetas: RemoteMachineMeta[]): RemoteMachineMeta {
while (!rmMetas.includes(this.configuredRMs[this.roundRobinIndex % this.configuredRMs.length])) {
this.roundRobinIndex++;
}
return this.configuredRMs[this.roundRobinIndex++ % this.configuredRMs.length];
}
private selectGPUsForTrial(gpuInfos: GPUInfo[], requiredGPUNum: number): GPUInfo[] {
// Sequentially allocate GPUs
return gpuInfos.slice(0, requiredGPUNum);
}
private allocateHost(requiredGPUNum: number, rmMeta: RemoteMachineMeta,
gpuInfos: GPUInfo[], trialJobDetail: RemoteMachineTrialJobDetail): RemoteMachineScheduleResult {
assert(gpuInfos.length >= requiredGPUNum);
const allocatedGPUs: GPUInfo[] = this.selectGPUsForTrial(gpuInfos, requiredGPUNum);
allocatedGPUs.forEach((gpuInfo: GPUInfo) => {
if (rmMeta.occupiedGpuIndexMap !== undefined) {
let num: number | undefined = rmMeta.occupiedGpuIndexMap.get(gpuInfo.index);
if (num === undefined) {
num = 0;
}
rmMeta.occupiedGpuIndexMap.set(gpuInfo.index, num + 1);
} else {
throw new Error(`Machine ${rmMeta.config.host} occupiedGpuIndexMap initialize error!`);
}
});
trialJobDetail.gpuIndices = allocatedGPUs;
trialJobDetail.rmMeta = rmMeta;
return {
resultType: ScheduleResultType.SUCCEED,
scheduleInfo: {
rmMeta: rmMeta,
cudaVisibleDevice: allocatedGPUs
.map((gpuInfo: GPUInfo) => {
return gpuInfo.index;
})
.join(',')
}
};
}
} | the_stack |
import { Sequence } from 'async-sequencer'
import { IData } from './interface'
import * as Util from './util'
import generatorData from './generatorData.json'
import fs from 'fs'
// Used to identify event functions.
let eventResolverNames = Object.keys(generatorData.event.eventName)
eventResolverNames = eventResolverNames.map(eventName => eventName.split('.')[0])
/**
* @description
* Overwatch Workshop
* Common Generator
*/
export default ({
interfacePath,
interfaceType
}: {
interfacePath: string
interfaceType: string
}) => {
return Sequence(async ({resolve, reject, data: preData})=>{
// Generator Data
let data: IData = preData
let { Logger } = data
// Sequence Logic
Logger.debug(`[${data.lang.toUpperCase()}] Entering ${interfaceType} Generate...`)
Util.collectInterfaceFiles(
`${process.cwd()}/bin/release/${data.lang}/${interfacePath}`,
async (collectedDatas) => {
// Create child resolvers
for(let {
fileName,
interfaceName
} of collectedDatas){
// Check overwatch interfaces data is exist
if(!data.interfaces || data.interfaces == undefined){
reject()
return
}
// Create child resolver folder
try{ fs.mkdirSync(`${data.resolverPath}/${interfaceType.toLowerCase()}`) } catch(e) {}
// Check is interface have properties
let isPropertiesExist = false
try{
isPropertiesExist =
data.interfaces[interfaceName].properties
&& data.interfaces[interfaceName].properties.length != 0
}catch(e){}
// Get overwatch method name (pacal case)
let valueName =
data.generatorData
[interfaceType.toLowerCase()]
[`${interfaceType.toLowerCase()}Name`]
[fileName]
/**
* `resolverCode`
*/
let resolverCode = ``
// Create External Type Import
// if(isPropertiesExist) resolverCode += `import { ${interfaceName} } from '../../../interface'\n\n`
/**
* @description
* `propertieTypeMap` is store every properties type names.
*/
let propertieTypeMap = {}
if(isPropertiesExist){
/**
* @deprecated
* Collect Import Target
*/
// let interfaceNamesMap = {}
/**
* @description
* Collect all unique interface name
* (All type will be converted interface)
*/
for(let propertieName of Object.keys(data.interfaces[interfaceName].properties)){
/**
* Case 1 (Single Ref)
* @example 'ValueArrayType'
*/
if(typeof data.interfaces[interfaceName].properties[propertieName]['$ref'] != 'undefined'){
if(typeof propertieTypeMap[propertieName] == 'undefined') propertieTypeMap[propertieName] = []
let notUniqueInterface = data.interfaces[interfaceName].properties[propertieName]
let notUniqueInterfaceName = String(notUniqueInterface.$ref).split('#/definitions/')[1]
/**
* Convert Type Name `ValueArrayType` To `Array`
*/
notUniqueInterfaceName = Util.pureTypeNameExtractor(notUniqueInterfaceName)
/**
* @deprecated
* Collect Import Target
*/
// interfaceNamesMap[notUniqueInterfaceName] = true
propertieTypeMap[propertieName].push(notUniqueInterfaceName)
}
/**
* Case 2 (Multiple Ref)
* @example 'ValueArrayType' | 'ValueNumberType'
*/
if(data.interfaces[interfaceName].properties[propertieName].anyOf){
Logger.warn(`[${data.lang.toUpperCase()}] Please don't be use multiple type reference in properties (${interfaceType.toLowerCase()}/${fileName})`)
/**
* @deprecated
* Collect Import Target
*/
/*
if(typeof propertieTypeMap[propertieName] == 'undefined') propertieTypeMap[propertieName] = []
for(let notUniqueInterface of interfaces[interfaceName].properties[propertieName].anyOf){
let notUniqueInterfaceName = String(notUniqueInterface.$ref).split('#/definitions/')[1]
interfaceNamesMap[notUniqueInterfaceName] = true
propertieTypeMap[propertieName].push(notUniqueInterfaceName)
}
*/
}
}
/**
* @deprecated
* Write External Type Import
*/
/*
let interfaceNames = ``
for(let propertieTypeName of Object.keys(interfaceNamesMap)){
try{
if(interfaceNames.length == 0) interfaceNames += `\n`
interfaceNames += `\t${propertieTypeName},\n`
}catch(e){ console.log(e) }
}
if(interfaceNames.length != 0){
resolverCode += `import { ${interfaceNames} } from '../../../interface'\n\n`
}
*/
}
/**
* `resolverCode` [description]
*/
try{
if(data.interfaces[interfaceName].description){
// Create Interface Description
let resolverDescription = '/**\n'
for(let description of data.interfaces[interfaceName].description.split('\n'))
resolverDescription += ` * ${description}\n`
resolverDescription += ' */\n'
resolverCode += resolverDescription
}
}catch(e){}
/**
* `resolverCode` [export]
*/
let resolverName = fileName.split('.')[0]
try{
if(typeof data.generatorData[interfaceType.toLowerCase()]['methodNameReplace'][resolverName] != 'undefined')
resolverName = data.generatorData[interfaceType.toLowerCase()]['methodNameReplace'][resolverName]
}catch(e){}
// Values Collect
let valueProperties = ``
if(isPropertiesExist){
for(let propertieName of Object.keys(data.interfaces[interfaceName].properties)){
try{
//let propertieTypeName = interfaces[interfaceName].properties[propertieName].type
let propertieTypeName = ``
if(typeof propertieTypeMap[propertieName] != 'undefined'){
if(propertieTypeMap[propertieName].length > 1)
Logger.critical(`[${data.lang.toUpperCase()}] [TYPE BROKEN ALERT] Multiple Types in Propertie! (${interfaceType.toLowerCase()}/${fileName})`)
propertieTypeName = propertieTypeMap[propertieName].join(' | ')
}else{
// Allow Default Data Type
try{
propertieTypeName = data.interfaces[interfaceName].properties[propertieName].type
}catch(e){
Logger.critical(`[${data.lang.toUpperCase()}] Unexpected Interface Param Type! (${interfaceType.toLowerCase()}/${fileName})`)
console.log(data.interfaces[interfaceName].properties[propertieName])
}
}
valueProperties += (valueProperties.length == 0) ? `\n` : `,\n`
/**
* `Insert Propertie Description`
*/
let propertiesDescription = '\t/**\n'
if(data.interfaces[interfaceName].properties[propertieName].description)
for(let description of data.interfaces[interfaceName].properties[propertieName].description.split('\n'))
propertiesDescription += `\t * ${description}\n`
/**
* `Insert Propertie Type Reference By JSDoc`
*/
let typescriptTypeList = ['number']
if(typescriptTypeList.indexOf(propertieTypeName) == -1)
propertiesDescription += `\t * - \`Type.${propertieTypeName}.\`\n`
propertiesDescription += '\t */\n'
valueProperties += propertiesDescription
if(typescriptTypeList.indexOf(propertieTypeName) == -1){
valueProperties += `\t${propertieName}: string | number | any[]`
}else{
valueProperties += `\t${propertieName}: ${propertieTypeName}`
}
}catch(e){
console.log(`ERROR fileName: ${fileName}`)
console.log(e)
}
}
}
resolverCode += `export const ${resolverName} = (${valueProperties}\n) => {\n\n`
resolverCode += '\treturn `'
/**
* [sub] `workshopCode` [init]
*/
let workshopCode = valueName
/**
* [sub] `workshopCode` [properties]
*/
if(isPropertiesExist){
if(eventResolverNames.indexOf(resolverName) != -1){
// Event Functions
let properties = Object.keys(data.interfaces[interfaceName].properties)
workshopCode += `;`
for(let propertieIndex in properties){
workshopCode += '\n\t\t'
let propertie = properties[propertieIndex]
workshopCode += `\$\{${propertie}\}`
if((properties.length-1) != Number(propertieIndex)) workshopCode += `;`
}
}else{
// Value & Action Functions
workshopCode += '('
let properties = Object.keys(data.interfaces[interfaceName].properties)
for(let propertieIndex in properties){
if(Number(propertieIndex) != 0) workshopCode += ', '
let propertie = properties[propertieIndex]
workshopCode += `\$\{${propertie}\}`
}
workshopCode += ')'
}
}
/**
* `resolverCode` [workshopCode]
*/
resolverCode += workshopCode
resolverCode += '`\n}'
/**
* `Collect Additional Value Resolver`
*/
if(interfaceType == 'Value' && typeof data.preCollectedTypes[resolverName] != 'undefined'){
/**
* `Modify Resolver Return Type to Array`
*/
if(data.preCollectedTypes[resolverName].indexOf('array') != -1){
resolverCode = `${resolverCode.replace(`) => {`, `): any[] => {`)}\n\n`
resolverCode = resolverCode.replace(`\n\treturn `,`\n\t// @ts-ignore\n\treturn `)
/**
* `Modify Resolver Return Type to Number`
*/
} else if(data.preCollectedTypes[resolverName].indexOf('number') != -1
|| data.preCollectedTypes[resolverName].indexOf('vector') != -1){
resolverCode = `${resolverCode.replace(`) => {`, `): number => {`)}\n\n`
resolverCode = resolverCode.replace(`\n\treturn `,`\n\t// @ts-ignore\n\treturn `)
}
}
// console.log(`${fileName}, ${interfaceName}`)
// console.log(interfaces[interfaceName])
// console.log(resolverCode)
Logger.debug(`[${data.lang.toUpperCase()}] Created Resolver <${interfaceType.toLowerCase()}/${fileName}>`)
fs.writeFileSync(`${data.resolverPath}/${interfaceType.toLowerCase()}/${fileName}`, resolverCode)
}
/**
* `Create child index`
*/
let indexCode = ''
for(let { fileName } of collectedDatas)
indexCode += `export * from './${fileName.split('.')[0]}'\n`
fs.writeFileSync(`${data.resolverPath}/${interfaceType.toLowerCase()}/index.ts`, indexCode)
Logger.debug(`[${data.lang.toUpperCase()}] Created Resolver Index <${interfaceType.toLowerCase()}/index.ts>`)
}
)
resolve()
})
} | the_stack |
import { render, screen, within } from '@testing-library/react'
import userEvent, { specialChars } from '@testing-library/user-event'
import addMonths from 'date-fns/addMonths'
import format from 'date-fns/format'
import React from 'react'
import CareGoalForm from '../../../patients/care-goals/CareGoalForm'
import CareGoal, { CareGoalStatus, CareGoalAchievementStatus } from '../../../shared/model/CareGoal'
const { arrowDown, enter } = specialChars
const startDate = new Date()
const dueDate = addMonths(new Date(), 1)
const careGoal = {
description: 'some description',
startDate: startDate.toISOString(),
dueDate: dueDate.toISOString(),
note: '',
priority: 'medium',
status: CareGoalStatus.Accepted,
achievementStatus: CareGoalAchievementStatus.InProgress,
} as CareGoal
const setup = (disabled = false, initializeCareGoal = true, error?: any) => {
const onCareGoalChangeSpy = jest.fn()
const TestComponent = () => {
const [careGoal2, setCareGoal] = React.useState(initializeCareGoal ? careGoal : {})
onCareGoalChangeSpy.mockImplementation(setCareGoal)
return (
<CareGoalForm
careGoal={careGoal2}
disabled={disabled}
careGoalError={error}
onChange={onCareGoalChangeSpy}
/>
)
}
return { ...render(<TestComponent />), onCareGoalChangeSpy }
}
describe('Care Goal Form', () => {
it('should render a description input', () => {
setup()
const descriptionInput = screen.getByLabelText(/patient.careGoal.description/i)
expect(descriptionInput).toBeInTheDocument()
expect(descriptionInput).toHaveValue(careGoal.description)
// TODO: not using built-in form accessibility features yet: required attribute
// expect((descriptionInput as HTMLInputElement).required).toBeTruthy()
})
it('should call onChange handler when description changes', async () => {
const expectedDescription = 'some new description'
const { onCareGoalChangeSpy } = setup(false, false)
const descriptionInput = screen.getByLabelText(/patient\.careGoal\.description/i)
userEvent.type(descriptionInput, `${expectedDescription}`)
expect(descriptionInput).toBeEnabled()
expect(descriptionInput).toBeInTheDocument()
expect(onCareGoalChangeSpy).toHaveBeenCalledTimes(expectedDescription.length)
expect(descriptionInput).toHaveDisplayValue(expectedDescription)
})
it('should render a priority selector', () => {
setup()
expect(screen.getByText(/patient.careGoal.priority.label/i)).toBeInTheDocument()
const priority = within(screen.getByTestId('prioritySelect')).getByRole('combobox')
expect(priority).toBeInTheDocument()
userEvent.click(priority) // display popup with the options
expect(screen.getByText(/patient.careGoal.priority.low/i)).toBeInTheDocument()
expect(screen.getByText(/patient.careGoal.priority.medium/i)).toBeInTheDocument()
expect(screen.getByText(/patient.careGoal.priority.high/i)).toBeInTheDocument()
userEvent.click(screen.getByText(/patient.careGoal.priority.low/i))
expect(priority).toHaveValue('patient.careGoal.priority.low')
expect(screen.queryByText(/patient.careGoal.priority.medium/i)).not.toBeInTheDocument()
})
it('should call onChange handler when priority changes', () => {
const expectedPriority = 'high'
const { onCareGoalChangeSpy } = setup(false, false)
const priority = within(screen.getByTestId('prioritySelect')).getByRole('combobox')
userEvent.type(priority, `${expectedPriority}${arrowDown}${enter}`)
expect(priority).toHaveDisplayValue([`patient.careGoal.priority.${expectedPriority}`])
expect(onCareGoalChangeSpy).toHaveBeenCalledTimes(1)
expect(onCareGoalChangeSpy).toHaveBeenCalledWith({ priority: expectedPriority })
})
it('should render a status selector', () => {
setup()
expect(screen.getByText(/patient.careGoal.status/i)).toBeInTheDocument()
const status = within(screen.getByTestId('statusSelect')).getByRole('combobox')
expect(status).toBeInTheDocument()
expect(status).toHaveValue(careGoal.status)
userEvent.click(status) // display popup with the options
Object.values(CareGoalStatus).forEach((value) =>
expect(screen.getByText(value)).toBeInTheDocument(),
)
userEvent.click(screen.getByText(CareGoalStatus.Proposed))
expect(status).toHaveValue(CareGoalStatus.Proposed)
expect(screen.queryByText(CareGoalStatus.Accepted)).not.toBeInTheDocument()
})
it('should call onChange handler when status changes', () => {
const expectedStatus = CareGoalStatus.OnHold
const { onCareGoalChangeSpy } = setup(false, false)
const status = within(screen.getByTestId('statusSelect')).getByRole('combobox')
userEvent.type(status, `${expectedStatus}${arrowDown}${enter}`)
expect(onCareGoalChangeSpy).toHaveBeenCalledWith({ status: expectedStatus })
})
it('should render the achievement status selector', () => {
setup()
expect(screen.getByText(/patient.careGoal.achievementStatus/i)).toBeInTheDocument()
const achievementStatus = within(screen.getByTestId('achievementStatusSelect')).getByRole(
'combobox',
)
expect(achievementStatus).toBeInTheDocument()
expect(achievementStatus).toHaveValue(careGoal.achievementStatus)
})
it('should call onChange handler when achievement status change', () => {
const expectedAchievementStatus = CareGoalAchievementStatus.Improving
const { onCareGoalChangeSpy } = setup(false, false)
const status = within(screen.getByTestId('achievementStatusSelect')).getByRole('combobox')
userEvent.type(status, `${expectedAchievementStatus}${arrowDown}${enter}`)
expect(onCareGoalChangeSpy).toHaveBeenCalledWith({
achievementStatus: expectedAchievementStatus,
})
})
it('should render a start date picker', () => {
setup()
expect(screen.getByText(/patient.careGoal.startDate/i)).toBeInTheDocument()
const startDatePicker = within(screen.getByTestId('startDateDatePicker')).getByRole('textbox')
expect(startDatePicker).toBeInTheDocument()
expect(startDatePicker).toHaveValue(format(startDate, 'MM/dd/y'))
})
it('should call onChange handler when start date change', () => {
const { onCareGoalChangeSpy } = setup()
const expectedDate = '12/31/2050'
const startDatePicker = within(screen.getByTestId('startDateDatePicker')).getByRole('textbox')
userEvent.type(startDatePicker, `{selectall}${expectedDate}{enter}`)
expect(onCareGoalChangeSpy).toHaveBeenCalled()
expect(startDatePicker).toHaveDisplayValue(expectedDate)
})
it('should render a due date picker', () => {
setup()
expect(screen.getByText(/patient.careGoal.dueDate/i)).toBeInTheDocument()
const dueDatePicker = within(screen.getByTestId('dueDateDatePicker')).getByRole('textbox')
expect(dueDatePicker).toBeInTheDocument()
expect(dueDatePicker).toHaveValue(format(dueDate, 'MM/dd/y'))
})
it('should call onChange handler when due date changes', () => {
const { onCareGoalChangeSpy } = setup()
const expectedDate = '12/31/2050'
const dueDatePicker = within(screen.getByTestId('dueDateDatePicker')).getByRole('textbox')
userEvent.type(dueDatePicker, `{selectall}${expectedDate}{enter}`)
expect(onCareGoalChangeSpy).toHaveBeenCalled()
expect(dueDatePicker).toHaveDisplayValue(expectedDate)
})
it('should render a note input', () => {
setup()
expect(screen.getByText(/patient.careGoal.note/i)).toBeInTheDocument()
const noteInput = screen.getByRole('textbox', {
name: /patient\.caregoal\.note/i,
})
expect(noteInput).toHaveDisplayValue(careGoal.note)
})
it('should call onChange handler when note change', () => {
const expectedNote = 'some new note'
const { onCareGoalChangeSpy } = setup(false, false)
const noteInput = screen.getByRole('textbox', {
name: /patient\.caregoal\.note/i,
})
userEvent.type(noteInput, expectedNote)
expect(noteInput).toHaveDisplayValue(expectedNote)
expect(onCareGoalChangeSpy).toHaveBeenCalledTimes(expectedNote.length)
})
it('should render all the forms fields disabled if the form is disabled', () => {
setup(true)
const descriptionInput = screen.getByLabelText(/patient\.careGoal\.description/i)
const priority = within(screen.getByTestId('prioritySelect')).getByRole('combobox')
const status = within(screen.getByTestId('statusSelect')).getByRole('combobox')
const achievementStatus = within(screen.getByTestId('achievementStatusSelect')).getByRole(
'combobox',
)
const startDatePicker = within(screen.getByTestId('startDateDatePicker')).getByRole('textbox')
const dueDatePicker = within(screen.getByTestId('dueDateDatePicker')).getByRole('textbox')
const noteInput = screen.getByRole('textbox', {
name: /patient\.caregoal\.note/i,
})
expect(descriptionInput).toBeDisabled()
expect(priority).toBeDisabled()
expect(status).toBeDisabled()
expect(achievementStatus).toBeDisabled()
expect(startDatePicker).toBeDisabled()
expect(dueDatePicker).toBeDisabled()
expect(noteInput).toBeDisabled()
})
it('should render the forms field in an error state', async () => {
const expectedError = {
message: 'some error message',
description: 'some description error',
status: 'some status error',
achievementStatus: 'some achievement status error',
priority: 'some priority error',
startDate: 'some start date error',
dueDate: 'some due date error',
note: 'some note error',
}
setup(false, false, expectedError)
const alert = await screen.findByRole('alert')
const descriptionInput = screen.getByRole('textbox', {
name: /this is a required input/i,
})
const priority = within(screen.getByTestId('prioritySelect')).getByRole('combobox')
const status = within(screen.getByTestId('statusSelect')).getByRole('combobox')
const achievementStatus = within(screen.getByTestId('achievementStatusSelect')).getByRole(
'combobox',
)
const startDatePicker = within(screen.getByTestId('startDateDatePicker')).getByRole('textbox')
const dueDatePicker = within(screen.getByTestId('dueDateDatePicker')).getByRole('textbox')
const noteInput = screen.getByRole('textbox', {
name: /patient\.caregoal\.note/i,
})
expect(screen.getByText(/some description error/i)).toBeInTheDocument()
expect(screen.getByText(/some start date error/i)).toBeInTheDocument()
expect(screen.getByText(/some due date error/i)).toBeInTheDocument()
expect(alert).toHaveTextContent(expectedError.message)
expect(descriptionInput).toBeInTheDocument()
expect(priority).toBeInTheDocument()
expect(status).toBeInTheDocument()
expect(achievementStatus).toBeInTheDocument()
expect(startDatePicker).toBeInTheDocument()
expect(dueDatePicker).toBeInTheDocument()
expect(noteInput).toBeInTheDocument()
// TODO: not using built-in form accessibility features yet: HTMLInputElement.setCustomValidity()
// expect((descriptionInput as HTMLInputElement).validity.valid).toBe(false)
expect(descriptionInput).toHaveClass('is-invalid')
expect(priority).toHaveClass('is-invalid')
expect(status).toHaveClass('is-invalid')
expect(achievementStatus).toHaveClass('is-invalid')
})
}) | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages a Sentinel Automation 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 exampleAnalyticsWorkspace = new azure.operationalinsights.AnalyticsWorkspace("exampleAnalyticsWorkspace", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* sku: "pergb2018",
* });
* const sentinel = new azure.operationalinsights.AnalyticsSolution("sentinel", {
* solutionName: "SecurityInsights",
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* workspaceResourceId: exampleAnalyticsWorkspace.id,
* workspaceName: exampleAnalyticsWorkspace.name,
* plan: {
* publisher: "Microsoft",
* product: "OMSGallery/SecurityInsights",
* },
* });
* const exampleAutomationRule = new azure.sentinel.AutomationRule("exampleAutomationRule", {
* logAnalyticsWorkspaceId: sentinel.workspaceResourceId,
* displayName: "automation_rule1",
* order: 1,
* actionIncidents: [{
* order: 1,
* status: "Active",
* }],
* });
* ```
*
* ## Import
*
* Sentinel Automation Rules can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:sentinel/automationRule:AutomationRule example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/AutomationRules/rule1
* ```
*/
export class AutomationRule extends pulumi.CustomResource {
/**
* Get an existing AutomationRule 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?: AutomationRuleState, opts?: pulumi.CustomResourceOptions): AutomationRule {
return new AutomationRule(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:sentinel/automationRule:AutomationRule';
/**
* Returns true if the given object is an instance of AutomationRule. 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 AutomationRule {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === AutomationRule.__pulumiType;
}
/**
* One or more `actionIncident` blocks as defined below.
*/
public readonly actionIncidents!: pulumi.Output<outputs.sentinel.AutomationRuleActionIncident[] | undefined>;
/**
* One or more `actionPlaybook` blocks as defined below.
*/
public readonly actionPlaybooks!: pulumi.Output<outputs.sentinel.AutomationRuleActionPlaybook[] | undefined>;
/**
* One or more `condition` blocks as defined below.
*/
public readonly conditions!: pulumi.Output<outputs.sentinel.AutomationRuleCondition[] | undefined>;
/**
* The display name which should be used for this Sentinel Automation Rule.
*/
public readonly displayName!: pulumi.Output<string>;
/**
* Whether this Sentinel Automation Rule is enabled? Defaults to `true`.
*/
public readonly enabled!: pulumi.Output<boolean | undefined>;
/**
* The time in RFC3339 format of kind `UTC` that determines when this Automation Rule should expire and be disabled.
*/
public readonly expiration!: pulumi.Output<string | undefined>;
/**
* The ID of the Log Analytics Workspace where this Sentinel applies to. Changing this forces a new Sentinel Automation Rule to be created.
*/
public readonly logAnalyticsWorkspaceId!: pulumi.Output<string>;
/**
* The UUID which should be used for this Sentinel Automation Rule. Changing this forces a new Sentinel Automation Rule to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* The order of this Sentinel Automation Rule. Possible values varies between `1` and `1000`.
*/
public readonly order!: pulumi.Output<number>;
/**
* Create a AutomationRule 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: AutomationRuleArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: AutomationRuleArgs | AutomationRuleState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as AutomationRuleState | undefined;
inputs["actionIncidents"] = state ? state.actionIncidents : undefined;
inputs["actionPlaybooks"] = state ? state.actionPlaybooks : undefined;
inputs["conditions"] = state ? state.conditions : undefined;
inputs["displayName"] = state ? state.displayName : undefined;
inputs["enabled"] = state ? state.enabled : undefined;
inputs["expiration"] = state ? state.expiration : undefined;
inputs["logAnalyticsWorkspaceId"] = state ? state.logAnalyticsWorkspaceId : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["order"] = state ? state.order : undefined;
} else {
const args = argsOrState as AutomationRuleArgs | undefined;
if ((!args || args.displayName === undefined) && !opts.urn) {
throw new Error("Missing required property 'displayName'");
}
if ((!args || args.logAnalyticsWorkspaceId === undefined) && !opts.urn) {
throw new Error("Missing required property 'logAnalyticsWorkspaceId'");
}
if ((!args || args.order === undefined) && !opts.urn) {
throw new Error("Missing required property 'order'");
}
inputs["actionIncidents"] = args ? args.actionIncidents : undefined;
inputs["actionPlaybooks"] = args ? args.actionPlaybooks : undefined;
inputs["conditions"] = args ? args.conditions : undefined;
inputs["displayName"] = args ? args.displayName : undefined;
inputs["enabled"] = args ? args.enabled : undefined;
inputs["expiration"] = args ? args.expiration : undefined;
inputs["logAnalyticsWorkspaceId"] = args ? args.logAnalyticsWorkspaceId : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["order"] = args ? args.order : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
const aliasOpts = { aliases: [{ type: "azure:sentinel/authomationRule:AuthomationRule" }] };
opts = pulumi.mergeOptions(opts, aliasOpts);
super(AutomationRule.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering AutomationRule resources.
*/
export interface AutomationRuleState {
/**
* One or more `actionIncident` blocks as defined below.
*/
actionIncidents?: pulumi.Input<pulumi.Input<inputs.sentinel.AutomationRuleActionIncident>[]>;
/**
* One or more `actionPlaybook` blocks as defined below.
*/
actionPlaybooks?: pulumi.Input<pulumi.Input<inputs.sentinel.AutomationRuleActionPlaybook>[]>;
/**
* One or more `condition` blocks as defined below.
*/
conditions?: pulumi.Input<pulumi.Input<inputs.sentinel.AutomationRuleCondition>[]>;
/**
* The display name which should be used for this Sentinel Automation Rule.
*/
displayName?: pulumi.Input<string>;
/**
* Whether this Sentinel Automation Rule is enabled? Defaults to `true`.
*/
enabled?: pulumi.Input<boolean>;
/**
* The time in RFC3339 format of kind `UTC` that determines when this Automation Rule should expire and be disabled.
*/
expiration?: pulumi.Input<string>;
/**
* The ID of the Log Analytics Workspace where this Sentinel applies to. Changing this forces a new Sentinel Automation Rule to be created.
*/
logAnalyticsWorkspaceId?: pulumi.Input<string>;
/**
* The UUID which should be used for this Sentinel Automation Rule. Changing this forces a new Sentinel Automation Rule to be created.
*/
name?: pulumi.Input<string>;
/**
* The order of this Sentinel Automation Rule. Possible values varies between `1` and `1000`.
*/
order?: pulumi.Input<number>;
}
/**
* The set of arguments for constructing a AutomationRule resource.
*/
export interface AutomationRuleArgs {
/**
* One or more `actionIncident` blocks as defined below.
*/
actionIncidents?: pulumi.Input<pulumi.Input<inputs.sentinel.AutomationRuleActionIncident>[]>;
/**
* One or more `actionPlaybook` blocks as defined below.
*/
actionPlaybooks?: pulumi.Input<pulumi.Input<inputs.sentinel.AutomationRuleActionPlaybook>[]>;
/**
* One or more `condition` blocks as defined below.
*/
conditions?: pulumi.Input<pulumi.Input<inputs.sentinel.AutomationRuleCondition>[]>;
/**
* The display name which should be used for this Sentinel Automation Rule.
*/
displayName: pulumi.Input<string>;
/**
* Whether this Sentinel Automation Rule is enabled? Defaults to `true`.
*/
enabled?: pulumi.Input<boolean>;
/**
* The time in RFC3339 format of kind `UTC` that determines when this Automation Rule should expire and be disabled.
*/
expiration?: pulumi.Input<string>;
/**
* The ID of the Log Analytics Workspace where this Sentinel applies to. Changing this forces a new Sentinel Automation Rule to be created.
*/
logAnalyticsWorkspaceId: pulumi.Input<string>;
/**
* The UUID which should be used for this Sentinel Automation Rule. Changing this forces a new Sentinel Automation Rule to be created.
*/
name?: pulumi.Input<string>;
/**
* The order of this Sentinel Automation Rule. Possible values varies between `1` and `1000`.
*/
order: pulumi.Input<number>;
} | the_stack |
import Env from './env'
export type MalJSFunc = (...args: MalVal[]) => MalVal | never
export const M_META = Symbol.for('meta')
export const M_AST = Symbol.for('ast')
export const M_ENV = Symbol.for('env')
export const M_PARAMS = Symbol.for('params')
export const M_ISMACRO = Symbol.for('ismacro')
export const M_ISLIST = Symbol.for('islist')
export const M_TYPE = Symbol.for('type')
export const M_EVAL = Symbol.for('eval')
export const M_OUTER = Symbol.for('outer')
export const M_OUTER_INDEX = Symbol.for('outer-key')
const M_EXPAND = Symbol.for('expand')
// Stores string repsentation
export const M_ISSUGAR = Symbol('issugar')
export const M_ELMSTRS = Symbol.for('elmstrs') // string representations of each elements
export const M_DELIMITERS = Symbol.for('delimiters') // delimiter strings of list/map
export const M_DEF = Symbol.for('def') // save def exp reference in symbol object
export type MalBind = (
| MalSymbol
| string
| {[k: string]: MalSymbol}
| MalBind
)[]
export enum ExpandType {
Constant = 1,
Env,
Unchange,
}
export interface ExpandInfoConstant {
type: ExpandType.Constant
exp: MalVal
}
export interface ExpandInfoEnv {
type: ExpandType.Env
exp: MalVal
env: Env
}
export interface ExpandInfoUnchange {
type: ExpandType.Unchange
}
export type ExpandInfo = ExpandInfoConstant | ExpandInfoEnv | ExpandInfoUnchange
export interface MalFuncThis {
callerEnv: Env
}
export interface MalFunc extends Function {
(this: void | MalFuncThis, ...args: MalVal[]): MalVal
[M_META]?: MalVal
[M_AST]: MalVal
[M_ENV]: Env
[M_PARAMS]: MalBind
[M_ISMACRO]: boolean
}
export class MalError extends Error {}
export type MalMap = {[keyword: string]: MalVal}
export interface MalNodeMap extends MalMap {
[M_META]?: MalVal
[M_DELIMITERS]: string[]
[M_ELMSTRS]: string[]
[M_EVAL]: MalVal
[M_OUTER]: MalNode
[M_OUTER_INDEX]: number
}
export interface MalSeq extends Array<MalVal> {
[M_ISLIST]: boolean
[M_META]?: MalVal
[M_ISSUGAR]: boolean
[M_DELIMITERS]: string[]
[M_ELMSTRS]: string[]
[M_EVAL]: MalVal // Stores evaluted value of the node
[M_EXPAND]: ExpandInfo
[M_OUTER]: MalNode
[M_OUTER_INDEX]: number
}
// Expand
function expandSymbolsInExp(exp: MalVal, env: Env): MalVal {
const type = getType(exp)
switch (type) {
case MalType.List:
case MalType.Vector: {
let ret = (exp as MalVal[]).map(val => expandSymbolsInExp(val, env))
if (type === MalType.List) {
ret = createList(...ret)
}
return ret
}
case MalType.Map: {
const ret = {} as MalMap
Object.entries(exp as MalMap).forEach(([key, val]) => {
ret[key] = expandSymbolsInExp(val, env)
})
return ret
}
case MalType.Symbol:
if (env.hasOwn(exp as MalSymbol)) {
return env.get(exp as MalSymbol)
} else {
return exp
}
default:
return exp
}
}
export function setExpandInfo(exp: MalSeq, info: ExpandInfo) {
exp[M_EXPAND] = info
}
export function expandExp(exp: MalVal) {
if (isList(exp) && M_EXPAND in exp) {
const info = exp[M_EXPAND]
switch (info.type) {
case ExpandType.Constant:
return info.exp
case ExpandType.Env:
return expandSymbolsInExp(info.exp, info.env)
case ExpandType.Unchange:
return exp
}
} else {
return getEvaluated(exp, false)
}
}
export function getOuter(exp: any) {
if (isNode(exp) && M_OUTER in exp) {
return exp[M_OUTER]
}
return null
}
export enum MalType {
// Collections
List = 'list',
Vector = 'vector',
Map = 'map',
// Atoms
Number = 'number',
String = 'string',
Boolean = 'boolean',
Nil = 'nil',
Symbol = 'symbol',
Keyword = 'keyword',
Atom = 'atom',
// Functions
Function = 'fn',
Macro = 'macro',
// Others
Undefined = 'undefined',
}
export function getType(obj: any): MalType {
const _typeof = typeof obj
switch (_typeof) {
case 'object':
if (obj === null) {
return MalType.Nil
} else if (Array.isArray(obj)) {
const islist = (obj as MalSeq)[M_ISLIST]
return islist ? MalType.List : MalType.Vector
} else if (obj instanceof Float32Array) {
return MalType.Vector
} else if ((obj as any)[M_TYPE] === MalType.Symbol) {
return MalType.Symbol
} else if ((obj as any)[M_TYPE] === MalType.Atom) {
return MalType.Atom
} else {
return MalType.Map
}
case 'function': {
const ismacro = (obj as MalFunc)[M_ISMACRO]
return ismacro ? MalType.Macro : MalType.Function
}
case 'string':
switch ((obj as string)[0]) {
case KEYWORD_PREFIX:
return MalType.Keyword
default:
return MalType.String
}
case 'number':
return MalType.Number
case 'boolean':
return MalType.Boolean
default:
return MalType.Undefined
}
}
export type MalNode = MalNodeMap | MalSeq
export const isNode = (v: MalVal | undefined): v is MalNode => {
const type = getType(v)
return (
type === MalType.List || type === MalType.Map || type === MalType.Vector
)
}
export const isSeq = (v: MalVal | undefined): v is MalSeq => {
const type = getType(v)
return type === MalType.List || type === MalType.Vector
}
export function getMeta(obj: MalVal): MalVal {
if (obj instanceof Object) {
return M_META in obj ? (obj as any)[M_META] : null
} else {
return null
}
}
const TYPES_SUPPORT_META = new Set([
MalType.Function,
MalType.Macro,
MalType.List,
MalType.Vector,
MalType.Map,
])
export function withMeta(a: MalVal, m: any) {
if (m === undefined) {
throw new MalError('[with-meta] Need the metadata to attach')
}
if (!TYPES_SUPPORT_META.has(getType(a))) {
throw new MalError('[with-meta] Object should not be atom')
}
const c = cloneExp(a as MalNode)
c[M_META] = m
return c
}
export function setMeta(a: MalVal, m: MalVal) {
if (!(a instanceof Object)) {
throw new MalError('[with-meta] Object should not be atom')
}
;(a as any)[M_META] = m
return a
}
export type MalVal =
| number
| string
| boolean
| null
| MalSymbol
| MalAtom
| MalFunc
| MalJSFunc
| MalMap
| MalVal[]
| MalNode
export interface MalNodeSelection {
outer: MalNode
index: number
}
interface MalRootSelection {
root: MalVal
}
export type MalSelection = MalNodeSelection | MalRootSelection
export function getMalFromSelection(sel: MalSelection) {
if ('root' in sel) {
return sel.root
} else {
const {outer, index} = sel
if (isMap(outer)) {
return outer[Object.keys(outer)[index]]
} else {
return outer[index]
}
}
}
// General Functions
export function isEqual(a: MalVal, b: MalVal) {
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false
}
for (let i = 0; i < a.length; i++) {
if (!isEqual(a[i], b[i])) {
return false
}
}
return true
} else if (isMap(a) && isMap(b)) {
if (a.size !== b.size) {
return false
}
for (const k of Object.keys(a)) {
const aval = a[k],
bval = b[k]
if (aval === undefined || bval === undefined || !isEqual(aval, bval)) {
return false
}
}
return true
} else {
return a === b
}
}
export function cloneExp<T extends MalVal>(exp: T, deep = false): T {
switch (getType(exp)) {
case MalType.List: {
const children = deep
? (exp as MalSeq).map(e => cloneExp(e, true))
: (exp as MalSeq)
const cloned = createList(...children)
if (Array.isArray((exp as MalNode)[M_DELIMITERS])) {
;(cloned as MalNode)[M_DELIMITERS] = [...(exp as MalNode)[M_DELIMITERS]]
}
return cloned as T
}
case MalType.Vector: {
const children = deep
? (exp as MalSeq).map(e => cloneExp(e, true))
: (exp as MalSeq)
const cloned = createVector(...children)
if (Array.isArray((exp as MalNode)[M_DELIMITERS])) {
;(cloned as MalNode)[M_DELIMITERS] = [...(exp as MalNode)[M_DELIMITERS]]
}
return cloned as T
}
case MalType.Map: {
const cloned = deep
? Object.fromEntries(
Object.entries(exp as MalMap).map(([k, v]) => [
k,
cloneExp(v, true),
])
)
: {...(exp as MalMap)}
if (Array.isArray((exp as MalNode)[M_DELIMITERS])) {
;(cloned as MalNode)[M_DELIMITERS] = [...(exp as MalNode)[M_DELIMITERS]]
}
return cloned as T
}
case MalType.Function:
case MalType.Macro: {
// new function instance
const fn = function (this: MalFuncThis, ...args: MalSeq) {
return (exp as MalFunc).apply(this, args)
}
// copy original properties
return Object.assign(fn, exp) as T
}
case MalType.Symbol:
return symbolFor((exp as MalSymbol).value) as T
default:
return exp
}
}
export function getEvaluated(exp: MalVal, deep = true): MalVal {
if (exp instanceof Object && M_EVAL in exp) {
const evaluated = (exp as MalNode)[M_EVAL]
if (isList(evaluated) && deep) {
return getEvaluated(evaluated, deep)
} else {
return evaluated
}
} else {
return exp
}
}
export function getName(exp: MalVal): string {
switch (getType(exp)) {
case MalType.String:
return exp as string
case MalType.Keyword:
return (exp as string).slice(1)
case MalType.Symbol:
return (exp as MalSymbol).value
default:
throw new MalError(
'getName() can only extract the name by string/keyword/symbol'
)
}
}
// Functions
export function createMalFunc(
fn: (this: void | MalFuncThis, ...args: MalVal[]) => MalVal,
exp: MalVal,
env: Env,
params: MalBind,
meta = null,
ismacro = false
): MalFunc {
const attrs = {
[M_AST]: exp,
[M_ENV]: env,
[M_PARAMS]: params,
[M_META]: meta,
[M_ISMACRO]: ismacro,
}
return Object.assign(fn, attrs)
}
export const isFunc = (exp: MalVal | undefined): exp is MalFunc =>
exp instanceof Function
export const isMalFunc = (obj: MalVal | undefined): obj is MalFunc =>
obj instanceof Function && (obj as MalFunc)[M_AST] ? true : false
// String
export const isString = (obj: MalVal | undefined): obj is string =>
getType(obj) === MalType.String
// Symbol
export class MalSymbol {
public constructor(public value: string) {
;(this as any)[M_TYPE] = MalType.Symbol
}
public set def(def: MalSeq | null) {
;(this as any)[M_DEF] = def
}
public get def(): MalSeq | null {
return (this as any)[M_DEF] || null
}
public set evaluated(value: MalVal) {
;(this as any)[M_EVAL] = value
}
public get evaluated(): MalVal {
return (this as any)[M_EVAL]
}
public toString() {
return this.value
}
}
export const isSymbol = (obj: MalVal | undefined): obj is MalSymbol =>
getType(obj) === MalType.Symbol
export const isSymbolFor = (obj: any, name: string): obj is MalSymbol =>
isSymbol(obj) && obj.value === name
export const symbolFor = (value: string) => new MalSymbol(value)
// Keyword
const KEYWORD_PREFIX = '\u029e'
// Use \u029e as the prefix of keyword instead of colon (:) for AST object
export const isKeyword = (obj: MalVal | undefined): obj is string =>
getType(obj) === MalType.Keyword
export const keywordFor = (k: string) => KEYWORD_PREFIX + k
// List
export const isList = (obj: MalVal | undefined): obj is MalSeq => {
// below code is identical to `getType(obj) === MalType.List`
return Array.isArray(obj) && (obj as any)[M_ISLIST]
}
export function createList(...coll: MalVal[]) {
;(coll as MalSeq)[M_ISLIST] = true
coll.forEach((child, i) => {
if (isNode(child)) {
child[M_OUTER] = coll as MalSeq
child[M_OUTER_INDEX] = i
}
})
return coll as MalSeq
}
// Vectors
export const isVector = (obj: MalVal | undefined): obj is MalSeq => {
// below code is identical to `getType(obj) === MalType.Vector`
return (
(Array.isArray(obj) && !(obj as any)[M_ISLIST]) ||
obj instanceof Float32Array
)
}
export function createVector(...coll: MalVal[]) {
coll.forEach((child, i) => {
if (isNode(child)) {
child[M_OUTER] = coll as MalSeq
child[M_OUTER_INDEX] = i
}
})
return coll as MalSeq
}
// Maps
export const isMap = (obj: MalVal | undefined): obj is MalMap =>
getType(obj) === MalType.Map
export function assocBang(hm: MalMap, ...args: any[]) {
if (args.length % 2 === 1) {
throw new MalError('Odd number of map arguments')
}
for (let i = 0; i < args.length; i += 2) {
if (typeof args[i] !== 'string') {
throw new MalError('Hash map can only use string/symbol/keyword as key')
}
hm[args[i]] = args[i + 1]
}
return hm
}
// Atoms
export class MalAtom {
public constructor(public value: MalVal) {
;(this as any)[M_TYPE] = MalType.Atom
}
}
// General functions
export function malEquals(a: MalVal, b: MalVal) {
const type = getType(a)
const typeB = getType(b)
if (type !== typeB) {
return false
}
switch (type) {
case MalType.List:
case MalType.Vector:
if ((a as MalVal[]).length !== (b as MalVal[]).length) {
return false
}
for (let i = 0; i < (a as MalVal[]).length; i++) {
if (!malEquals((a as MalVal[])[i], (b as MalVal[])[i])) {
return false
}
}
return true
case MalType.Map: {
const keys = Object.keys(a as MalMap)
if (keys.length !== Object.keys(b as MalMap).length) {
return false
}
for (const key of keys) {
if (!malEquals((a as MalMap)[key], (b as MalMap)[key])) {
return false
}
}
return true
}
case MalType.Symbol:
return (a as MalSymbol).value === (b as MalSymbol).value
default:
return a === b
}
} | the_stack |
import * as express from 'express';
import * as path from 'path';
const fs = require('fs');
const dotenv = require('dotenv');
if (fs.existsSync(path.join(__dirname, '../.env'))) {
const envPath = fs.readFileSync(path.join(__dirname, '../.env'));
// tslint:disable-next-line: no-console
console.log('A .env file has been found found and will now be parsed.');
// https://github.com/motdotla/dotenv#what-happens-to-environment-variables-that-were-already-set
const envConfig = dotenv.parse(envPath);
if (envConfig) {
for (const key in envConfig) {
if (envConfig.hasOwnProperty(key)) {
process.env[key] = envConfig[key];
}
}
// tslint:disable-next-line: no-console
console.log('The provided .env file has been parsed successfully.');
}
}
import * as bodyParser from 'body-parser';
import { createConnection } from 'typeorm';
const authController = require('./routes/authentication.controller');
import * as userController from './routes/user.controller';
const fileUploadController = require('./routes/file-upload.controller');
import * as orgController from './routes/organization.controller';
import * as assetController from './routes/asset.controller';
import * as assessmentController from './routes/assessment.controller';
import * as vulnController from './routes/vulnerability.controller';
import * as jwtMiddleware from './middleware/jwt.middleware';
import { generateReport } from './utilities/puppeteer.utility';
import * as configController from './routes/config.controller';
import * as teamController from './routes/team.controller';
import * as apiKeyController from './routes/api-key.controller';
const helmet = require('helmet');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(
express.static(path.join(__dirname, '../frontend/dist/frontend'), {
etag: false,
})
);
app.use(helmet());
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self' blob:", 'stackpath.bootstrapcdn.com'],
scriptSrc: [
"'self'",
'code.jquery.com',
'stackpath.bootstrapcdn.com',
'${serverIpAddress}',
],
styleSrc: ["'self'", 'stackpath.bootstrapcdn.com', "'unsafe-inline'"],
},
})
);
app.use(bodyParser.json({ limit: '2mb' }));
app.use(bodyParser.urlencoded({ extended: true }));
const serverPort = process.env.PORT || 5000;
const serverIpAddress = process.env.SERVER_ADDRESS || '127.0.0.1';
app.set('port', serverPort);
app.set('serverIpAddress', serverIpAddress);
// tslint:disable-next-line: no-console
app.listen(serverPort, () =>
console.info(`Server running on ${serverIpAddress}:${serverPort}`)
);
// create typeorm connection
createConnection().then((_) => {
// tslint:disable-next-line: no-console
console.info(`Database connection successful`);
// Check for initial configuration and user
// If none exist, insert
configController.initialInsert();
// Protected Global Routes
app.post(
'/api/user/email',
jwtMiddleware.checkToken,
userController.updateUserEmail
);
app.post(
'/api/user/email/revoke',
jwtMiddleware.checkToken,
userController.revokeEmailRequest
);
app.patch('/api/user', jwtMiddleware.checkToken, userController.patch);
app.post('/api/user', jwtMiddleware.checkToken, userController.create);
app.get('/api/user', jwtMiddleware.checkToken, userController.getUser);
app.get('/api/user', jwtMiddleware.checkToken, userController.getUser);
app.get(
'/api/users/all',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
userController.getAllUsers
);
app.get('/api/users', jwtMiddleware.checkToken, userController.getUsers);
app.get(
'/api/testers/:orgId',
jwtMiddleware.checkToken,
userController.getTesters
);
app.patch(
'/api/user/password',
jwtMiddleware.checkToken,
userController.updateUserPassword
);
app.post(
'/api/refresh',
jwtMiddleware.checkRefreshToken,
authController.refreshSession
);
app.get(
'/api/file/:id',
jwtMiddleware.checkToken,
fileUploadController.getFileById
);
app.get(
'/api/organization',
jwtMiddleware.checkToken,
orgController.getActiveOrgs
);
app.get(
'/api/organization/archive',
jwtMiddleware.checkToken,
orgController.getArchivedOrgs
);
app.get(
'/api/organization/:id',
jwtMiddleware.checkToken,
orgController.getOrgById
);
app.get(
'/api/organization/asset/:id',
jwtMiddleware.checkToken,
assetController.getOrgAssets
);
app.get(
'/api/organization/:id/asset/archive',
jwtMiddleware.checkToken,
assetController.getArchivedOrgAssets
);
app.get(
'/api/organization/:id/asset/:assetId',
jwtMiddleware.checkToken,
assetController.getAssetById
);
app.get(
'/api/asset/:assetId/open/vulnerabilities',
jwtMiddleware.checkToken,
assetController.getOpenVulnsByAsset
);
app.get(
'/api/assessment/:id',
jwtMiddleware.checkToken,
assessmentController.getAssessmentsByAssetId
);
app.get(
'/api/assessment/:id/vulnerability',
jwtMiddleware.checkToken,
assessmentController.getAssessmentVulns
);
app.post(
'/api/assessment',
jwtMiddleware.checkToken,
assessmentController.createAssessment
);
app.delete(
'/api/assessment/:assessmentId',
jwtMiddleware.checkToken,
assessmentController.deleteAssessmentById
);
app.get(
'/api/asset/:assetId/assessment/:assessmentId',
jwtMiddleware.checkToken,
assessmentController.getAssessmentById
);
app.patch(
'/api/asset/:assetId/assessment/:assessmentId',
jwtMiddleware.checkToken,
assessmentController.updateAssessmentById
);
app.get(
'/api/assessment/:assessmentId/report',
jwtMiddleware.checkToken,
assessmentController.queryReportDataByAssessment
);
app.post('/api/report/generate', jwtMiddleware.checkToken, generateReport);
app.get(
'/api/vulnerability/:vulnId',
jwtMiddleware.checkToken,
vulnController.getVulnById
);
app.delete(
'/api/vulnerability/:vulnId',
jwtMiddleware.checkToken,
vulnController.deleteVulnById
);
app.patch(
'/api/vulnerability/:vulnId',
jwtMiddleware.checkToken,
vulnController.patchVulnById
);
app.post(
'/api/vulnerability',
jwtMiddleware.checkToken,
vulnController.createVuln
);
app.get(
'/api/vulnerability/jira/:vulnId',
jwtMiddleware.checkToken,
vulnController.exportToJira
);
app.get(
'/api/user/teams',
jwtMiddleware.checkToken,
teamController.getMyTeams
);
app.post(
'/api/user/key',
jwtMiddleware.checkToken,
apiKeyController.generateApiKey
);
app.get(
'/api/user/key',
jwtMiddleware.checkToken,
apiKeyController.getUserApiKeyInfo
);
app.patch(
'/api/user/key/:id',
jwtMiddleware.checkToken,
apiKeyController.deleteApiKeyAsUser
);
// Public Routes
app.post('/api/user/register', userController.register);
app.get('/api/user/verify/:uuid', userController.verify);
app.patch('/api/forgot-password', authController.forgotPassword);
app.patch('/api/password-reset', authController.resetPassword);
app.post('/api/user/email/validate', userController.validateEmailRequest);
app.post('/api/login', authController.login);
// Tester Routes
app.post(
'/api/upload',
jwtMiddleware.checkToken,
fileUploadController.uploadFile
);
// Admin Routes
app.patch(
'/api/organization/:id/asset/:assetId',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
assetController.updateAssetById
);
app.post(
'/api/organization/:id/asset',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
assetController.createAsset
);
app.patch(
'/api/asset/archive/:assetId',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
assetController.archiveAssetById
);
app.patch(
'/api/asset/activate/:assetId',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
assetController.activateAssetById
);
app.post(
'/api/config',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
configController.saveConfig
);
app.get(
'/api/config',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
configController.getConfig
);
app.post(
'/api/user/invite',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
userController.invite
);
app.patch(
'/api/organization/:id/archive',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
orgController.archiveOrgById
);
app.patch(
'/api/organization/:id/activate',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
orgController.activateOrgById
);
app.patch(
'/api/organization/:id',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
orgController.updateOrgById
);
app.post(
'/api/organization',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
orgController.createOrg
);
app.delete(
'/api/asset/jira/:assetId',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
assetController.purgeJiraInfo
);
app.get(
'/api/team/:teamId',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
teamController.getTeamById
);
app.get(
'/api/team',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
teamController.getAllTeams
);
app.post(
'/api/team',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
teamController.createTeam
);
app.patch(
'/api/team',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
teamController.updateTeamInfo
);
app.post(
'/api/team/member/add',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
teamController.addTeamMember
);
app.post(
'/api/team/member/remove',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
teamController.removeTeamMember
);
app.delete(
'/api/team/:teamId',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
teamController.deleteTeam
);
app.post(
'/api/team/asset/add',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
teamController.addTeamAsset
);
app.post(
'/api/team/asset/remove',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
teamController.removeTeamAsset
);
app.get(
'/api/keys',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
apiKeyController.getAdminApiKeyInfo
);
app.patch(
'/api/key/:id',
[jwtMiddleware.checkToken, jwtMiddleware.isAdmin],
apiKeyController.deleteApiKeyAsAdmin
);
}); | the_stack |
import { CfnDomain, CfnRepository } from '@aws-cdk/aws-codeartifact';
import { InterfaceVpcEndpoint } from '@aws-cdk/aws-ec2';
import { Effect, Grant, IGrantable, PolicyStatement } from '@aws-cdk/aws-iam';
import { ArnFormat, Construct, IConstruct, Lazy, Stack } from '@aws-cdk/core';
import { AwsCustomResource, AwsCustomResourcePolicy, PhysicalResourceId } from '@aws-cdk/custom-resources';
import * as api from './api';
export interface RepositoryProps {
/**
* The description of the Repository resource.
*/
readonly description?: string;
/**
* The name of the Domain.
*
* @default - a name is generated by CDK.
*/
readonly domainName?: string;
/**
* Specify `domainName` and `domainExists: true` in order to use an existing
* CodeArtifact domain instead of creating a new one.
*
* @default false
*/
readonly domainExists?: boolean;
/**
* The name of the Repository.
*
* @default - a name is generated by CDK.
*/
readonly repositoryName?: string;
/**
* The name of upstream repositories to configure on this repository. Those
* repositories must be in the same domain, hence this property can only be
* used if `domainExists` is `true`.
*
* @default - none
*/
readonly upstreams?: string[];
}
export interface IRepository extends IConstruct, api.IRepository {
/** The ARN of the CodeArtifact Domain that contains the repository. */
readonly repositoryDomainArn: string;
/** The effective name of the CodeArtifact Domain. */
readonly repositoryDomainName: string;
/** The owner account of the CodeArtifact Domain. */
readonly repositoryDomainOwner: string;
/** The ARN of the CodeArtifact Repository. */
readonly repositoryArn: string;
/** The effective name of the CodeArtifact Repository. */
readonly repositoryName: string;
/** The URL to the endpoint of the CodeArtifact Repository for use with NPM. */
readonly repositoryNpmEndpoint: string;
/**
* Grants read-only access to the repository, for use with NPM.
*
* @param grantee the entity to be granted read access.
*
* @returns the resulting `Grant`.
*/
grantReadFromRepository(grantee: IGrantable): Grant;
}
/**
* A CodeArtifact repository.
*/
export class Repository extends Construct implements IRepository {
/**
* The ARN of the CodeArtifact Domain that contains the repository.
*/
public readonly repositoryDomainArn: string;
/**
* The name of the CodeArtifact Domain that contains the repository.
*/
public readonly repositoryDomainName: string;
/**
* The account ID that owns the CodeArtifact Domain that contains the repository.
*/
public readonly repositoryDomainOwner: string;
/**
* The ARN of the CodeArtifact Repository.
*/
public readonly repositoryArn: string;
/**
* The name of the CodeArtifact Repository.
*/
public readonly repositoryName: string;
/**
* The name of the CodeArtifact Repository where to publish overlay packages.
*/
public readonly publishingRepositoryArn: string;
/**
* The name of the CodeArtifact Repository where to publish overlay packages.
*/
public readonly publishingRepositoryName: string;
readonly #externalConnections = new Array<string>();
#repositoryNpmEndpoint?: string;
#publishingRepositoryNpmEndpoint?: string;
#s3BucketArn?: string;
public constructor(scope: Construct, id: string, props?: RepositoryProps) {
super(scope, id);
if (props?.domainExists && !props.domainName) {
throw new Error('domainExists cannot be specified if no domainName is provided');
}
if (props?.upstreams && !props.domainExists) {
throw new Error('upstreams can only be specified if domainExists and domainName are provided');
}
const domainName = props?.domainName ?? this.node.addr;
const domain = props?.domainExists ? undefined : new CfnDomain(this, 'Domain', { domainName });
const repositoryName = props?.repositoryName ?? this.node.addr;
/**
* This repository does not have any upstreams or external connections, so
* it should be exempt from surprises. Concretely, any apckages published
* to this repository will go in there, so we can separate "hand-published"
* from "from upstream or external" packages.
*/
const publishingUpstream = domain && new CfnRepository(this, 'Publishing', {
description: 'Publishing repository',
domainName: domain.attrName,
repositoryName: `${repositoryName}-publish-overlay`,
});
const repository = new CfnRepository(this, 'Default', {
description: props?.description,
domainName: domain?.attrName ?? domainName,
externalConnections: Lazy.list({
produce: () =>
!domain && this.#externalConnections.length > 0
? this.#externalConnections
: undefined,
}),
repositoryName,
// NOTE: Upstream order IS important, as CodeArtifact repositories query
// their upstreams in the order they are listed in. The publishing
// upstream is hence last in the list, so we get packages from the
// "official" sources first.
upstreams: Lazy.list({
produce: () =>
domain && this.#externalConnections.length > 0
? [
...(props?.upstreams ?? []),
...this.#externalConnections.map((name) => this.makeUpstreamForId(name, { domain, repositoryName })),
...(publishingUpstream ? [publishingUpstream.attrName] : []),
]
: publishingUpstream ? [publishingUpstream?.attrName] : props?.upstreams,
}),
});
this.repositoryDomainArn = domain?.attrArn ?? Stack.of(this).formatArn({
service: 'codeartifact',
resource: 'domain',
arnFormat: ArnFormat.SLASH_RESOURCE_NAME,
resourceName: domainName,
});
this.repositoryDomainName = repository.attrDomainName;
this.repositoryDomainOwner = repository.attrDomainOwner;
this.repositoryArn = repository.attrArn;
this.repositoryName = repository.attrName;
this.publishingRepositoryArn = publishingUpstream?.attrArn ?? this.repositoryArn;
this.publishingRepositoryName = publishingUpstream?.attrName ?? repositoryName;
}
/**
* Adds an external connection to this repository.
*
* @param id the id of the external connection (i.e: `public:npmjs`).
*/
public addExternalConnection(id: 'public:npmjs'): void {
if (!this.#externalConnections.includes(id)) {
this.#externalConnections.push(id);
}
}
/**
* The npm repository endpoint to use for interacting with this repository.
*/
public get repositoryNpmEndpoint(): string {
if (this.#repositoryNpmEndpoint == null) {
const serviceCall = {
service: 'CodeArtifact',
action: 'getRepositoryEndpoint',
parameters: {
domain: this.repositoryDomainName,
domainOwner: this.repositoryDomainOwner,
format: 'npm',
repository: this.repositoryName,
},
physicalResourceId: PhysicalResourceId.fromResponse('repositoryEndpoint'),
};
const endpoint = new AwsCustomResource(this, 'GetEndpoint', {
onCreate: serviceCall,
onUpdate: serviceCall,
policy: AwsCustomResourcePolicy.fromSdkCalls({ resources: [this.repositoryArn] }),
resourceType: 'Custom::CodeArtifactNpmRepositoryEndpoint',
});
this.#repositoryNpmEndpoint = endpoint.getResponseField('repositoryEndpoint');
}
return this.#repositoryNpmEndpoint;
}
/**
* The npm repository endpoint to use for interacting with this repository to
* publish new packages.
*/
public get publishingRepositoryNpmEndpoint(): string {
if (this.#publishingRepositoryNpmEndpoint == null) {
const serviceCall = {
service: 'CodeArtifact',
action: 'getRepositoryEndpoint',
parameters: {
domain: this.repositoryDomainName,
domainOwner: this.repositoryDomainOwner,
format: 'npm',
repository: this.publishingRepositoryName,
},
physicalResourceId: PhysicalResourceId.fromResponse('repositoryEndpoint'),
};
const endpoint = new AwsCustomResource(this, 'GetPublishingEndpoint', {
onCreate: serviceCall,
onUpdate: serviceCall,
policy: AwsCustomResourcePolicy.fromSdkCalls({ resources: [this.publishingRepositoryArn] }),
resourceType: 'Custom::CodeArtifactNpmRepositoryEndpoint',
});
this.#publishingRepositoryNpmEndpoint = endpoint.getResponseField('repositoryEndpoint');
}
return this.#publishingRepositoryNpmEndpoint;
}
/**
* The S3 bucket in which CodeArtifact stores the package data. When using
* VPC Endpoints for CodeArtifact, an S3 Gateway Endpoint must also be
* available, which allows reading from this bucket.
*/
public get s3BucketArn(): string {
if (this.#s3BucketArn == null) {
const domainDescription = new AwsCustomResource(this, 'DescribeDomain', {
onCreate: {
service: 'CodeArtifact',
action: 'describeDomain',
parameters: {
domain: this.repositoryDomainName,
domainOwner: this.repositoryDomainOwner,
},
physicalResourceId: PhysicalResourceId.fromResponse('domain.s3BucketArn'),
},
policy: AwsCustomResourcePolicy.fromSdkCalls({ resources: [this.repositoryDomainArn] }),
resourceType: 'Custom::CoreArtifactDomainDescription',
});
this.#s3BucketArn = domainDescription.getResponseField('domain.s3BucketArn');
}
return this.#s3BucketArn;
}
public grantReadFromRepository(grantee: IGrantable): Grant {
// The Grant API does not allow conditions
const stsGrantResult = grantee.grantPrincipal.addToPrincipalPolicy(new PolicyStatement({
effect: Effect.ALLOW,
actions: ['sts:GetServiceBearerToken'],
conditions: { StringEquals: { 'sts:AWSServiceName': 'codeartifact.amazonaws.com' } },
resources: ['*'], // STS does not support resource-specified permissions
}));
if (!stsGrantResult.statementAdded) {
return Grant.drop(grantee, 'CodeArtifact:ReadFromRepository');
}
return Grant.addToPrincipal({
grantee,
actions: [
'codeartifact:GetAuthorizationToken',
'codeartifact:GetRepositoryEndpoint',
'codeartifact:ReadFromRepository',
],
resourceArns: [this.repositoryDomainArn, this.repositoryArn, this.publishingRepositoryArn],
});
}
public grantPublishToRepository(grantee: IGrantable, format = 'npm'): Grant {
const readOnlyGrant = this.grantReadFromRepository(grantee);
if (!readOnlyGrant.success) {
return readOnlyGrant;
}
return Grant.addToPrincipal({
grantee,
actions: [
'codeartifact:PublishPackageVersion',
'codeartifact:PutPackageMetadata',
],
resourceArns: [Stack.of(this).formatArn({
arnFormat: ArnFormat.SLASH_RESOURCE_NAME,
service: 'codeartifact',
resource: 'package',
resourceName: `${this.repositoryDomainName}/${this.publishingRepositoryName}/${format}/*`,
})],
});
}
/**
* Obtains a view of this repository that is intended to be accessed though
* VPC endpoints.
*
* @param apiEndpoint an `InterfaceVpcEndpoint` to the `codeartifact.api`
* service.
* @param repoEndpoint an `InterfaceVpcEndpoint` to the
* `codeartifact.repositories` service.
*
* @returns a view of this repository that appropriately grants permissions on
* the VPC endpoint policies, too.
*/
public throughVpcEndpoint(apiEndpoint: InterfaceVpcEndpoint, repoEndpoint: InterfaceVpcEndpoint): IRepository {
return new Proxy(this, {
get(target, property, _receiver) {
if (property === 'grantReadFromRepository') {
return decoratedGrantReadFromRepository.bind(target);
}
return (target as any)[property];
},
getOwnPropertyDescriptor(target, property) {
const realDescriptor = Object.getOwnPropertyDescriptor(target, property);
if (property === 'grantReadFromRepository') {
return {
...realDescriptor,
value: decoratedGrantReadFromRepository,
get: undefined,
set: undefined,
};
}
return realDescriptor;
},
});
function decoratedGrantReadFromRepository(this: Repository, grantee: IGrantable): Grant {
const mainGrant = this.grantReadFromRepository(grantee);
if (mainGrant.success) {
apiEndpoint.addToPolicy(new PolicyStatement({
effect: Effect.ALLOW,
actions: ['sts:GetServiceBearerToken'],
conditions: { StringEquals: { 'sts:AWSServiceName': 'codeartifact.amazonaws.com' } },
resources: ['*'], // STS does not support resource-specified permissions
principals: [grantee.grantPrincipal],
}));
apiEndpoint.addToPolicy(new PolicyStatement({
effect: Effect.ALLOW,
actions: ['codeartifact:GetAuthorizationToken', 'codeartifact:GetRepositoryEndpoint'],
resources: [this.repositoryDomainArn, this.repositoryArn],
principals: [grantee.grantPrincipal],
}));
repoEndpoint.addToPolicy(new PolicyStatement({
effect: Effect.ALLOW,
actions: ['codeartifact:ReadFromRepository'],
resources: [this.repositoryArn],
principals: [grantee.grantPrincipal],
}));
}
return mainGrant;
}
}
private makeUpstreamForId(externalConnection: string, { domain, repositoryName }: {domain: CfnDomain; repositoryName: string}): string {
return new CfnRepository(this, `Upstream:${externalConnection}`, {
domainName: domain.attrName,
description: `Upstream with external connection to ${externalConnection}`,
externalConnections: [externalConnection],
repositoryName: `${repositoryName}-${externalConnection.substr(7)}`,
}).attrName;
}
} | the_stack |
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output,
ViewEncapsulation,
} from '@angular/core';
import {
AbstractControl,
FormControl,
FormGroup,
} from '@angular/forms';
import { untilComponentDestroyed } from '@terminus/ngx-tools/utilities';
import { TsStyleThemeTypes } from '@terminus/ui/utilities';
import { BehaviorSubject } from 'rxjs';
/**
* Define the structure of the date range object used by {@link TsDateRangeComponent}
*/
export interface TsDateRange {
/**
* The start date of the range
*/
start: Date | undefined;
/**
* The end date of the range
*/
end: Date | undefined;
}
/**
* This is the date-range UI Component
*
* @example
* <ts-date-range
* [dateFormGroup]="myForm.get('dateRange')"
* endMaxDate="{{ new Date(2017, 4, 30) }}"
* endMinDate="{{ new Date(2017, 4, 1) }}"
* [isDisabled]="true"
* startingView="year"
* startMaxDate="{{ new Date(2017, 4, 30) }}"
* startMinDate="{{ new Date(2017, 4, 1) }}"
* theme="primary"
* (dateRangeChange)="myMethod($event)"
* (endSelected)="myMethod($event)"
* (startSelected)="myMethod($event)"
* ></ts-date-range>
*
* <example-url>https://getterminus.github.io/ui-demos-release/components/date-range</example-url>
*/
@Component({
selector: 'ts-date-range',
templateUrl: './date-range.component.html',
styleUrls: ['./date-range.component.scss'],
host: { class: 'ts-date-range' },
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
exportAs: 'tsDateRange',
})
export class TsDateRangeComponent implements OnInit, OnDestroy {
/**
* Getter to return the date range as an object
*
* @returns The current date range
*/
private get dateRange(): TsDateRange {
return {
start: this.startDateControl.value,
end: this.endDateControl.value,
};
}
/**
* Provide quick access to the endDate form control
*/
public get endDateControl(): AbstractControl {
const ctrl: AbstractControl | null = this.dateFormGroup ? this.dateFormGroup.get('endDate') : null;
return ctrl ? ctrl : this.internalEndControl;
}
/**
* Expose the minimum date for the endDate
*
* NOTE: `any` is used since we cannot seem to use union types in a BehaviorSubject and the value could be a Date or undefined
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public endMinDate$: BehaviorSubject<any> = new BehaviorSubject(undefined);
/**
* Define the end date label
*/
public endLabel = 'End date';
/**
* The internal FormControl to manage the end date
*/
public internalEndControl = new FormControl();
/**
* The internal FormControl to manage the start date
*/
public internalStartControl = new FormControl();
/**
* Define the separator between the two date inputs
*/
public separator = '-';
/**
* Provide quick access to the startDate form control
*/
public get startDateControl(): AbstractControl {
const ctrl: AbstractControl | null = this.dateFormGroup ? this.dateFormGroup.get('startDate') : null;
return ctrl ? ctrl : this.internalStartControl;
}
/**
* Expose the maximum date for the startDate
*
* NOTE: `any` is used since we cannot seem to use union types in a BehaviorSubject and the value could be a Date or undefined
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public startMaxDate$: BehaviorSubject<any> = new BehaviorSubject(undefined);
/**
* Define the start date label
*/
public startLabel = 'Start date';
/**
* Define the form group to attach the date range to
*
* @param value
*/
@Input()
public set dateFormGroup(value: FormGroup | AbstractControl | undefined) {
this._dateFormGroup = value;
}
public get dateFormGroup(): FormGroup | AbstractControl | undefined {
return this._dateFormGroup;
}
private _dateFormGroup: FormGroup | AbstractControl | undefined;
/**
* Define the date locale
*/
@Input()
public dateLocale: string | undefined;
/**
* Define the max date for the end date
*/
@Input()
public endMaxDate: Date | undefined;
/**
* Define the min date for the end date
*/
@Input()
public endMinDate: Date | undefined;
/**
* Define if the range should be disabled
*/
@Input()
public isDisabled = false;
/**
* Define the starting view for both datepickers
*/
@Input()
public startingView: 'month' | 'year' = 'month';
/**
* Define the max date for the starting date
*/
@Input()
public startMaxDate: Date | undefined;
/**
* Define the min date for the starting date
*/
@Input()
public startMinDate: Date | undefined;
/**
* Define the component theme
*/
@Input()
public theme: TsStyleThemeTypes = 'primary';
/**
* Event emitted anytime the range is changed
*/
@Output()
public readonly dateRangeChange: EventEmitter<TsDateRange> = new EventEmitter();
/**
* Output the end date when selected
*/
@Output()
public readonly endSelected: EventEmitter<Date | undefined> = new EventEmitter();
/**
* Output the start date when selected
*/
@Output()
public readonly startSelected: EventEmitter<Date | undefined> = new EventEmitter();
constructor(
private changeDetectorRef: ChangeDetectorRef,
) { }
/**
* Seed initial date range values
*/
public ngOnInit(): void {
// Seed values from a passed in form group
if (this.dateFormGroup) {
this.initializeMinAndMax(this.dateFormGroup);
}
// istanbul ignore else
if (!this.endDateControl.value) {
this.startMaxDate$.next(this.startMaxDate);
}
// istanbul ignore else
if (!this.startDateControl.value) {
this.endMinDate$.next(this.endMinDate);
}
this.setUpFormControlSync();
}
/**
* Needed for untilComponentDestroyed
*/
public ngOnDestroy(): void {}
/**
* Set up subscriptions to sync the internal FormControl to the external FormControl
*/
private setUpFormControlSync(): void {
if (!this.dateFormGroup) {
return;
}
const startCtrl = this.dateFormGroup.get('startDate');
const endCtrl = this.dateFormGroup.get('endDate');
if (!startCtrl || !endCtrl) {
return;
}
this.changeDetectorRef.detectChanges();
// HACK: This is to fix on an initial load, date range value isn't populating correctly.
this.internalStartControl.setValue(startCtrl.value);
this.internalEndControl.setValue(endCtrl.value);
// START DATE
startCtrl.valueChanges.pipe(untilComponentDestroyed(this)).subscribe(value => {
this.internalStartControl.setValue(value);
this.endMinDate$.next(value);
});
startCtrl.statusChanges.pipe(untilComponentDestroyed(this)).subscribe(() => {
this.internalStartControl.setErrors(startCtrl.errors);
});
// END DATE
endCtrl.valueChanges.pipe(untilComponentDestroyed(this)).subscribe(value => {
this.internalEndControl.setValue(value);
this.startMaxDate$.next(value);
});
endCtrl.statusChanges.pipe(untilComponentDestroyed(this)).subscribe(() => {
this.internalEndControl.setErrors(endCtrl.errors);
});
this.changeDetectorRef.detectChanges();
}
/**
* Set up initial min and max dates
*
* @param formGroup - The date form group
*/
private initializeMinAndMax(formGroup: FormGroup | AbstractControl): void {
const startControl: AbstractControl | null = formGroup.get('startDate');
const endControl: AbstractControl | null = formGroup.get('endDate');
const startControlValue: Date | undefined = startControl ? startControl.value /* istanbul ignore next - Unreachable */ : undefined;
const endControlValue: Date | undefined = endControl ? endControl.value /* istanbul ignore next - Unreachable */ : undefined;
const startValueToUse = startControlValue || this.endMinDate;
const endValueToUse = endControlValue || this.endMinDate;
this.endMinDate$.next(startValueToUse);
this.startMaxDate$.next(endValueToUse);
}
/**
* Emit the selected start date and date range
*
* @param date
*/
public startDateSelected(date: Date): void {
if (date) {
this.endMinDate$.next(date);
// Update the form value if a formGroup was passed in
// istanbul ignore else
if (this.dateFormGroup && this.startDateControl) {
this.startDateControl.setValue(date);
}
this.startSelected.emit(date);
this.dateRangeChange.emit(this.dateRange);
} else {
// If no startDate was selected, reset to the original endMinDate
this.endMinDate$.next(this.endMinDate);
}
}
/**
* Emit the selected end date and date range
*
* @param date
*/
public endDateSelected(date: Date): void {
if (date) {
this.startMaxDate$.next(date);
// Update the form value if a formGroup was passed in
// istanbul ignore else
if (this.dateFormGroup && this.endDateControl) {
this.endDateControl.setValue(date);
}
this.endSelected.emit(date);
this.dateRangeChange.emit(this.dateRange);
} else {
// If no endDate was selected, reset to the original startMaxDate
this.startMaxDate$.next(this.startMaxDate);
}
}
/**
* Update dates when the start date input receives a blur event
*
* @param date - The date entered
*/
public startBlur(date: Date | undefined): void {
const ctrl = this.dateFormGroup ? this.dateFormGroup.get('startDate') /* istanbul ignore next - Untestable */ : null;
const value = date ? date : null;
// Update the max date for the end date control
this.endMinDate$.next(value);
// Update the consumer's control
// istanbul ignore else
if (ctrl) {
ctrl.setValue(value);
ctrl.markAsTouched();
ctrl.updateValueAndValidity();
this.dateRangeChange.emit(this.dateRange);
}
}
/**
* Update dates when the end date input receives a blur event
*
* @param date - The date entered
*/
public endBlur(date: Date | undefined): void {
const ctrl = this.dateFormGroup ? this.dateFormGroup.get('endDate') /* istanbul ignore next - Untestable */ : null;
const value = date ? date : null;
// Update the max date for the start date control
this.startMaxDate$.next(value);
// Update the consumer's control
// istanbul ignore else
if (ctrl) {
ctrl.setValue(value);
ctrl.markAsTouched();
ctrl.updateValueAndValidity();
this.dateRangeChange.emit(this.dateRange);
}
}
} | the_stack |
import { geoAlbers, geoConicEqualArea, GeoStream, geoStream } from "d3-geo";
function noop() { }
let x0 = Infinity;
let y0 = x0;
let x1 = -x0;
let y1 = x1;
function boundsPoint(x, y) {
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
const boundsStream = {
point: boundsPoint,
lineStart: noop,
lineEnd: noop,
polygonStart: noop,
polygonEnd: noop,
result() {
const bounds = [[x0, y0], [x1, y1]];
x1 = y1 = -(y0 = x0 = Infinity);
return bounds;
}
};
function fitExtent(projection, extent, object) {
const w = extent[1][0] - extent[0][0];
const h = extent[1][1] - extent[0][1];
const clip = projection.clipExtent && projection.clipExtent();
projection
.scale(150)
.translate([0, 0]);
if (clip != null) projection.clipExtent(null);
geoStream(object, projection.stream(boundsStream));
const b = boundsStream.result();
const k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1]));
const x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2;
const y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;
if (clip != null) projection.clipExtent(clip);
return projection
.scale(k * 150)
.translate([x, y]);
}
function fitSize(projection, size, object) {
return fitExtent(projection, [[0, 0], size], object);
}
// const d3Geo = _d3Geo.geo || _d3Geo.default || _d3Geo;
// Origonally ased on geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
export class Geohash {
/* (Geohash-specific) Base32 map */
private static base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
/**
* Encodes latitude/longitude to geohash, either to specified precision or to automatically
* evaluated precision.
*
* @param {number} lat - Latitude in degrees.
* @param {number} lon - Longitude in degrees.
* @param {number} [precision] - Number of characters in resulting geohash.
* @returns {string} Geohash of supplied latitude/longitude.
* @throws Invalid geohash.
*
* @example
* var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: "u120fxw"
*/
encode(lat, lon, precision) {
// infer precision?
if (typeof precision === "undefined") {
// refine geohash until it matches precision of supplied lat/lon
for (let p = 1; p <= 12; p++) {
const hash = this.encode(lat, lon, p);
const posn = this.decode(hash);
if (posn.lat === lat && posn.lon === lon) return hash;
}
precision = 12; // set to maximum
}
lat = Number(lat);
lon = Number(lon);
precision = Number(precision);
if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error("Invalid geohash");
let idx = 0; // index into base32 map
let bit = 0; // each char holds 5 bits
let evenBit = true;
let geohash = "";
let latMin = -90;
let latMax = 90;
let lonMin = -180;
let lonMax = 180;
while (geohash.length < precision) {
if (evenBit) {
// bisect E-W longitude
const lonMid = (lonMin + lonMax) / 2;
if (lon > lonMid) {
idx = idx * 2 + 1;
lonMin = lonMid;
} else {
idx = idx * 2;
lonMax = lonMid;
}
} else {
// bisect N-S latitude
const latMid = (latMin + latMax) / 2;
if (lat > latMid) {
idx = idx * 2 + 1;
latMin = latMid;
} else {
idx = idx * 2;
latMax = latMid;
}
}
evenBit = !evenBit;
if (++bit === 5) {
// 5 bits gives us a character: append it and start over
geohash += Geohash.base32.charAt(idx);
bit = 0;
idx = 0;
}
}
return geohash;
}
/**
* Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
* to reasonable precision).
*
* @param {string} geohash - Geohash string to be converted to latitude/longitude.
* @returns {{lat:number, lon:number}} (Center of) geohashed location.
* @throws Invalid geohash.
*
* @example
* var latlon = Geohash.decode("u120fxw"); // latlon: { lat: 52.205, lon: 0.1188 }
*/
decode(geohash) {
const bounds = this.bounds(geohash); // <-- the hard work
// now just determine the centre of the cell...
const latMin = bounds.sw.lat;
const lonMin = bounds.sw.lon;
const latMax = bounds.ne.lat;
const lonMax = bounds.ne.lon;
// cell centre
let lat = (latMin + latMax) / 2;
let lon = (lonMin + lonMax) / 2;
// round to close to centre without excessive precision: ⌊2-log10(Δ°)⌋ decimal places
lat = Number(lat.toFixed(Math.floor(2 - Math.log(latMax - latMin) / Math.LN10)));
lon = Number(lon.toFixed(Math.floor(2 - Math.log(lonMax - lonMin) / Math.LN10)));
return { lat, lon };
}
/**
* Returns SW/NE latitude/longitude bounds of specified geohash.
*
* @param {string} geohash - Cell that bounds are required of.
* @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
* @throws Invalid geohash.
*/
bounds(geohash) {
if (geohash.length === 0) throw new Error("Invalid geohash");
geohash = geohash.toLowerCase();
let evenBit = true;
let latMin = -90;
let latMax = 90;
let lonMin = -180;
let lonMax = 180;
for (let i = 0; i < geohash.length; i++) {
const chr = geohash.charAt(i);
const idx = Geohash.base32.indexOf(chr);
if (idx === -1) throw new Error("Invalid geohash");
for (let n = 4; n >= 0; n--) {
const bitN = idx >> n & 1;
if (evenBit) {
// longitude
const lonMid = (lonMin + lonMax) / 2;
if (bitN === 1) {
lonMin = lonMid;
} else {
lonMax = lonMid;
}
} else {
// latitude
const latMid = (latMin + latMax) / 2;
if (bitN === 1) {
latMin = latMid;
} else {
latMax = latMid;
}
}
evenBit = !evenBit;
}
}
const bounds = {
sw: { lat: latMin, lon: lonMin },
ne: { lat: latMax, lon: lonMax }
};
return bounds;
}
/**
* Determines adjacent cell in given direction.
*
* @param geohash - Cell to which adjacent cell is required.
* @param direction - Direction from geohash (N/S/E/W).
* @returns {string} Geocode of adjacent cell.
* @throws Invalid geohash.
*/
adjacent(geohash, direction) {
// based on github.com/davetroy/geohash-js
geohash = geohash.toLowerCase();
direction = direction.toLowerCase();
if (geohash.length === 0) throw new Error("Invalid geohash");
if ("nsew".indexOf(direction) === -1) throw new Error("Invalid direction");
const neighbour = {
n: ["p0r21436x8zb9dcf5h7kjnmqesgutwvy", "bc01fg45238967deuvhjyznpkmstqrwx"],
s: ["14365h7k9dcfesgujnmqp0r2twvyx8zb", "238967debc01fg45kmstqrwxuvhjyznp"],
e: ["bc01fg45238967deuvhjyznpkmstqrwx", "p0r21436x8zb9dcf5h7kjnmqesgutwvy"],
w: ["238967debc01fg45kmstqrwxuvhjyznp", "14365h7k9dcfesgujnmqp0r2twvyx8zb"]
};
const border = {
n: ["prxz", "bcfguvyz"],
s: ["028b", "0145hjnp"],
e: ["bcfguvyz", "prxz"],
w: ["0145hjnp", "028b"]
};
const lastCh = geohash.slice(-1); // last character of hash
let parent = geohash.slice(0, -1); // hash without last character
const type = geohash.length % 2;
// check for edge-cases which don"t share common prefix
if (border[direction][type].indexOf(lastCh) !== -1 && parent !== "") {
parent = this.adjacent(parent, direction);
}
// append letter for direction to parent
return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
}
/**
* Returns all 8 adjacent cells to specified geohash.
*
* @param {string} geohash - Geohash neighbours are required of.
* @returns {{n,ne,e,se,s,sw,w,nw: string}}
* @throws Invalid geohash.
*/
neighbours(geohash) {
return {
n: this.adjacent(geohash, "n"),
ne: this.adjacent(this.adjacent(geohash, "n"), "e"),
e: this.adjacent(geohash, "e"),
se: this.adjacent(this.adjacent(geohash, "s"), "e"),
s: this.adjacent(geohash, "s"),
sw: this.adjacent(this.adjacent(geohash, "s"), "w"),
w: this.adjacent(geohash, "w"),
nw: this.adjacent(this.adjacent(geohash, "n"), "w")
};
}
// HPCC Extensions ---
contained(w, n, e, s, precision) {
if (isNaN(n) || n >= 90) n = 89;
if (isNaN(e) || e > 180) e = 180;
if (isNaN(s) || s <= -90) s = -89;
if (isNaN(w) || w < -180) w = -180;
precision = precision || 1;
const geoHashNW = this.encode(n, w, precision);
const geoHashNE = this.encode(n, e, precision);
const geoHashSE = this.encode(s, e, precision);
let currRowHash = geoHashNW;
let col = 0;
let maxCol = -1;
const geoHashes = [geoHashNW, geoHashSE];
let currHash = this.adjacent(geoHashNW, "e");
while (currHash !== geoHashSE) {
geoHashes.push(currHash);
++col;
if (currHash === geoHashNE || maxCol === col) {
maxCol = col + 1;
col = 0;
currHash = this.adjacent(currRowHash, "s");
currRowHash = currHash;
} else {
currHash = this.adjacent(currHash, "e");
}
}
return geoHashes;
}
calculateWidthDegrees(n) {
let a;
if (n % 2 === 0)
a = -1;
else
a = -0.5;
const result = 180 / Math.pow(2, 2.5 * n + a);
return result;
}
width(n) {
const parity = n % 2;
return 180 / (2 ^ (((5 * n + parity) / 2) - 1));
}
}
function multiplex(streams) {
const n = streams.length;
return {
point(x, y) { let i = -1; while (++i < n) streams[i].point(x, y); },
sphere() { let i = -1; while (++i < n) streams[i].sphere(); },
lineStart() { let i = -1; while (++i < n) streams[i].lineStart(); },
lineEnd() { let i = -1; while (++i < n) streams[i].lineEnd(); },
polygonStart() { let i = -1; while (++i < n) streams[i].polygonStart(); },
polygonEnd() { let i = -1; while (++i < n) streams[i].polygonEnd(); }
};
}
// A modified d3.geo.albersUsa to include Puerto Rico.
export function albersUsaPr() {
let cache;
let cacheStream;
const ε = 1e-6;
const lower48 = geoAlbers();
let lower48Point;
// EPSG:3338
const alaska = geoConicEqualArea()
.rotate([154, 0])
.center([-2, 58.5])
.parallels([55, 65]);
let alaskaPoint;
// ESRI:102007
const hawaii = geoConicEqualArea()
.rotate([157, 0])
.center([-3, 19.9])
.parallels([8, 18]);
let hawaiiPoint;
// XXX? You should check that this is a standard PR projection!
const puertoRico = geoConicEqualArea()
.rotate([66, 0])
.center([0, 18])
.parallels([8, 18]);
let puertoRicoPoint;
let point;
const pointStream = { point: (x, y) => { point = [x, y]; } } as GeoStream;
const albersUsa: any = function (coordinates) {
const x = coordinates[0];
const y = coordinates[1];
point = null;
(lower48Point.point(x, y), point) ||
(alaskaPoint.point(x, y), point) ||
(hawaiiPoint.point(x, y), point) ||
(puertoRicoPoint.point(x, y), point); // jshint ignore:line
return point;
};
albersUsa.invert = function (coordinates) {
const k = lower48.scale();
const t = lower48.translate();
const x = (coordinates[0] - t[0]) / k;
const y = (coordinates[1] - t[1]) / k;
return (y >= 0.120 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska
: y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii
: y >= 0.204 && y < 0.234 && x >= 0.320 && x < 0.380 ? puertoRico
: lower48).invert(coordinates);
};
// A naïve multi-projection stream.
// The projections must have mutually exclusive clip regions on the sphere,
// as this will avoid emitting interleaving lines and polygons.
albersUsa.stream = function (stream) {
return cache && cacheStream === stream ? cache : cache = multiplex([
lower48.stream(cacheStream = stream),
alaska.stream(stream),
hawaii.stream(stream),
puertoRico.stream(stream)
]);
};
albersUsa.precision = function (_) {
if (!arguments.length) return lower48.precision();
lower48.precision(_);
alaska.precision(_);
hawaii.precision(_);
puertoRico.precision(_);
return reset();
};
albersUsa.scale = function (_) {
if (!arguments.length) return lower48.scale();
lower48.scale(_);
alaska.scale(_ * 0.35);
hawaii.scale(_);
puertoRico.scale(_);
return albersUsa.translate(lower48.translate());
};
albersUsa.translate = function (_) {
if (!arguments.length) return lower48.translate();
const k = lower48.scale();
const x = +_[0];
const y = +_[1];
lower48Point = lower48
.translate(_)
.clipExtent([[x - 0.455 * k, y - 0.238 * k], [x + 0.455 * k, y + 0.238 * k]])
.stream(pointStream);
alaskaPoint = alaska
.translate([x - 0.307 * k, y + 0.201 * k])
.clipExtent([[x - 0.425 * k + ε, y + 0.120 * k + ε], [x - 0.214 * k - ε, y + 0.234 * k - ε]])
.stream(pointStream);
hawaiiPoint = hawaii
.translate([x - 0.205 * k, y + 0.212 * k])
.clipExtent([[x - 0.214 * k + ε, y + 0.166 * k + ε], [x - 0.115 * k - ε, y + 0.234 * k - ε]])
.stream(pointStream);
puertoRicoPoint = puertoRico
.translate([x + 0.350 * k, y + 0.224 * k])
.clipExtent([[x + 0.320 * k, y + 0.204 * k], [x + 0.380 * k, y + 0.234 * k]])
.stream(pointStream);
return reset();
};
albersUsa.fitExtent = function (extent, object) {
return fitExtent(albersUsa, extent, object);
};
albersUsa.fitSize = function (size, object) {
return fitSize(albersUsa, size, object);
};
function reset() {
cache = cacheStream = null;
return albersUsa;
}
return albersUsa.scale(1070);
} | the_stack |
import express = require("express");
import * as eris from "eris";
import randomstring = require("randomstring");
import Joi = require("joi");
import { Server, User, BlacklistedChannel, Role, RoleCondition, LeagueAccount } from "../database";
import { requireAuth, swallowErrors } from "./decorators";
import { REGIONS } from "../riot/api";
import DiscordClient from "../discord/client";
import config from "../config";
import * as crypto from "crypto";
import * as ipc from "../cluster/master-ipc";
import { default as getTranslator, getLanguages as getI18nLanguages } from "../i18n";
export default class WebAPIClient {
private bot: eris.Client;
private summoners: Map<string, riot.Summoner & { region: string, targetSummonerIcon: number }> = new Map();
constructor(private client: DiscordClient, private app: express.Application) {
this.bot = client.bot;
app.get("/api/v1/commands", swallowErrors(this.serveCommands));
app.get("/api/v1/languages", swallowErrors(this.serveLanguages));
app.get("/api/v1/user", swallowErrors(this.serveUserProfile));
app.patch("/api/v1/user", swallowErrors(this.patchUserProfile));
app.post("/api/v1/summoner", swallowErrors(this.lookupSummoner));
app.post("/api/v1/user/accounts", swallowErrors(this.addUserAccount));
app.patch("/api/v1/user/account/:accountId", swallowErrors(this.updateAccountSettings));
app.delete("/api/v1/user/accounts", swallowErrors(this.deleteUserAccount));
app.get("/api/v1/user/:id/accounts", swallowErrors(this.serveUserAccounts));
app.get("/api/v1/server/:id", swallowErrors(this.serveServer));
app.patch("/api/v1/server/:id", swallowErrors(this.patchServer));
app.post("/api/v1/server/:id/blacklisted_channels", swallowErrors(this.addBlacklistedChannel));
app.delete("/api/v1/server/:id/blacklisted_channels", swallowErrors(this.deleteBlacklistedChannel));
app.post("/api/v1/server/:id/role", swallowErrors(this.addRole));
app.post("/api/v1/server/:id/role/preset/:name", swallowErrors(this.addRolePreset));
app.post("/api/v1/server/:id/role/:role", swallowErrors(this.updateRole));
app.delete("/api/v1/server/:id/role/:role", swallowErrors(this.deleteRole));
app.post("/api/v1/server/:id/role/:role/link", swallowErrors(this.linkRoleWithDiscord));
}
/**
* Serves a static list of all commands registered with the discord command handler,
* for documentation purposes on the website.
*/
private serveCommands = async (req: express.Request, res: express.Response) => {
const language = req.query.language || "en-US";
res.json(this.client.commands.filter(x => !x.hideFromHelp).map(cmd => ({
name: cmd.name,
description: getTranslator(language)[cmd.descriptionKey],
keywords: cmd.keywords
})));
};
/**
* Serves a static list of all languages supported for discord translation.
*/
private serveLanguages = async (req: express.Request, res: express.Response) => {
res.json(getI18nLanguages());
};
/**
* Serves the user profile, with guilds they can manage and their accounts + settings.
*/
private serveUserProfile = requireAuth(async (req: express.Request, res: express.Response) => {
const guilds = [];
for (const guild of this.bot.guilds.filter(x => x.members.has(req.user.snowflake))) {
const member = guild.members.get(req.user.snowflake)!;
// Make sure the user can manage server (or is the owner).
if (!member.permission.has("manageGuild") && member.id !== config.discord.owner) continue;
// Make sure that the server is configured with ori (should always be the case).
if (!(await Server.query().where("snowflake", guild.id).first())) continue;
guilds.push({
id: guild.id,
name: guild.name,
icon: guild.iconURL || "https://discordapp.com/assets/dd4dbc0016779df1378e7812eabaa04d.png"
});
}
// Load user accounts.
await req.user.$loadRelated("accounts");
res.json({
...req.user.toJSON(),
avatar: req.user.avatarURL,
guilds
});
});
/**
* Handles updates to user settings, in particular the privacy toggles.
*/
private patchUserProfile = requireAuth(async (req: express.Request, res: express.Response) => {
if (!this.validate({
treat_as_unranked: Joi.bool().optional(),
language: Joi.any().valid("", ...getI18nLanguages().map(x => x.code)).optional()
}, req, res)) return;
if (typeof req.body.treat_as_unranked !== "undefined") {
await req.user.$query().patch({
treat_as_unranked: req.body.treat_as_unranked
});
}
if (typeof req.body.language !== "undefined") {
await req.user.$query().patch({
language: req.body.language
});
}
return res.json({ ok: true });
});
/**
* Queries for a summoner and returns the summoner data plus validation code if found.
* Returns null and 404 if the summoner cannot be found.
*/
private lookupSummoner = async (req: express.Request, res: express.Response) => {
if (!this.validate( {
username: Joi.string().required(),
region: Joi.any().valid(REGIONS)
}, req, res)) return;
const summ = await this.client.riotAPI.getLoLSummonerByName(req.body.region, req.body.username);
if (!summ) return res.status(404).json(null);
let taken = false;
// Check if this account has been taken by someone else already.
if (await LeagueAccount.query().where("summoner_id", summ.id).where("region", req.body.region).first()) {
taken = true;
}
// Generate a key and assign it for the current session.
// Note that this will expire if we restart, but that should rarely happen.
const key = randomstring.generate({
length: 8,
readable: true
});
let targetSummonerIcon = 0;
do {
targetSummonerIcon = Math.floor(Math.random() * 28);
} while (targetSummonerIcon === summ.profileIconId);
this.summoners.set(key, {
...summ,
region: req.body.region,
targetSummonerIcon
});
return res.json({
taken,
region: req.body.region,
username: summ.name,
account_id: summ.accountId,
summoner_id: summ.id,
targetSummonerIcon,
code: key
});
};
/**
* Adds the specified summoner with the specified code to the currently logged in user.
*/
private addUserAccount = requireAuth(async (req: express.Request, res: express.Response) => {
if (!this.validate({
code: Joi.string().required() // must be a valid code
}, req, res)) return;
// Make sure that the code is valid.
const summoner = this.summoners.get(req.body.code);
if (!summoner) return res.status(400).json({ ok: false, error: "Invalid code." });
// Ensure that the summoner icon was updated properly.
const refreshedSummoner = await this.client.riotAPI.getLoLSummonerById(summoner.region, summoner.id);
if (!refreshedSummoner || refreshedSummoner.profileIconId !== summoner.targetSummonerIcon) {
return res.json({ ok: false });
}
// Check if this account has been taken by someone else already.
// If it has, remove it from the old account.
const oldAccount = await LeagueAccount.query().where("summoner_id", summoner.id).where("region", summoner.region).first();
if (oldAccount) {
const user = await User.query().where("id", oldAccount.user_id).first();
await oldAccount.$query().delete();
await ipc.fetchAndUpdateUser(user!);
}
// Find the matching TFT summoner.
const tftSummoner = await this.client.riotAPI.getTFTSummonerByName(summoner.region, summoner.name);
if (!tftSummoner) throw new Error("The TFT summoner for the LoL summoner " + summoner.name + " does not exist?");
// Add the user..
await req.user.addAccount(summoner.region, summoner, tftSummoner);
ipc.fetchAndUpdateUser(req.user);
return res.json({ ok: true });
});
/**
* Updates various settings for the specified account, such as if it is primary and if it should be included in profile.
*/
private updateAccountSettings = requireAuth(async (req: express.Request, res: express.Response) => {
await req.user.$loadRelated("accounts");
const target = req.user.accounts!.find(x => x.account_id === req.params.accountId);
if (!target) return res.status(404).json({ ok: false, error: "Unknown account" });
if (!this.validate({
primary: Joi.bool().optional(),
show_in_profile: Joi.bool().optional(),
include_region: Joi.bool().optional()
}, req, res)) return;
// Update the primary if it is toggled to true. We don't handle toggling to false.
if (typeof req.body.primary !== "undefined" && req.body.primary) {
// Un-primary any accounts that were previously primary.
for (const acc of req.user.accounts!) {
if (acc.primary) {
acc.primary = false;
await acc.$query().patch({
primary: false
});
}
}
// Make the account primary.
target.primary = true;
await target.$query().patch({
primary: true
});
}
// Update other settings as appropriate.
if (typeof req.body.show_in_profile !== "undefined" || typeof req.body.include_region !== "undefined") {
delete req.body.primary;
await target.$query().patch(req.body);
}
// Run an update in the background.
ipc.fetchAndUpdateUser(req.user);
return res.json({ ok: true });
});
/**
* Deletes the specified account from the user's profile.
*/
private deleteUserAccount = requireAuth(async (req: express.Request, res: express.Response) => {
if (!this.validate(Joi.object({
summoner_id: Joi.string(),
region: Joi.any().valid(REGIONS)
}).unknown(true), req, res)) return;
await req.user.$loadRelated("accounts");
const toDelete = req.user.accounts!.find(x => x.region === req.body.region && x.summoner_id === req.body.summoner_id);
if (!toDelete) return res.status(400).json(null);
await toDelete.$query().delete();
// If this was the primary account, and we have other accounts, mark a random other account as primary.
if (toDelete.primary) {
toDelete.primary = false;
const newPrimary = req.user.accounts!.find(x => x.id !== toDelete.id && !x.primary);
if (newPrimary) {
newPrimary.primary = true;
await newPrimary.$query().patch({
primary: true
});
}
}
// Don't await so we can return without doing this.
// TODO: Maybe instead of updating now just put it in the queue?
ipc.fetchAndUpdateUser(req.user);
return res.json({ ok: true });
});
/**
* Exposes a list of all accounts connected to the specified user id, similar to
* the list command, but in JSON format.
*/
private serveUserAccounts = async (req: express.Request, res: express.Response) => {
const user = await User.query().where("snowflake", req.params.id).eager("accounts").first();
if (!user) {
return res.status(200).json([]);
}
return res.status(200).json(user.accounts!.filter(x => x.show_in_profile).map(x => ({
id: crypto.createHash("md5").update(x.account_id).digest("hex"),
region: x.region,
summonerName: x.username
})));
};
/**
* Serves the settings and roles for the specified discord server id.
*/
private serveServer = requireAuth(async (req: express.Request, res: express.Response) => {
const { server, guild } = await this.verifyServerRequest(req, res);
if (!server) return;
await server.$loadRelated("roles.*");
await server.$loadRelated("blacklisted_channels");
// Find our highest rank, for web interface logic.
const us = guild.members.get(this.client.bot.user.id)!;
const highest = Math.max(...us.roles.map(x => guild.roles.get(x)!.position));
const channels = guild.channels.filter(x => x.type === 0).map(x => ({ id: x.id, name: x.name }));
const roles = guild.roles.filter(x => x.name !== "@everyone").map(x => ({
id: x.id,
name: x.name,
color: "#" + x.color.toString(16),
position: x.position
}));
return res.json({
...server.toJSON(),
discord: {
channels,
roles,
highestRole: highest
}
});
});
/**
* Handles a simple diff change patch for the specified server.
*/
private patchServer = requireAuth(async (req: express.Request, res: express.Response) => {
const { server, guild } = await this.verifyServerRequest(req, res);
if (!server) return;
// Check payload.
if (!this.validate({
// Announcement channel must be null or a valid channnel. Optional.
announcement_channel: Joi.any().valid(null, ...guild.channels.filter(x => x.type === 0).map(x => x.id)).optional(),
// Default champion must be a number or null. Optional.
default_champion: Joi.number().allow(null).optional(),
// Completed intro must be a boolean. Optional
completed_intro: Joi.boolean().optional(),
// Language must be a valid language.
language: Joi.any().valid(getI18nLanguages().map(x => x.code)).optional(),
// Nickname pattern must be a string
nickname_pattern: Joi.string().allow("").optional(),
// Engagement mode. Must match one of the patterns.
engagement: Joi.alt([
{ type: Joi.any().valid("on_command") },
{ type: Joi.any().valid("on_join") },
{ type: Joi.any().valid("on_react"), channel: Joi.string(), emote: Joi.string() }
]).optional(),
// Role requirement must be a role that exists, or null.
server_leaderboard_role_requirement: Joi.any().valid(null, ...guild.roles.map(x => x.id)).optional(),
}, req, res)) return;
// Convert engagement to the JSON representation.
if (req.body.engagement) {
req.body.engagement_json = JSON.stringify(req.body.engagement);
delete req.body.engagement;
}
await server.$query().update(req.body);
return res.json({ ok: true });
});
/**
* Adds a new blacklisted channel to the specified server.
*/
private addBlacklistedChannel = requireAuth(async (req: express.Request, res: express.Response) => {
const { server, guild } = await this.verifyServerRequest(req, res);
if (!server) return;
// Check payload.
if (!this.validate({
channel: Joi.any().valid(null, ...guild.channels.filter(x => x.type === 0).map(x => x.id))
}, req, res)) return;
// If the channel hasn't been marked as blacklisted already, add it.
await server.$loadRelated("blacklisted_channels");
if (!server.blacklisted_channels!.some(x => x.snowflake === req.body.channel) && req.body.channel) {
await server.$relatedQuery<BlacklistedChannel>("blacklisted_channels").insert({
snowflake: req.body.channel
});
}
return res.json({ ok: true });
});
/**
* Removes a blacklisted channel from the specified server.
*/
private deleteBlacklistedChannel = requireAuth(async (req: express.Request, res: express.Response) => {
const { server, guild } = await this.verifyServerRequest(req, res);
if (!server) return;
// Check payload.
if (!this.validate({
channel: Joi.any().valid(null, ...guild.channels.filter(x => x.type === 0).map(x => x.id))
}, req, res)) return;
// If the channel was marked as blacklisted, remove it.
await server.$loadRelated("blacklisted_channels");
const blacklistedChannel = server.blacklisted_channels!.find(x => x.snowflake === req.body.channel);
if (blacklistedChannel) {
await blacklistedChannel.$query().delete();
}
return res.json({ ok: true });
});
/**
* Adds a new role with the specified name and no conditions.
*/
private addRole = requireAuth(async (req: express.Request, res: express.Response) => {
const { server, guild } = await this.verifyServerRequest(req, res);
if (!server) return;
// Check payload.
if (!this.validate({
name: Joi.string()
}, req, res)) return;
const discordRole = guild.roles.find(x => x.name === req.body.name);
const role = await server.$relatedQuery<Role>("roles").insertAndFetch({
name: req.body.name,
announce: !!server.announcement_channel, // turn on announce based on whether or not we have an announcement channel set
snowflake: discordRole ? discordRole.id : ""
});
res.json({
...role.toJSON(),
conditions: []
});
});
/**
* Adds a new preset of roles to the specified server.
*/
private addRolePreset = requireAuth(async (req: express.Request, res: express.Response) => {
const { server, guild } = await this.verifyServerRequest(req, res);
if (!server) return;
const roleId = (name: string) => guild.roles.find(x => x.name === name) ? guild.roles.find(x => x.name === name)!.id : "";
if (req.params.name === "region") {
for (const region of REGIONS) {
await server.$relatedQuery<Role>("roles").insertGraph(<any>{
name: region,
announce: false,
snowflake: roleId(region),
conditions: [{
type: "server",
options: { region }
}]
});
}
} else if (req.params.name === "rank") {
for (let i = 0; i <= config.riot.tiers.length; i++) {
const name = i === 0 ? "Unranked" : (config.riot.tiers[i - 1].charAt(0) + config.riot.tiers[i - 1].toLowerCase().slice(1));
await server.$relatedQuery<Role>("roles").insertGraph(<any>{
name,
announce: false,
snowflake: roleId(name),
conditions: [{
type: "ranked_tier",
options: {
compare_type: "equal",
tier: i,
queue: req.body.queue
}
}]
});
}
} else if (req.params.name === "mastery") {
for (let i = 1; i <= 7; i++) {
await server.$relatedQuery<Role>("roles").insertGraph(<any>{
name: "Level " + i,
announce: server.announcement_channel !== null,
snowflake: roleId("Level " + i),
conditions: [{
type: "mastery_level",
options: {
compare_type: "exactly",
value: i,
champion: +req.body.champion
}
}]
});
}
} else if (req.params.name === "step") {
const formatNumber = (x: number) => x >= 1000000 ? (x / 1000000).toFixed(1).replace(/[.,]0$/, "") + "m" : (x / 1000).toFixed(0) + "k";
for (let i = req.body.start; i <= req.body.end; i += req.body.step) {
await server.$relatedQuery<Role>("roles").insertGraph(<any>{
name: formatNumber(i),
announce: server.announcement_channel !== null,
snowflake: roleId(formatNumber(i)),
conditions: [{
type: "mastery_score",
options: {
compare_type: "between",
min: i,
max: i + req.body.step,
champion: +req.body.champion
}
}]
});
}
} else {
res.status(400).json({ ok: false, error: "Invalid preset name" });
}
res.json({ ok: true });
});
/**
* Updates the specified role and role conditions.
*/
private updateRole = requireAuth(async (req: express.Request, res: express.Response) => {
const { server } = await this.verifyServerRequest(req, res);
if (!server) return;
// Check that role exists and belongs to server.
const role = await server.$relatedQuery<Role>("roles").findById(req.params.role);
if (!role) return;
// Check payload.
if (!this.validate({
name: Joi.string(),
announce: Joi.boolean(),
combinator: [
{ type: "all" },
{ type: "any" },
{ type: "at_least", amount: Joi.number().required() },
],
conditions: Joi.array().items({
type: Joi.string(),
options: Joi.object()
})
}, req, res)) return;
// Update role announce.
await role.$query().update({
announce: req.body.announce,
name: req.body.name,
combinator: req.body.combinator
});
// Drop all old conditions.
await role.$relatedQuery("conditions").delete();
// Insert new conditions.
for (const condition of req.body.conditions) {
await role.$relatedQuery<RoleCondition>("conditions").insert({
type: condition.type,
options: condition.options
});
}
res.json({ ok: true });
});
/**
* Deletes the specified role.
*/
private deleteRole = requireAuth(async (req: express.Request, res: express.Response) => {
const { server } = await this.verifyServerRequest(req, res);
if (!server) return;
// Check that role exists and belongs to server.
const role = await server.$relatedQuery<Role>("roles").findById(req.params.role);
if (!role) return;
await role.$query().delete();
res.json({ ok: true });
});
/**
* Either finds or creates a discord role for the specified Orianna role, then returns the created role.
*/
private linkRoleWithDiscord = requireAuth(async (req: express.Request, res: express.Response) => {
const { server, guild } = await this.verifyServerRequest(req, res);
if (!server) return;
// Check that role exists and belongs to server.
const role = await server.$relatedQuery<Role>("roles").findById(req.params.role);
if (!role) return;
// Find or create discord role.
let discordRole = guild.roles.find(x => x.name === role.name);
if (!discordRole) {
discordRole = (await guild.createRole({
name: role.name
}, "Linked to Orianna Bot role " + role.name))!;
}
// Write to database, return new/found discord role.
await role.$query().update({ snowflake: discordRole.id });
res.json({
id: discordRole.id,
name: discordRole.name,
color: discordRole.color.toString(16)
});
});
/**
* Validates the post contents of the specified request with the specified schema. Returns
* true if the request is valid, false otherwise. This will close the request if the request
* was invalid.
*/
private validate(schema: any, req: express.Request, res: express.Response): boolean {
const result = Joi.validate(req.body, schema);
if (result.error) {
res.status(400).json({ ok: false, error: result.error.message });
return false;
}
return true;
}
/**
* Checks that the requested server exists and that the current user has access. Returns a null
* server if something went wrong, valid values otherwise.
*/
private async verifyServerRequest(req: express.Request, res: express.Response): Promise<{ server: Server | null, guild: eris.Guild }> {
const server = await Server.query().where("snowflake", req.params.id).first();
if (!server) {
res.status(400).send({ ok: false, error: "Invalid server" });
return { server: null, guild: <any>null };
}
const guild = this.bot.guilds.get(server.snowflake);
if (!guild) {
res.status(400).send({ ok: false, error: "Server missing guild" });
return { server: null, guild: <any>null };
}
if (!this.hasAccess(req.user, server)) {
res.status(403).send({ ok: false, error: "No permissions" });
return { server: null, guild: <any>null };
}
return { server, guild };
}
/**
* Checks if the specified user has permissions to edit the specified server.
*/
private hasAccess(user: User, server: Server): boolean {
const guild = this.bot.guilds.get(server.snowflake);
if (!guild) return false;
// Owner always has access to server configs.
if (user.snowflake === config.discord.owner) return true;
// Check if the current user has access.
return guild.members.has(user.snowflake) && guild.members.get(user.snowflake)!.permission.has("manageMessages");
}
} | the_stack |
import { MessageHeaders } from "../src/IHubProtocol";
import { TransferFormat } from "../src/ITransport";
import { HttpClient, HttpRequest } from "../src/HttpClient";
import { ILogger } from "../src/ILogger";
import { ServerSentEventsTransport } from "../src/ServerSentEventsTransport";
import { getUserAgentHeader } from "../src/Utils";
import { VerifyLogger } from "./Common";
import { TestEventSource, TestMessageEvent } from "./TestEventSource";
import { TestHttpClient } from "./TestHttpClient";
import { registerUnhandledRejectionHandler } from "./Utils";
import { IHttpConnectionOptions } from "signalr/src/IHttpConnectionOptions";
registerUnhandledRejectionHandler();
describe("ServerSentEventsTransport", () => {
it("does not allow non-text formats", async () => {
await VerifyLogger.run(async (logger) => {
const sse = new ServerSentEventsTransport(new TestHttpClient(), undefined, logger,
{ logMessageContent: true, EventSource: TestEventSource, withCredentials: true, headers: {} });
await expect(sse.connect("", TransferFormat.Binary))
.rejects
.toEqual(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));
});
});
it("connect waits for EventSource to be connected", async () => {
await VerifyLogger.run(async (logger) => {
const sse = new ServerSentEventsTransport(new TestHttpClient(), undefined, logger,
{ logMessageContent: true, EventSource: TestEventSource, withCredentials: true, headers: {} });
let connectComplete: boolean = false;
const connectPromise = (async () => {
await sse.connect("http://example.com", TransferFormat.Text);
connectComplete = true;
})();
await TestEventSource.eventSource.openSet;
expect(connectComplete).toBe(false);
TestEventSource.eventSource.onopen(new TestMessageEvent());
await connectPromise;
expect(connectComplete).toBe(true);
});
});
it("connect failure does not call onclose handler", async () => {
await VerifyLogger.run(async (logger) => {
const sse = new ServerSentEventsTransport(new TestHttpClient(), undefined, logger,
{ logMessageContent: true, EventSource: TestEventSource, withCredentials: true, headers: {} });
let closeCalled = false;
sse.onclose = () => closeCalled = true;
const connectPromise = (async () => {
await sse.connect("http://example.com", TransferFormat.Text);
})();
await TestEventSource.eventSource.openSet;
TestEventSource.eventSource.onerror(new TestMessageEvent());
await expect(connectPromise)
.rejects
.toEqual(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."));
expect(closeCalled).toBe(false);
});
});
[["http://example.com", "http://example.com?access_token=secretToken"],
["http://example.com?value=null", "http://example.com?value=null&access_token=secretToken"]]
.forEach(([input, expected]) => {
it(`appends access_token to url ${input}`, async () => {
await VerifyLogger.run(async (logger) => {
await createAndStartSSE(logger, input, () => "secretToken");
expect(TestEventSource.eventSource.url).toBe(expected);
});
});
});
it("sets Authorization header on sends", async () => {
await VerifyLogger.run(async (logger) => {
let request: HttpRequest;
const httpClient = new TestHttpClient().on((r) => {
request = r;
return "";
});
const sse = await createAndStartSSE(logger, "http://example.com", () => "secretToken", { httpClient });
await sse.send("");
expect(request!.headers!.Authorization).toBe("Bearer secretToken");
expect(request!.url).toBe("http://example.com");
});
});
it("can send data", async () => {
await VerifyLogger.run(async (logger) => {
let request: HttpRequest;
const httpClient = new TestHttpClient().on((r) => {
request = r;
return "";
});
const sse = await createAndStartSSE(logger, "http://example.com", undefined, { httpClient });
await sse.send("send data");
expect(request!.content).toBe("send data");
});
});
it("can receive data", async () => {
await VerifyLogger.run(async (logger) => {
const sse = await createAndStartSSE(logger);
let received: string | ArrayBuffer;
sse.onreceive = (data) => {
received = data;
};
const message = new TestMessageEvent();
message.data = "receive data";
TestEventSource.eventSource.onmessage(message);
expect(typeof received!).toBe("string");
expect(received!).toBe("receive data");
});
});
it("stop closes EventSource and calls onclose", async () => {
await VerifyLogger.run(async (logger) => {
const sse = await createAndStartSSE(logger);
let closeCalled: boolean = false;
sse.onclose = () => {
closeCalled = true;
};
await sse.stop();
expect(closeCalled).toBe(true);
expect(TestEventSource.eventSource.closed).toBe(true);
});
});
it("can close from EventSource error", async () => {
await VerifyLogger.run(async (logger) => {
const sse = await createAndStartSSE(logger);
let closeCalled: boolean = false;
let error: Error | undefined;
sse.onclose = (e) => {
closeCalled = true;
error = e;
};
const errorEvent = new TestMessageEvent();
errorEvent.data = "error";
TestEventSource.eventSource.onerror(errorEvent);
expect(closeCalled).toBe(true);
expect(TestEventSource.eventSource.closed).toBe(true);
expect(error).toBeUndefined();
});
});
it("send throws if not connected", async () => {
await VerifyLogger.run(async (logger) => {
const sse = new ServerSentEventsTransport(new TestHttpClient(), undefined, logger,
{ logMessageContent: true, EventSource: TestEventSource, withCredentials: true, headers: {} });
await expect(sse.send(""))
.rejects
.toEqual(new Error("Cannot send until the transport is connected"));
});
});
it("closes on error from receive", async () => {
await VerifyLogger.run(async (logger) => {
const sse = await createAndStartSSE(logger);
sse.onreceive = () => {
throw new Error("error parsing");
};
let closeCalled: boolean = false;
let error: Error | undefined;
sse.onclose = (e) => {
closeCalled = true;
error = e;
};
const errorEvent = new TestMessageEvent();
errorEvent.data = "some data";
TestEventSource.eventSource.onmessage(errorEvent);
expect(closeCalled).toBe(true);
expect(TestEventSource.eventSource.closed).toBe(true);
expect(error).toEqual(new Error("error parsing"));
});
});
it("sets user agent header on connect and sends", async () => {
await VerifyLogger.run(async (logger) => {
let request: HttpRequest;
const httpClient = new TestHttpClient().on((r) => {
request = r;
return "";
});
const sse = await createAndStartSSE(logger, "http://example.com", undefined, { httpClient });
let [, value] = getUserAgentHeader();
expect((TestEventSource.eventSource.eventSourceInitDict as any).headers[`User-Agent`]).toEqual(value);
await sse.send("");
[, value] = getUserAgentHeader();
expect(request!.headers![`User-Agent`]).toBe(value);
expect(request!.url).toBe("http://example.com");
});
});
it("overwrites library headers with user headers", async () => {
await VerifyLogger.run(async (logger) => {
let request: HttpRequest;
const httpClient = new TestHttpClient().on((r) => {
request = r;
return "";
});
const headers = { "User-Agent": "Custom Agent", "X-HEADER": "VALUE" };
const sse = await createAndStartSSE(logger, "http://example.com", undefined, { httpClient, headers });
expect((TestEventSource.eventSource.eventSourceInitDict as any).headers["User-Agent"]).toEqual("Custom Agent");
expect((TestEventSource.eventSource.eventSourceInitDict as any).headers["X-HEADER"]).toEqual("VALUE");
await sse.send("");
expect(request!.headers!["User-Agent"]).toEqual("Custom Agent");
expect(request!.headers!["X-HEADER"]).toEqual("VALUE");
expect(request!.url).toBe("http://example.com");
});
});
it("sets timeout on sends", async () => {
await VerifyLogger.run(async (logger) => {
let request: HttpRequest;
const httpClient = new TestHttpClient().on((r) => {
request = r;
return "";
});
const sse = await createAndStartSSE(logger, "http://example.com", undefined, { httpClient, timeout: 123 });
await sse.send("");
expect(request!.timeout).toEqual(123);
});
});
});
async function createAndStartSSE(logger: ILogger, url?: string, accessTokenFactory?: (() => string | Promise<string>), options?: IHttpConnectionOptions): Promise<ServerSentEventsTransport> {
const sse = new ServerSentEventsTransport(options?.httpClient || new TestHttpClient(), accessTokenFactory, logger,
{ logMessageContent: true, EventSource: TestEventSource, withCredentials: true, timeout: 10205, ...options });
const connectPromise = sse.connect(url || "http://example.com", TransferFormat.Text);
await TestEventSource.eventSource.openSet;
TestEventSource.eventSource.onopen(new TestMessageEvent());
await connectPromise;
return sse;
} | the_stack |
import {
IGatsbyState,
IGatsbyPage,
IHtmlFileState,
IStaticQueryResultState,
} from "../../redux/types"
const platformSpy = jest.spyOn(require(`os`), `platform`)
interface IMinimalStateSliceForTest {
html: IGatsbyState["html"]
pages: IGatsbyState["pages"]
components: IGatsbyState["components"]
}
describe(`calcDirtyHtmlFiles`, () => {
let calcDirtyHtmlFiles
beforeEach(() => {
jest.isolateModules(() => {
calcDirtyHtmlFiles = require(`../build-utils`).calcDirtyHtmlFiles
})
})
function generateStateToTestHelper(
pages: Record<
string,
{
dirty: number
removedOrDeleted?: "deleted" | "not-recreated"
}
>
): IGatsbyState {
const state: IMinimalStateSliceForTest = {
pages: new Map<string, IGatsbyPage>(),
html: {
browserCompilationHash: `a-hash`,
ssrCompilationHash: `a-hash`,
trackedHtmlFiles: new Map<string, IHtmlFileState>(),
unsafeBuiltinWasUsedInSSR: false,
trackedStaticQueryResults: new Map<string, IStaticQueryResultState>(),
},
components: new Map(),
}
state.components.set(`/foo`, {
componentPath: `/foo`,
componentChunkName: `foo`,
pages: new Set(),
isInBootstrap: false,
query: ``,
serverData: false,
})
for (const pagePath in pages) {
const page = pages[pagePath]
if (page.removedOrDeleted !== `not-recreated`) {
state.pages.set(pagePath, {
component: `/foo`,
componentPath: `/foo`,
componentChunkName: `foo`,
context: {},
internalComponentName: `foo`,
isCreatedByStatefulCreatePages: false,
path: pagePath,
matchPath: undefined,
pluginCreatorId: `foo`,
// eslint-disable-next-line @typescript-eslint/naming-convention
pluginCreator___NODE: `foo`,
updatedAt: 1,
mode: `SSG`,
defer: false,
ownerNodeId: ``,
})
}
state.html.trackedHtmlFiles.set(pagePath, {
dirty: page.dirty,
pageDataHash: `a-hash`,
isDeleted: page.removedOrDeleted === `deleted`,
})
}
return state as IGatsbyState
}
it(`nothing changed`, () => {
const state = generateStateToTestHelper({
// page not dirty - we can reuse, so shouldn't be regenerated, deleted or cleaned up
"/to-reuse/": {
dirty: 0,
},
})
const results = calcDirtyHtmlFiles(state)
// as nothing changed nothing should be regenerated, deleted or cleaned up
expect(results.toRegenerate.sort()).toEqual([])
expect(results.toDelete.sort()).toEqual([])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([])
})
it(`content for few pages changed`, () => {
const state = generateStateToTestHelper({
// pages were marked as dirty for whatever reason
"/to-regenerate/": {
dirty: 42,
},
"/to-regenerate/nested/": {
dirty: 42,
},
})
const results = calcDirtyHtmlFiles(state)
// as pages are marked as dirty, artifacts for those should be (re)generated
expect(results.toRegenerate.sort()).toEqual([
`/to-regenerate/`,
`/to-regenerate/nested/`,
])
expect(results.toDelete.sort()).toEqual([])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([])
})
it(`few pages were deleted`, () => {
const state = generateStateToTestHelper({
// pages were deleted with `deletePage` action
"/deleted/": {
dirty: 0,
removedOrDeleted: `deleted`,
},
"/deleted/nested/": {
dirty: 42,
removedOrDeleted: `deleted`,
},
})
const results = calcDirtyHtmlFiles(state)
// as pages are marked as deleted, artifacts for those should be deleted
expect(results.toRegenerate.sort()).toEqual([])
expect(results.toDelete.sort()).toEqual([`/deleted/`, `/deleted/nested/`])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([])
})
it(`few pages were not re-created`, () => {
const state = generateStateToTestHelper({
// pages are tracked, but were not recreated
"/not-recreated/": {
dirty: 0,
removedOrDeleted: `not-recreated`,
},
"/not-recreated/nested/": {
dirty: 0,
removedOrDeleted: `not-recreated`,
},
})
const results = calcDirtyHtmlFiles(state)
// as pages are not recreated, artifacts for those should be deleted
expect(results.toRegenerate.sort()).toEqual([])
expect(results.toDelete.sort()).toEqual([
`/not-recreated/`,
`/not-recreated/nested/`,
])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([])
})
describe(`onCreatePage + deletePage + createPage that change path of a page (remove trailing slash)`, () => {
it(`page is dirty`, () => {
const state = generateStateToTestHelper({
// page was created, then deleted and similar page with slightly different path was created for it
// both page paths would result in same artifacts
"/remove-trailing-slashes-dirty/": {
dirty: 0,
removedOrDeleted: `deleted`,
},
"/remove-trailing-slashes-dirty": {
dirty: 42,
},
})
const results = calcDirtyHtmlFiles(state)
// as pages would generate artifacts with same filenames - we expect artifact for
// deleted page NOT to be deleted, but instead just tracking state clean up
// and regeneration of new page with adjusted path
expect(results.toRegenerate.sort()).toEqual([
`/remove-trailing-slashes-dirty`,
])
expect(results.toDelete.sort()).toEqual([])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([
`/remove-trailing-slashes-dirty/`,
])
})
it(`page is NOT dirty`, () => {
const state = generateStateToTestHelper({
// page was created, then deleted and similar page with slightly different path was created for it
// both page paths would result in same artifacts
"/remove-trailing-slashes-not-dirty/": {
dirty: 0,
removedOrDeleted: `deleted`,
},
"/remove-trailing-slashes-not-dirty": {
dirty: 0,
},
})
const results = calcDirtyHtmlFiles(state)
// as pages would generate artifacts with same filenames - we expect artifact for
// deleted page NOT to be deleted, but instead just tracking state clean up
// adjusted page is not marked as dirty so it shouldn't regenerate ()
expect(results.toRegenerate.sort()).toEqual([])
expect(results.toDelete.sort()).toEqual([])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([
`/remove-trailing-slashes-not-dirty/`,
])
})
})
it(`slash was removed between builds (without onCreatePage + deletePage combination)`, () => {
const state = generateStateToTestHelper({
// page was created in previous build, but not recreated in current one
// instead page with slightly different path is created
// both page paths would result in same artifacts
"/slash-removed-without-onCreatePage/": {
dirty: 0,
removedOrDeleted: `not-recreated`,
},
"/slash-removed-without-onCreatePage": {
dirty: 1,
},
})
const results = calcDirtyHtmlFiles(state)
expect(results.toRegenerate.sort()).toEqual([
`/slash-removed-without-onCreatePage`,
])
expect(results.toDelete.sort()).toEqual([])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([
`/slash-removed-without-onCreatePage/`,
])
})
describe(`onCreatePage + deletePage + createPage that change path casing of a page`, () => {
afterAll(() => {
platformSpy.mockRestore()
})
it(`linux (case sensitive file system)`, () => {
let isolatedCalcDirtyHtmlFiles
jest.isolateModules(() => {
platformSpy.mockImplementation(() => `linux`)
isolatedCalcDirtyHtmlFiles =
require(`../build-utils`).calcDirtyHtmlFiles
})
const state = generateStateToTestHelper({
// page was created, then deleted and similar page with slightly different path was created for it
// different artifacts would be created for them
"/TEST/": {
dirty: 0,
removedOrDeleted: `deleted`,
},
"/test/": {
dirty: 1,
},
})
const results = isolatedCalcDirtyHtmlFiles(state)
// on case sensitive file systems /test/ and /TEST/ are different files so we do need to delete a file
expect(results.toRegenerate.sort()).toEqual([`/test/`])
expect(results.toDelete.sort()).toEqual([`/TEST/`])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([])
})
it(`windows / mac (case insensitive file system)`, () => {
let isolatedCalcDirtyHtmlFiles
jest.isolateModules(() => {
platformSpy.mockImplementation(() => `win32`)
isolatedCalcDirtyHtmlFiles =
require(`../build-utils`).calcDirtyHtmlFiles
})
const state = generateStateToTestHelper({
// page was created, then deleted and similar page with slightly different path was created for it
// both page paths would result in same artifacts
"/TEST/": {
dirty: 0,
removedOrDeleted: `deleted`,
},
"/test/": {
dirty: 1,
},
})
const results = isolatedCalcDirtyHtmlFiles(state)
// on case insensitive file systems /test/ and /TEST/ are NOT different files so we should
// not delete files, but still we should cleanup tracked state
expect(results.toRegenerate.sort()).toEqual([`/test/`])
expect(results.toDelete.sort()).toEqual([])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([
`/TEST/`,
])
})
})
// cases above are to be able to pinpoint exact failure, kitchen sink case is to test all of above in one go
// and make sure that various conditions mixed together are handled correctly
it(`kitchen sink`, () => {
const state = generateStateToTestHelper({
// page not dirty - we can reuse, so shouldn't be regenerated, deleted or cleaned up
"/to-reuse/": {
dirty: 0,
},
// pages were marked as dirty for whatever reason
"/to-regenerate/": {
dirty: 42,
},
"/to-regenerate/nested/": {
dirty: 42,
},
// pages were deleted with `deletePage` action
"/deleted/": {
dirty: 0,
removedOrDeleted: `deleted`,
},
"/deleted/nested/": {
dirty: 42,
removedOrDeleted: `deleted`,
},
// pages are tracked, but were not recreated
"/not-recreated/": {
dirty: 0,
removedOrDeleted: `not-recreated`,
},
"/not-recreated/nested/": {
dirty: 0,
removedOrDeleted: `not-recreated`,
},
// page was created, then deleted and similar page with slightly different path was created for it
// both page paths would result in same artifacts
"/remove-trailing-slashes-dirty/": {
dirty: 0,
removedOrDeleted: `deleted`,
},
"/remove-trailing-slashes-dirty": {
dirty: 42,
},
// page was created, then deleted and similar page with slightly different path was created for it
// both page paths would result in same artifacts
"/remove-trailing-slashes-not-dirty/": {
dirty: 0,
removedOrDeleted: `deleted`,
},
"/remove-trailing-slashes-not-dirty": {
dirty: 0,
},
// page was created in previous build, but not recreated in current one
// instead page with slightly different path is created
// both page paths would result in same artifacts
"/slash-removed-without-onCreatePage/": {
dirty: 0,
removedOrDeleted: `not-recreated`,
},
"/slash-removed-without-onCreatePage": {
dirty: 1,
},
})
const results = calcDirtyHtmlFiles(state)
expect(results.toRegenerate.sort()).toEqual([
`/remove-trailing-slashes-dirty`,
`/slash-removed-without-onCreatePage`,
`/to-regenerate/`,
`/to-regenerate/nested/`,
])
expect(results.toDelete.sort()).toEqual([
`/deleted/`,
`/deleted/nested/`,
`/not-recreated/`,
`/not-recreated/nested/`,
])
expect(Array.from(results.toCleanupFromTrackedState).sort()).toEqual([
`/remove-trailing-slashes-dirty/`,
`/remove-trailing-slashes-not-dirty/`,
`/slash-removed-without-onCreatePage/`,
])
})
}) | the_stack |
import Currencies from '@tf2autobot/tf2-currencies';
import { genUserPure, genScrapAdjustment } from './userSettings';
import Bot from '../Bot';
import { EntryData, KeyPrices, PricelistChangedSource } from '../Pricelist';
import log from '../../lib/logger';
import { currPure } from '../../lib/tools/pure';
import sendAlert from '../../lib/DiscordWebhook/sendAlert';
export interface OverallStatus {
isBuyingKeys: boolean;
isBankingKeys: boolean;
checkAlertOnLowPure: boolean;
alreadyUpdatedToBank: boolean;
alreadyUpdatedToBuy: boolean;
alreadyUpdatedToSell: boolean;
}
type SetOverallStatus = [boolean, boolean, boolean, boolean, boolean, boolean];
interface OldAmount {
keysCanBuy: number;
keysCanSell: number;
keysCanBankMin: number;
keysCanBankMax: number;
ofKeys: number;
}
type SetOldAmount = [number, number, number, number, number];
export default class Autokeys {
get isEnabled(): boolean {
return this.bot.options.autokeys.enable;
}
get isKeyBankingEnabled(): boolean {
return this.bot.options.autokeys.banking.enable;
}
get isEnableScrapAdjustment(): boolean {
return genScrapAdjustment(
this.bot.options.autokeys.scrapAdjustment.value,
this.bot.options.autokeys.scrapAdjustment.enable
).enabled;
}
get scrapAdjustmentValue(): number {
return genScrapAdjustment(
this.bot.options.autokeys.scrapAdjustment.value,
this.bot.options.autokeys.scrapAdjustment.enable
).value;
}
get userPure(): {
minKeys: number;
maxKeys: number;
minRefs: number;
maxRefs: number;
} {
return genUserPure(
this.bot.options.autokeys.minKeys,
this.bot.options.autokeys.maxKeys,
this.bot.options.autokeys.minRefined,
this.bot.options.autokeys.maxRefined
);
}
private isActive = false;
private set setActiveStatus(set: boolean) {
this.isActive = set;
}
get getActiveStatus(): boolean {
return this.isActive;
}
private status: OverallStatus = {
isBuyingKeys: false,
isBankingKeys: false,
checkAlertOnLowPure: false,
alreadyUpdatedToBank: false,
alreadyUpdatedToBuy: false,
alreadyUpdatedToSell: false
};
private set setOverallStatus(set: SetOverallStatus) {
this.status = {
isBuyingKeys: set[0],
isBankingKeys: set[1],
checkAlertOnLowPure: set[2],
alreadyUpdatedToBank: set[3],
alreadyUpdatedToBuy: set[4],
alreadyUpdatedToSell: set[5]
};
}
get getOverallStatus(): OverallStatus {
return this.status;
}
private oldAmount: OldAmount = {
keysCanBuy: 0,
keysCanSell: 0,
keysCanBankMin: 0,
keysCanBankMax: 0,
ofKeys: 0
};
private set setOldAmount(set: SetOldAmount) {
this.oldAmount = {
keysCanBuy: set[0],
keysCanSell: set[1],
keysCanBankMin: set[2],
keysCanBankMax: set[3],
ofKeys: set[4]
};
}
private OldKeyPrices: { buy: Currencies; sell: Currencies };
constructor(private readonly bot: Bot) {
this.bot = bot;
}
check(): void {
log.debug(`checking autokeys (Enabled: ${String(this.isEnabled)})`);
if (this.isEnabled === false) {
return;
}
const userPure = this.userPure;
const userMinKeys = userPure.minKeys;
const userMaxKeys = userPure.maxKeys;
const userMinRef = userPure.minRefs;
const userMaxRef = userPure.maxRefs;
if (isNaN(userMinKeys) || isNaN(userMaxKeys) || isNaN(userMinRef) || isNaN(userMaxRef)) {
log.warn(
"You've entered a non-number on either your MINIMUM_KEYS/MINIMUM_REFINED/MAXIMUM_REFINED variables," +
' please correct it. Autokeys is disabled until you correct it.'
);
return;
}
const pure = currPure(this.bot);
const currKeys = pure.key;
const currRef = pure.refTotalInScrap;
const currKeyPrice = this.bot.pricelist.getKeyPrices;
if (currKeyPrice !== this.OldKeyPrices && this.isEnableScrapAdjustment) {
// When scrap adjustment activated, if key rate changes, then it will force update key prices after a trade.
this.setOverallStatus = [false, false, false, false, false, false];
this.OldKeyPrices = { buy: currKeyPrice.buy, sell: currKeyPrice.sell };
}
/** enable Autokeys - Buying - true if currRef \> maxRef AND currKeys \< maxKeys */
const isBuyingKeys = currRef > userMaxRef && currKeys < userMaxKeys;
/*
* <————————————○ \
* Keys ----|--------|----> ⟩ AND
* ○————> /
* Refs ----|--------|---->
* min max
*/
/** enable Autokeys - Selling - true if currRef \< minRef AND currKeys \> minKeys */
const isSellingKeys = currRef < userMinRef && currKeys > userMinKeys;
/*
* ○—————————————> \
* Keys ----|--------|----> ⟩ AND
* <———○ /
* Refs ----|--------|---->
* min max
*/
/**
* disable Autokeys - true if currRef \>= maxRef AND currKeys \>= maxKeys OR
* (minRef \<= currRef \<= maxRef AND currKeys \<= maxKeys)
*/
const isRemoveAutoKeys =
(currRef >= userMaxRef && currKeys >= userMaxKeys) ||
(currRef >= userMinRef && currRef <= userMaxRef && currKeys <= userMaxKeys);
/*
* <————————————●····> \
* Keys ----|--------|----> ⟩ AND
* ●————————●····> /
* Refs ----|--------|---->
* min max
* ^^|^^
* OR
*/
/** enable Autokeys - Banking - true if user set autokeys.banking.enable to true */
const isEnableKeyBanking = this.isKeyBankingEnabled;
/** enable Autokeys - Banking - true if minRef \< currRef \< maxRef AND currKeys \> minKeys */
const isBankingKeys = currRef > userMinRef && currRef < userMaxRef && currKeys > userMinKeys;
/*
* ○—————————————> \
* Keys ----|--------|----> ⟩ AND
* ○————————○ /
* Refs ----|-------|---->
* min max
*/
/** enable Autokeys - Banking - true if currRef \> minRef AND keys \< minKeys will buy keys. */
const isBankingBuyKeysWithEnoughRefs = currRef > userMinRef && currKeys <= userMinKeys;
/*
* <———● \
* Keys ----|--------|----> ⟩ AND
* ○—————————————> /
* Refs ----|--------|---->
* min max
*/
/** disable Autokeys - Banking - true if currRef \< minRef AND currKeys \< minKeys */
const isRemoveBankingKeys = currRef <= userMaxRef && currKeys <= userMinKeys;
/*
* <———● \
* Keys ----|--------|----> ⟩ AND
* <————————————● /
* Refs ----|--------|---->
* min max
*/
/** send alert to admins when both keys and refs below minimum */
const isAlertAdmins = currRef <= userMinRef && currKeys <= userMinKeys;
/*
* <———● \
* Keys ----|--------|----> ⟩ AND
* <———● /
* Refs ----|--------|---->
* min max
*/
let setMinKeys: number;
let setMaxKeys: number;
const rKeysCanBuy = Math.round((currRef - userMaxRef) / currKeyPrice.buy.toValue());
const rKeysCanSell = Math.round((userMinRef - currRef) / currKeyPrice.sell.toValue());
const rKeysCanBankMin = Math.round((userMaxRef - currRef) / currKeyPrice.sell.toValue());
const rKeysCanBankMax = Math.round((currRef - userMinRef) / currKeyPrice.buy.toValue());
// Check and set new min and max
if (isBuyingKeys) {
// If buying - we need to set min = currKeys and max = currKeys + CanBuy
const min = currKeys;
setMinKeys = min <= userMinKeys ? userMinKeys : min;
const max = currKeys + rKeysCanBuy;
setMaxKeys = max >= userMaxKeys ? userMaxKeys : max < 1 ? 1 : max;
if (setMinKeys === setMaxKeys) {
setMaxKeys += 1;
} else if (setMinKeys > setMaxKeys) {
setMaxKeys = setMinKeys + 1;
}
//
} else if (isBankingBuyKeysWithEnoughRefs && isEnableKeyBanking) {
// If buying (while banking) - we need to set min = currKeys and max = currKeys + CanBankMax
const min = currKeys;
setMinKeys = min <= userMinKeys ? userMinKeys : min;
const max = currKeys + rKeysCanBankMax;
setMaxKeys = max >= userMaxKeys ? userMaxKeys : max < 1 ? 1 : max;
if (setMinKeys === setMaxKeys) {
setMaxKeys += 1;
} else if (setMinKeys > setMaxKeys) {
setMaxKeys = setMinKeys + 2;
}
//
} else if (isSellingKeys) {
// If selling - we need to set min = currKeys - CanSell and max = currKeys
const min = currKeys - rKeysCanSell;
setMinKeys = min <= userMinKeys ? userMinKeys : min;
const max = currKeys;
setMaxKeys = max >= userMaxKeys ? userMaxKeys : max < 1 ? 1 : max;
if (setMinKeys === setMaxKeys) {
setMinKeys -= 1;
} else if (setMinKeys > setMaxKeys) {
setMaxKeys = setMinKeys + 1;
}
//
} else if (isBankingKeys && isEnableKeyBanking) {
// If banking - we need to set min = currKeys - CanBankMin and max = currKeys + CanBankMax
const min = currKeys - rKeysCanBankMin;
setMinKeys = min <= userMinKeys ? userMinKeys : min;
const max = currKeys + rKeysCanBankMax;
setMaxKeys = max >= userMaxKeys ? userMaxKeys : max < 1 ? 1 : max;
if (setMinKeys === setMaxKeys) {
setMinKeys -= 1;
} else if (setMaxKeys - setMinKeys === 1) {
setMaxKeys += 1;
} else if (setMinKeys > setMaxKeys) {
// When banking, the bot should be able to both buy and sell keys.
setMaxKeys = setMinKeys + 2;
}
// When banking, the bot should be able to both buy and sell keys.
if (setMaxKeys === currKeys) {
setMaxKeys += 1;
}
if (currKeys >= setMaxKeys) {
setMaxKeys = currKeys + 1;
}
}
const opt = this.bot.options;
const isBanking =
isBankingKeys &&
isEnableKeyBanking &&
(!this.status.alreadyUpdatedToBank ||
rKeysCanBankMin !== this.oldAmount.keysCanBankMin ||
rKeysCanBankMax !== this.oldAmount.keysCanBankMax ||
currKeys !== this.oldAmount.ofKeys);
const isTooManyRefWhileBanking =
isBankingBuyKeysWithEnoughRefs &&
isEnableKeyBanking &&
(!this.status.alreadyUpdatedToBuy ||
rKeysCanBankMax !== this.oldAmount.keysCanBuy ||
currKeys !== this.oldAmount.ofKeys);
const buyKeys =
isBuyingKeys &&
(!this.status.alreadyUpdatedToBuy ||
rKeysCanBuy !== this.oldAmount.keysCanBuy ||
currKeys !== this.oldAmount.ofKeys);
const sellKeys =
isSellingKeys &&
(!this.status.alreadyUpdatedToSell ||
rKeysCanSell !== this.oldAmount.keysCanSell ||
currKeys !== this.oldAmount.ofKeys);
if (this.isActive) {
// if Autokeys already running
if (isBanking) {
// enable keys banking - if banking conditions to enable banking matched and banking is enabled
this.setOverallStatus = [false, true, false, true, false, false];
this.setOldAmount = [0, 0, rKeysCanBankMin, rKeysCanBankMax, currKeys];
this.setActiveStatus = true;
this.updateToBank(setMinKeys, setMaxKeys, currKeyPrice);
//
} else if (isTooManyRefWhileBanking) {
// enable keys banking - if refs > minRefs but Keys < minKeys, will buy keys.
this.setOverallStatus = [true, false, false, false, true, false];
this.setOldAmount = [0, rKeysCanBankMax, 0, 0, currKeys];
this.setActiveStatus = true;
this.update(setMinKeys, setMaxKeys, currKeyPrice, 'buy');
//
} else if (buyKeys) {
// enable Autokeys - Buying - if buying keys conditions matched
this.setOverallStatus = [true, false, false, false, true, false];
this.setOldAmount = [0, rKeysCanBuy, 0, 0, currKeys];
this.setActiveStatus = true;
this.update(setMinKeys, setMaxKeys, currKeyPrice, 'buy');
//
} else if (sellKeys) {
// enable Autokeys - Selling - if selling keys conditions matched
this.setOverallStatus = [false, false, false, false, false, true];
this.setOldAmount = [rKeysCanSell, 0, 0, 0, currKeys];
this.setActiveStatus = true;
this.update(setMinKeys, setMaxKeys, currKeyPrice, 'sell');
//
} else if (isRemoveBankingKeys && isEnableKeyBanking) {
// disable keys banking - if to conditions to disable banking matched and banking is enabled
this.setOverallStatus = [false, false, false, false, false, false];
this.setActiveStatus = false;
void this.disable(currKeyPrice);
//
} else if (isRemoveAutoKeys && !isEnableKeyBanking) {
// disable Autokeys when conditions to disable Autokeys matched
this.setOverallStatus = [false, false, false, false, false, false];
this.setActiveStatus = false;
void this.disable(currKeyPrice);
//
} else if (isAlertAdmins && !this.status.checkAlertOnLowPure) {
// alert admins when low pure
this.setOverallStatus = [false, false, true, false, false, false];
this.setActiveStatus = false;
const msg = 'I am now low on both keys and refs.';
if (opt.sendAlert.enable && opt.sendAlert.autokeys.lowPure) {
if (opt.discordWebhook.sendAlert.enable && opt.discordWebhook.sendAlert.url !== '') {
sendAlert('lowPure', this.bot, msg);
} else {
this.bot.messageAdmins(msg, []);
}
}
}
} else {
// if Autokeys is not running/disabled
if (this.bot.pricelist.getPrice('5021;6', false) === null) {
// if Mann Co. Supply Crate Key entry does not exist in the pricelist.json
if (isBankingKeys && isEnableKeyBanking) {
//create new Key entry and enable keys banking - if banking conditions to enable banking matched and banking is enabled
this.setOverallStatus = [false, true, false, true, false, false];
this.setOldAmount = [0, 0, rKeysCanBankMin, rKeysCanBankMax, currKeys];
this.setActiveStatus = true;
this.createToBank(setMinKeys, setMaxKeys, currKeyPrice);
//
} else if (isBankingBuyKeysWithEnoughRefs && isEnableKeyBanking) {
// enable keys banking - if refs > minRefs but Keys < minKeys, will buy keys.
this.setOverallStatus = [true, false, false, false, true, false];
this.setOldAmount = [0, rKeysCanBankMax, 0, 0, currKeys];
this.setActiveStatus = true;
this.create(setMinKeys, setMaxKeys, currKeyPrice, 'buy');
//
} else if (isBuyingKeys) {
// create new Key entry and enable Autokeys - Buying - if buying keys conditions matched
this.setOverallStatus = [true, false, false, false, true, false];
this.setOldAmount = [0, rKeysCanBuy, 0, 0, currKeys];
this.setActiveStatus = true;
this.create(setMinKeys, setMaxKeys, currKeyPrice, 'buy');
//
} else if (isSellingKeys) {
// create new Key entry and enable Autokeys - Selling - if selling keys conditions matched
this.setOverallStatus = [false, false, false, false, false, true];
this.setOldAmount = [rKeysCanSell, 0, 0, 0, currKeys];
this.setActiveStatus = true;
this.create(setMinKeys, setMaxKeys, currKeyPrice, 'sell');
//
} else if (isAlertAdmins && !this.status.checkAlertOnLowPure) {
// alert admins when low pure
this.setOverallStatus = [false, false, true, false, false, false];
this.setActiveStatus = false;
const msg = 'I am now low on both keys and refs.';
if (opt.sendAlert.enable && opt.sendAlert.autokeys.lowPure) {
if (opt.discordWebhook.sendAlert.enable && opt.discordWebhook.sendAlert.url !== '') {
sendAlert('lowPure', this.bot, msg);
} else {
this.bot.messageAdmins(msg, []);
}
}
}
} else {
// if Mann Co. Supply Crate Key entry already in the pricelist.json
if (isBanking) {
// enable keys banking - if banking conditions to enable banking matched and banking is enabled
this.setOverallStatus = [false, true, false, true, false, false];
this.setOldAmount = [0, 0, rKeysCanBankMin, rKeysCanBankMax, currKeys];
this.setActiveStatus = true;
this.updateToBank(setMinKeys, setMaxKeys, currKeyPrice);
//
} else if (isTooManyRefWhileBanking) {
// enable keys banking - if refs > minRefs but Keys < minKeys, will buy keys.
this.setOverallStatus = [true, false, false, false, true, false];
this.setOldAmount = [0, rKeysCanBankMax, 0, 0, currKeys];
this.setActiveStatus = true;
this.update(setMinKeys, setMaxKeys, currKeyPrice, 'buy');
//
} else if (buyKeys) {
// enable Autokeys - Buying - if buying keys conditions matched
this.setOverallStatus = [true, false, false, false, true, false];
this.setOldAmount = [0, rKeysCanBuy, 0, 0, currKeys];
this.setActiveStatus = true;
this.update(setMinKeys, setMaxKeys, currKeyPrice, 'buy');
//
} else if (sellKeys) {
// enable Autokeys - Selling - if selling keys conditions matched
this.setOverallStatus = [false, false, false, false, false, true];
this.setOldAmount = [rKeysCanSell, 0, 0, 0, currKeys];
this.setActiveStatus = true;
this.update(setMinKeys, setMaxKeys, currKeyPrice, 'sell');
//
} else if (isAlertAdmins && !this.status.checkAlertOnLowPure) {
// alert admins when low pure
this.setOverallStatus = [false, false, true, false, false, false];
this.setActiveStatus = false;
const msg = 'I am now low on both keys and refs.';
if (opt.sendAlert.enable && opt.sendAlert.autokeys.lowPure) {
if (opt.discordWebhook.sendAlert.enable && opt.discordWebhook.sendAlert.url !== '') {
sendAlert('lowPure', this.bot, msg);
} else {
this.bot.messageAdmins(msg, []);
}
}
}
}
}
log.debug(
`Autokeys status:-\n Ref: minRef(${Currencies.toRefined(userMinRef)})` +
` < currRef(${Currencies.toRefined(currRef)})` +
` < maxRef(${Currencies.toRefined(userMaxRef)})` +
`\n Key: minKeys(${userMinKeys}) ≤ currKeys(${currKeys}) ≤ maxKeys(${userMaxKeys})` +
`\nStatus: ${
isBankingKeys && isEnableKeyBanking && this.isActive
? `Banking (Min: ${setMinKeys}, Max: ${setMaxKeys})`
: isBuyingKeys && this.isActive
? `Buying (Min: ${setMinKeys}, Max: ${setMaxKeys})`
: isSellingKeys && this.isActive
? `Selling (Min: ${setMinKeys}, Max: ${setMaxKeys})`
: 'Not active'
}`
);
}
private generateEntry(enabled: boolean, min: number, max: number, intent: 0 | 1 | 2): EntryData {
return {
sku: '5021;6',
enabled: enabled,
autoprice: true,
min: min,
max: max,
intent: intent
};
}
private setManual(entry: EntryData, keyPrices: KeyPrices): EntryData {
entry.autoprice = false;
entry.buy = {
keys: 0,
metal: keyPrices.buy.metal
};
entry.sell = {
keys: 0,
metal: keyPrices.sell.metal
};
return entry;
}
private setWithScrapAdjustment(entry: EntryData, keyPrices: KeyPrices, type: 'buy' | 'sell'): EntryData {
const optSA = this.bot.options.autokeys.scrapAdjustment;
const scrapAdjustment = genScrapAdjustment(optSA.value, optSA.enable);
entry.autoprice = false;
entry.buy = {
keys: 0,
metal: Currencies.toRefined(
keyPrices.buy.toValue() + (type === 'buy' ? scrapAdjustment.value : -scrapAdjustment.value)
)
};
entry.sell = {
keys: 0,
metal: Currencies.toRefined(
keyPrices.sell.toValue() + (type === 'buy' ? scrapAdjustment.value : -scrapAdjustment.value)
)
};
return entry;
}
private onError(
setActive: boolean,
msg: string,
isEnableSend: boolean,
sendToDiscord: boolean,
type: string
): void {
this.setActiveStatus = setActive;
log.warn(msg);
if (isEnableSend) {
if (sendToDiscord) {
sendAlert(type as AlertType, this.bot, msg);
} else {
this.bot.messageAdmins(msg, []);
}
}
}
private createToBank(minKeys: number, maxKeys: number, keyPrices: KeyPrices): void {
let entry = this.generateEntry(true, minKeys, maxKeys, 2);
if (keyPrices.src === 'manual') {
entry = this.setManual(entry, keyPrices);
}
this.bot.pricelist
.addPrice(entry, true, PricelistChangedSource.Autokeys)
.then(() => log.debug(`✅ Automatically added Mann Co. Supply Crate Key to bank.`))
.catch(err => {
const opt2 = this.bot.options;
this.onError(
false,
`❌ Failed to add Mann Co. Supply Crate Key to bank automatically: ${(err as Error).message}`,
opt2.sendAlert.enable && opt2.sendAlert.autokeys.failedToAdd,
opt2.discordWebhook.sendAlert.enable && opt2.discordWebhook.sendAlert.url !== '',
'autokeys-failedToAdd-bank'
);
});
}
private create(minKeys: number, maxKeys: number, keyPrices: KeyPrices, intent: 'buy' | 'sell'): void {
let entry = this.generateEntry(true, minKeys, maxKeys, intent === 'buy' ? 0 : 1);
if (keyPrices.src === 'manual' && !this.isEnableScrapAdjustment) {
entry = this.setManual(entry, keyPrices);
} else if (this.isEnableScrapAdjustment) {
entry = this.setWithScrapAdjustment(entry, keyPrices, intent);
}
this.bot.pricelist
.addPrice(entry, true, PricelistChangedSource.Autokeys)
.then(() => log.debug(`✅ Automatically added Mann Co. Supply Crate Key to ${intent}.`))
.catch(err => {
const opt2 = this.bot.options;
this.onError(
false,
`❌ Failed to add Mann Co. Supply Crate Key to ${intent} automatically: ${(err as Error).message}`,
opt2.sendAlert.enable && opt2.sendAlert.autokeys.failedToAdd,
opt2.discordWebhook.sendAlert.enable && opt2.discordWebhook.sendAlert.url !== '',
`autokeys-failedToAdd-${intent}`
);
});
}
private updateToBank(minKeys: number, maxKeys: number, keyPrices: KeyPrices): void {
let entry = this.generateEntry(true, minKeys, maxKeys, 2);
if (keyPrices.src === 'manual') {
entry = this.setManual(entry, keyPrices);
}
this.bot.pricelist
.updatePrice(entry, true, PricelistChangedSource.Autokeys)
.then(() => log.debug(`✅ Automatically updated Mann Co. Supply Crate Key to bank.`))
.catch(err => {
const opt2 = this.bot.options;
this.onError(
false,
`❌ Failed to update Mann Co. Supply Crate Key to bank automatically: ${(err as Error).message}`,
opt2.sendAlert.enable && opt2.sendAlert.autokeys.failedToUpdate,
opt2.discordWebhook.sendAlert.enable && opt2.discordWebhook.sendAlert.url !== '',
'autokeys-failedToUpdate-bank'
);
});
}
private update(minKeys: number, maxKeys: number, keyPrices: KeyPrices, intent: 'buy' | 'sell'): void {
let entry = this.generateEntry(true, minKeys, maxKeys, intent === 'buy' ? 0 : 1);
if (keyPrices.src === 'manual' && !this.isEnableScrapAdjustment) {
entry = this.setManual(entry, keyPrices);
} else if (this.isEnableScrapAdjustment) {
entry = this.setWithScrapAdjustment(entry, keyPrices, intent);
}
this.bot.pricelist
.updatePrice(entry, true, PricelistChangedSource.Autokeys)
.then(() => log.debug(`✅ Automatically update Mann Co. Supply Crate Key to ${intent}.`))
.catch(err => {
const opt2 = this.bot.options;
this.onError(
false,
`❌ Failed to update Mann Co. Supply Crate Key to ${intent} automatically: ${
(err as Error).message
}`,
opt2.sendAlert.enable && opt2.sendAlert.autokeys.failedToUpdate,
opt2.discordWebhook.sendAlert.enable && opt2.discordWebhook.sendAlert.url !== '',
`autokeys-failedToUpdate-${intent}`
);
});
}
disable(keyPrices: KeyPrices): Promise<void> {
return new Promise((resolve, reject) => {
const match = this.bot.pricelist.getPrice('5021;6', false);
if (match === null) {
return resolve();
}
if (!match.enabled) {
return resolve();
}
let entry = this.generateEntry(false, 0, 1, 2);
if (keyPrices.src === 'manual') {
entry = this.setManual(entry, keyPrices);
}
this.bot.pricelist
.updatePrice(entry, true, PricelistChangedSource.Autokeys)
.then(() => {
log.debug('✅ Automatically disabled Autokeys.');
resolve();
})
.catch(err => {
const opt2 = this.bot.options;
this.onError(
true,
`❌ Failed to disable Autokeys: ${(err as Error).message}`,
opt2.sendAlert.enable && opt2.sendAlert.autokeys.failedToDisable,
opt2.discordWebhook.sendAlert.enable && opt2.discordWebhook.sendAlert.url !== '',
'autokeys-failedToDisable'
);
reject();
});
});
}
refresh(): void {
this.setOverallStatus = [false, false, false, false, false, false];
this.setActiveStatus = false;
this.check();
}
}
type AlertType =
| 'autokeys-failedToDisable'
| 'autokeys-failedToAdd-bank'
| 'autokeys-failedToAdd-sell'
| 'autokeys-failedToAdd-buy'
| 'autokeys-failedToUpdate-bank'
| 'autokeys-failedToUpdate-sell'
| 'autokeys-failedToUpdate-buy'; | the_stack |
import { ensureLeadingSlash, inBrowser, isString } from '@vitebook/core';
import { tick } from 'svelte';
import { noop, raf } from 'svelte/internal';
import { get } from 'svelte/store';
import type { SvelteModule } from '../../shared';
import { currentPage } from '../stores/currentPage';
import { currentRoute } from '../stores/currentRoute';
import { pages } from '../stores/pages';
import type {
GoToRouteOptions,
NavigationOptions,
Route,
RouteLocation,
RouterOptions,
} from './types';
/**
* Adapted from https://github.com/sveltejs/kit/blob/master/packages/kit/src/runtime/client/router.js
*/
export class Router {
protected readonly history: History;
protected readonly routes: Map<string, Route> = new Map();
enabled = true;
baseUrl = '/';
scrollBehaviour?: ScrollBehavior = 'auto';
scrollOffset = () => ({ top: 0, left: 0 });
beforeNavigate?: (url: URL) => void | Promise<void>;
afterNavigate?: (url: URL) => void | Promise<void>;
protected _isReady = false;
protected _resolveReadyPromise?: () => void;
protected _isReadyPromise = new Promise(
(res) =>
(this._resolveReadyPromise = () => {
res(void 0);
this._isReady = true;
}),
);
get isReady() {
return this._isReady;
}
get waitUntilReady() {
return this._isReadyPromise;
}
constructor({ baseUrl, history, routes }: RouterOptions) {
this.baseUrl = baseUrl;
this.history = history;
routes?.forEach((route) => {
this.addRoute(route);
});
if (inBrowser) {
// make it possible to reset focus
document.body.setAttribute('tabindex', '-1');
// create initial history entry, so we can return here
this.history.replaceState(this.history.state || {}, '', location.href);
}
}
hasRoute(path: string) {
return this.routes.has(decodeURI(path));
}
addRoute(route: Route) {
this.routes.set(decodeURI(route.path), route);
}
removeRoute(route: string | Route) {
this.routes.delete(decodeURI(isString(route) ? route : route.path));
}
owns(url: URL) {
if (import.meta.env.SSR) return true;
return (
url.origin === location.origin && url.pathname.startsWith(this.baseUrl)
);
}
parse(url: URL): RouteLocation | undefined {
if (this.owns(url)) {
const path = ensureLeadingSlash(
url.pathname.slice(this.baseUrl.length) || '/',
);
const decodedPath = decodeURI(path);
const route =
this.routes.get(decodedPath) ?? this.routes.get('/404.html')!;
const query = new URLSearchParams(url.search);
const id = `${path}?${query}`;
return { id, route, path, query, hash: url.hash, decodedPath };
}
return undefined;
}
back() {
this.history.back();
}
async go(
href,
{
scroll = undefined,
replace = false,
keepfocus = false,
state = {},
}: GoToRouteOptions = {},
) {
const url = new URL(
href,
href.startsWith('#')
? /(.*?)(#|$)/.exec(location.href)![1]
: getBaseUri(this.baseUrl),
);
await this.beforeNavigate?.(url);
if (this.enabled && this.owns(url)) {
this.history[replace ? 'replaceState' : 'pushState'](state, '', href);
await this.navigate({
url,
scroll,
keepfocus,
hash: url.hash,
});
if (this._resolveReadyPromise) {
this._resolveReadyPromise();
this._resolveReadyPromise = undefined;
}
return;
}
location.href = url.href;
return new Promise(() => {
/* never resolves */
});
}
async prefetch(url: URL): Promise<void> {
const routeLocation = this.parse(url);
if (routeLocation?.route.redirect) {
await this.prefetch(
new URL(routeLocation.route.redirect, getBaseUri(this.baseUrl)),
);
return;
}
if (!routeLocation) {
throw new Error(
'Attempted to prefetch a URL that does not belong to this app',
);
}
await routeLocation.route.prefetch?.(routeLocation);
}
protected async navigate({
url,
keepfocus,
scroll,
hash,
}: NavigationOptions) {
const routeLocation = this.parse(url);
if (routeLocation?.route.redirect) {
// TODO: this doesn't forward hash or query string
await this.go(routeLocation.route.redirect, { replace: true });
return;
}
if (!routeLocation) {
throw new Error(
'Attempted to navigate to a URL that does not belong to this app',
);
}
const component = await routeLocation.route.loader(routeLocation);
if (!get(pages).find((page) => page.route === routeLocation.path)) {
currentPage.__set(undefined);
}
currentRoute.__set({
...routeLocation,
component: (component as SvelteModule).default ?? component,
});
await tick();
if (inBrowser) {
if (!keepfocus) {
document.body.focus();
}
if (scroll !== false) {
await this.scrollToPosition({ scroll, hash });
}
}
await this.afterNavigate?.(url);
}
protected async scrollToPosition({
scroll,
hash,
}: Pick<NavigationOptions, 'scroll' | 'hash'>) {
if (!inBrowser) return;
const deepLinked =
hash && document.getElementById(decodeURI(hash).slice(1));
const scrollTo = (options: ScrollToOptions) => {
if ('scrollBehavior' in document.documentElement.style) {
window.scrollTo(options);
} else {
window.scrollTo(options.left ?? 0, options.top ?? 0);
}
};
await raf(noop);
if (scroll) {
scrollTo({
left: scroll.x,
top: scroll.y,
behavior: this.scrollBehaviour,
});
} else if (deepLinked) {
const docRect = document.documentElement.getBoundingClientRect();
const elRect = deepLinked.getBoundingClientRect();
const offset = this.scrollOffset();
const left = elRect.left - docRect.left - offset.left;
const top = elRect.top - docRect.top - offset.top;
scrollTo({ left, top, behavior: this.scrollBehaviour });
} else {
scrollTo({ left: 0, top: 0, behavior: this.scrollBehaviour });
}
}
initListeners() {
if ('scrollRestoration' in this.history) {
this.history.scrollRestoration = 'manual';
}
// Adopted from Nuxt.js
// Reset scrollRestoration to auto when leaving page, allowing page reload
// and back-navigation from other pages to use the browser to restore the
// scrolling position.
addEventListener('beforeunload', () => {
this.history.scrollRestoration = 'auto';
});
// Setting scrollRestoration to manual again when returning to this page.
addEventListener('load', () => {
this.history.scrollRestoration = 'manual';
});
// There's no API to capture the scroll location right before the user
// hits the back/forward button, so we listen for scroll events
let scrollTimer;
addEventListener('scroll', () => {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(() => {
// Store the scroll location in the history
// This will persist even if we navigate away from the site and come back
const newState = {
...(this.history.state || {}),
'vitebook:scroll': scrollState(),
};
this.history.replaceState(
newState,
document.title,
window.location.href,
);
}, 50);
});
const hasPrefetched = new Set();
const triggerPrefetch = (event: MouseEvent | TouchEvent) => {
const a = findAnchor(event.target as Node | null);
if (
!a ||
!a.href ||
hasPrefetched.has(getHref(a)) ||
!getHref(a).startsWith(getBaseUri(this.baseUrl)) ||
!this.routes.has(decodeURI(getHrefURL(a).pathname))
) {
return;
}
this.prefetch(getHrefURL(a));
hasPrefetched.add(getHref(a));
};
let mouseMoveTimeout;
const handleMouseMove = (event: MouseEvent | TouchEvent) => {
clearTimeout(mouseMoveTimeout);
mouseMoveTimeout = setTimeout(() => {
triggerPrefetch(event);
}, 20);
};
addEventListener('touchstart', triggerPrefetch);
addEventListener('mousemove', handleMouseMove);
addEventListener('click', (event: MouseEvent) => {
if (!this.enabled) return;
// Adapted from https://github.com/visionmedia/page.js
// MIT license https://github.com/visionmedia/page.js#license
if (event.button || event.which !== 1) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
return;
if (event.defaultPrevented) return;
const a = findAnchor(event.target as Node | null);
if (!a || !a.href) return;
const url = getHrefURL(a);
const urlString = url.toString();
if (urlString === location.href) {
event.preventDefault();
if (location.hash) {
this.scrollToPosition({ hash: location.hash });
}
return;
}
// Ignore if tag has
// 1. 'download' attribute
// 2. 'rel' attribute includes external
const rel = (a.getAttribute('rel') || '').split(/\s+/);
if (a.hasAttribute('download') || (rel && rel.includes('external'))) {
return;
}
// Ignore if <a> has a target
if (a instanceof SVGAElement ? a.target.baseVal : a.target) return;
if (!this.owns(url)) return;
const i1 = urlString.indexOf('#');
const i2 = location.href.indexOf('#');
const u1 = i1 >= 0 ? urlString.substring(0, i1) : urlString;
const u2 = i2 >= 0 ? location.href.substring(0, i2) : location.href;
if (u1 === u2) {
this.go(decodeURI(url.hash), { replace: true });
return;
}
this.go(url.href);
event.preventDefault();
});
addEventListener('popstate', (event) => {
if (event.state && this.enabled) {
const url = new URL(location.href);
this.navigate({
url,
scroll: event.state['vitebook:scroll'],
});
}
});
}
}
function scrollState() {
return {
x: scrollX,
y: scrollY,
};
}
function findAnchor(node: Node | null): HTMLAnchorElement | SVGAElement | null {
while (node && node.nodeName.toUpperCase() !== 'A') node = node.parentNode; // SVG <a> elements have a lowercase name
return node as HTMLAnchorElement | SVGAElement;
}
function getHref(node: HTMLAnchorElement | SVGAElement): string {
return node instanceof SVGAElement ? node.href.baseVal : node.href;
}
function getHrefURL(node: HTMLAnchorElement | SVGAElement): URL {
return node instanceof SVGAElement
? new URL(node.href.baseVal, document.baseURI)
: new URL(node.href);
}
function getBaseUri(baseUrl = '/') {
return import.meta.env.SSR
? `https://ssr.com/${baseUrl}` // protocol/host irrelevant during SSR
: `${location.protocol}//${location.host}${baseUrl === '/' ? '' : baseUrl}`;
} | the_stack |
import {
EventEmitter, NextFunction, HookContext as BaseHookContext
} from './dependencies.ts';
type SelfOrArray<S> = S | S[];
type OptionalPick<T, K extends PropertyKey> = Pick<T, Extract<keyof T, K>>
export type { NextFunction };
export interface ServiceOptions {
events?: string[];
methods?: string[];
serviceEvents?: string[];
}
export interface ServiceMethods<T, D = Partial<T>> {
find (params?: Params): Promise<T | T[]>;
get (id: Id, params?: Params): Promise<T>;
create (data: D, params?: Params): Promise<T>;
update (id: NullableId, data: D, params?: Params): Promise<T | T[]>;
patch (id: NullableId, data: D, params?: Params): Promise<T | T[]>;
remove (id: NullableId, params?: Params): Promise<T | T[]>;
setup (app: Application, path: string): Promise<void>;
}
export interface ServiceOverloads<T, D> {
create? (data: D[], params?: Params): Promise<T[]>;
update? (id: Id, data: D, params?: Params): Promise<T>;
update? (id: null, data: D, params?: Params): Promise<T[]>;
patch? (id: Id, data: D, params?: Params): Promise<T>;
patch? (id: null, data: D, params?: Params): Promise<T[]>;
remove? (id: Id, params?: Params): Promise<T>;
remove? (id: null, params?: Params): Promise<T[]>;
}
export type Service<T, D = Partial<T>> =
ServiceMethods<T, D> &
ServiceOverloads<T, D>;
export type ServiceInterface<T, D = Partial<T>> =
Partial<ServiceMethods<T, D>>;
export interface ServiceAddons<A = Application, S = Service<any, any>> extends EventEmitter {
id?: string;
hooks (options: HookOptions<A, S>): this;
}
export interface ServiceHookOverloads<S> {
find (
params: Params,
context: HookContext
): Promise<HookContext>;
get (
id: Id,
params: Params,
context: HookContext
): Promise<HookContext>;
create (
data: ServiceGenericData<S> | ServiceGenericData<S>[],
params: Params,
context: HookContext
): Promise<HookContext>;
update (
id: NullableId,
data: ServiceGenericData<S>,
params: Params,
context: HookContext
): Promise<HookContext>;
patch (
id: NullableId,
data: ServiceGenericData<S>,
params: Params,
context: HookContext
): Promise<HookContext>;
remove (
id: NullableId,
params: Params,
context: HookContext
): Promise<HookContext>;
}
export type FeathersService<A = FeathersApplication, S = Service<any>> =
S & ServiceAddons<A, S> & OptionalPick<ServiceHookOverloads<S>, keyof S>;
export type CustomMethod<Methods extends string> = {
[k in Methods]: <X = any> (data: any, params?: Params) => Promise<X>;
}
export type ServiceMixin<A> = (service: FeathersService<A>, path: string, options?: ServiceOptions) => void;
export type ServiceGenericType<S> = S extends ServiceInterface<infer T> ? T : any;
export type ServiceGenericData<S> = S extends ServiceInterface<infer _T, infer D> ? D : any;
export interface FeathersApplication<ServiceTypes = any, AppSettings = any> {
/**
* The Feathers application version
*/
version: string;
/**
* A list of callbacks that run when a new service is registered
*/
mixins: ServiceMixin<Application<ServiceTypes, AppSettings>>[];
/**
* The index of all services keyed by their path.
*
* __Important:__ Services should always be retrieved via `app.service('name')`
* not via `app.services`.
*/
services: ServiceTypes;
/**
* The application settings that can be used via
* `app.get` and `app.set`
*/
settings: AppSettings;
/**
* A private-ish indicator if `app.setup()` has been called already
*/
_isSetup: boolean;
/**
* Contains all registered application level hooks.
*/
appHooks: HookMap<Application<ServiceTypes, AppSettings>, any>;
/**
* Retrieve an application setting by name
*
* @param name The setting name
*/
get<L extends keyof AppSettings & string> (name: L): AppSettings[L];
/**
* Set an application setting
*
* @param name The setting name
* @param value The setting value
*/
set<L extends keyof AppSettings & string> (name: L, value: AppSettings[L]): this;
/**
* Runs a callback configure function with the current application instance.
*
* @param callback The callback `(app: Application) => {}` to run
*/
configure (callback: (this: this, app: this) => void): this;
/**
* Returns a fallback service instance that will be registered
* when no service was found. Usually throws a `NotFound` error
* but also used to instantiate client side services.
*
* @param location The path of the service
*/
defaultService (location: string): ServiceInterface<any>;
/**
* Register a new service or a sub-app. When passed another
* Feathers application, all its services will be re-registered
* with the `path` prefix.
*
* @param path The path for the service to register
* @param service The service object to register or another
* Feathers application to use a sub-app under the `path` prefix.
* @param options The options for this service
*/
use<L extends keyof ServiceTypes & string> (
path: L,
service: keyof any extends keyof ServiceTypes ? ServiceInterface<any> | Application : ServiceTypes[L],
options?: ServiceOptions
): this;
/**
* Get the Feathers service instance for a path. This will
* be the service originally registered with Feathers functionality
* like hooks and events added.
*
* @param path The name of the service.
*/
service<L extends keyof ServiceTypes & string> (
path: L
): FeathersService<this, keyof any extends keyof ServiceTypes ? Service<any> : ServiceTypes[L]>;
setup (server?: any): Promise<this>;
/**
* Register application level hooks.
*
* @param map The application hook settings.
*/
hooks (map: HookOptions<this, any>): this;
}
// This needs to be an interface instead of a type
// so that the declaration can be extended by other modules
export interface Application<ServiceTypes = any, AppSettings = any> extends FeathersApplication<ServiceTypes, AppSettings>, EventEmitter {
}
export type Id = number | string;
export type NullableId = Id | null;
export interface Query {
[key: string]: any;
}
export interface Params {
query?: Query;
provider?: string;
route?: { [key: string]: string };
headers?: { [key: string]: any };
[key: string]: any; // (JL) not sure if we want this
}
export interface HookContext<A = Application, S = any> extends BaseHookContext<ServiceGenericType<S>> {
/**
* A read only property that contains the Feathers application object. This can be used to
* retrieve other services (via context.app.service('name')) or configuration values.
*/
readonly app: A;
/**
* A read only property with the name of the service method (one of find, get,
* create, update, patch, remove).
*/
readonly method: string;
/**
* A read only property and contains the service name (or path) without leading or
* trailing slashes.
*/
readonly path: string;
/**
* A read only property and contains the service this hook currently runs on.
*/
readonly service: S;
/**
* A read only property with the hook type (one of before, after or error).
* Will be `null` for asynchronous hooks.
*/
readonly type: null | 'before' | 'after' | 'error';
/**
* The list of method arguments. Should not be modified, modify the
* `params`, `data` and `id` properties instead.
*/
readonly arguments: any[];
/**
* A writeable property containing the data of a create, update and patch service
* method call.
*/
data?: ServiceGenericData<S>;
/**
* A writeable property with the error object that was thrown in a failed method call.
* It is only available in error hooks.
*/
error?: any;
/**
* A writeable property and the id for a get, remove, update and patch service
* method call. For remove, update and patch context.id can also be null when
* modifying multiple entries. In all other cases it will be undefined.
*/
id?: Id;
/**
* A writeable property that contains the service method parameters (including
* params.query).
*/
params: Params;
/**
* A writeable property containing the result of the successful service method call.
* It is only available in after hooks.
*
* `context.result` can also be set in
*
* - A before hook to skip the actual service method (database) call
* - An error hook to swallow the error and return a result instead
*/
result?: ServiceGenericType<S>;
/**
* A writeable, optional property and contains a 'safe' version of the data that
* should be sent to any client. If context.dispatch has not been set context.result
* will be sent to the client instead.
*/
dispatch?: ServiceGenericType<S>;
/**
* A writeable, optional property that allows to override the standard HTTP status
* code that should be returned.
*/
statusCode?: number;
/**
* The event emitted by this method. Can be set to `null` to skip event emitting.
*/
event: string|null;
}
// Legacy hook typings
export type LegacyHookFunction<A = Application, S = Service<any, any>> =
(this: S, context: HookContext<A, S>) => (Promise<HookContext<Application, S> | void> | HookContext<Application, S> | void);
export type Hook<A = Application, S = Service<any, any>> = LegacyHookFunction<A, S>;
type LegacyHookMethodMap<A, S> =
{ [L in keyof S]?: SelfOrArray<LegacyHookFunction<A, S>>; } &
{ all?: SelfOrArray<LegacyHookFunction<A, S>> };
type LegacyHookTypeMap<A, S> =
SelfOrArray<LegacyHookFunction<A, S>> | LegacyHookMethodMap<A, S>;
export type LegacyHookMap<A, S> = {
before?: LegacyHookTypeMap<A, S>,
after?: LegacyHookTypeMap<A, S>,
error?: LegacyHookTypeMap<A, S>
}
// New @feathersjs/hook typings
export type HookFunction<A = Application, S = Service<any, any>> =
(context: HookContext<A, S>, next: NextFunction) => Promise<void>;
export type HookMap<A, S> = {
[L in keyof S]?: HookFunction<A, S>[];
};
export type HookOptions<A, S> =
HookMap<A, S> | HookFunction<A, S>[] | LegacyHookMap<A, S>; | the_stack |
import { BroadcastChannel, createLeaderElection } from 'broadcast-channel';
import {
Path,
StateValueAtPath,
Plugin,
PluginCallbacks,
StateValueAtRoot,
none,
PluginCallbacksOnSetArgument,
State
} from '@hookstate/core';
type OnLeaderSubscriber = () => void
function activateLeaderElection() {
let thisInstanceId = -1
let isLeader = false;
let channel = new BroadcastChannel<number>('hookstate-broadcasted-system-channel');
let elector = createLeaderElection(channel);
const subscribers = new Set<OnLeaderSubscriber>()
const onLeader = () => {
thisInstanceId = Math.random()
const capturedInstanceId = thisInstanceId;
channel.postMessage(thisInstanceId)
// There is a bug in broadcast-channel
// which causes 2 leaders claimed elected simultaneously
// This is a workaround for the problem:
// the tab may revoke leadership itself (see above)
// so we delay the action
setTimeout(() => {
// if leadership has not been revoked
if (capturedInstanceId === thisInstanceId) {
isLeader = true
subscribers.forEach(s => s())
subscribers.clear()
}
}, 500)
}
const onMessage = (otherId: number) => {
if (thisInstanceId === -1) {
// has not been elected
return;
}
if (isLeader) {
window.location.reload()
// has been elected and the leadership has been established for this tab
// other tab can not claim it after, if it happened it is an error
}
window.console.warn('other tab claimed leadership too!')
if (otherId > thisInstanceId) {
window.console.warn('other tab has got leadership priority')
// revoke leadership
thisInstanceId = -1;
// and recreate the channel
channel.onmessage = null;
elector.die()
channel.close()
channel = new BroadcastChannel<number>('hookstate-broadcasted-system-channel');
channel.onmessage = onMessage
elector = createLeaderElection(channel);
elector.awaitLeadership().then(onLeader)
}
};
channel.onmessage = onMessage
elector.awaitLeadership().then(onLeader)
return {
subscribe(s: OnLeaderSubscriber) {
if (!isLeader) {
subscribers.add(s)
} else {
s()
}
},
unsubscribe(s: OnLeaderSubscriber) {
if (!isLeader) {
subscribers.delete(s)
}
}
}
}
const SystemLeaderSubscription = activateLeaderElection()
// SystemLeaderSubscription.subscribe(() => {
// if (window) {
// window.console.info('[@hookstate/broadcasted]: this tab is a leader')
// }
// })
interface BroadcastChannelHandle<T> {
topic: string,
channel: BroadcastChannel<T>,
onMessage: (m: T) => void
onLeader: () => void
}
function subscribeBroadcastChannel<T>(
topic: string,
onMessage: (m: T) => void,
onLeader: () => void): BroadcastChannelHandle<T> {
const channel = new BroadcastChannel<T>(topic);
channel.onmessage = (m) => onMessage(m);
SystemLeaderSubscription.subscribe(onLeader)
return {
topic,
channel,
onMessage,
onLeader
}
}
function unsubscribeBroadcastChannel<T>(handle: BroadcastChannelHandle<T>) {
SystemLeaderSubscription.unsubscribe(handle.onLeader)
handle.channel.onmessage = null;
handle.channel.close()
}
function generateUniqueId() {
return `${new Date().getTime().toString()}.${Math.random().toString(16)}`
}
interface BroadcastMessage {
readonly version: number;
readonly path: Path,
readonly value?: StateValueAtPath, // absent when None
readonly tag: string,
readonly expectedTag?: string,
readonly srcInstance: string,
readonly dstInstance?: string,
}
interface ServiceMessage {
readonly version: number;
readonly kind: 'request-initial';
readonly srcInstance: string;
}
type Writeable<T> = { -readonly [P in keyof T]: T[P] };
const PluginID = Symbol('Broadcasted');
class BroadcastedPluginInstance implements PluginCallbacks {
private broadcastRef: BroadcastChannelHandle<BroadcastMessage | ServiceMessage>;
private isDestroyed = false;
private isBroadcastEnabled = true;
private isLeader: boolean | undefined = undefined;
private currentTag = generateUniqueId();
private instanceId = generateUniqueId();
constructor(
readonly topic: string,
readonly state: State<StateValueAtRoot>,
readonly onLeader?: (link: State<StateValueAtRoot>, wasFollower: boolean) => void
) {
this.broadcastRef = subscribeBroadcastChannel(topic, (message: BroadcastMessage | ServiceMessage) => {
// window.console.trace('[@hookstate/broadcasted]: received message', topic, message)
if (message.version > 1) {
return;
}
if ('kind' in message) {
if (this.isLeader && message.kind === 'request-initial') {
this.submitValueFromState(message.srcInstance)
}
return;
}
if (message.path.length === 0 || !state.promised) {
if (message.dstInstance && message.dstInstance !== this.instanceId) {
return;
}
if (message.expectedTag && this.currentTag !== message.expectedTag) {
// window.console.trace('[@hookstate/broadcasted]: conflicting update at path:', message.path);
if (this.isLeader) {
this.submitValueFromState(message.srcInstance)
} else {
this.requestValue()
}
return;
}
let targetState = state;
for (let i = 0; i < message.path.length; i += 1) {
const p = message.path[i];
try {
targetState = targetState.nested(p)
} catch {
// window.console.trace('[@hookstate/broadcasted]: broken tree at path:', message.path);
this.requestValue()
return;
}
}
if (this.isLeader === undefined) {
this.isLeader = false; // follower
}
this.isBroadcastEnabled = false;
targetState.set('value' in message ? message.value : none)
this.currentTag = message.tag;
this.isBroadcastEnabled = true;
}
}, () => {
const wasFollower = this.isLeader === false
this.isLeader = true;
if (onLeader) {
onLeader(state, wasFollower)
} else if (!wasFollower) {
this.submitValueFromState()
}
})
this.requestValue()
}
requestValue() {
if (this.isDestroyed) {
return;
}
const message: ServiceMessage = {
version: 1,
kind: 'request-initial',
srcInstance: this.instanceId
}
// window.console.trace('[@hookstate/broadcasted]: sending message', this.topic, message);
this.broadcastRef.channel.postMessage(message)
}
submitValueFromState(dst?: string) {
let [_, controls] = this.state.attach(PluginID);
this.submitValue(
this.state.promised
? { path: [] }
: { path: [], value: controls.getUntracked() },
undefined,
dst)
}
submitValue(source: { path: Path, value?: StateValueAtRoot }, newTag?: string, dst?: string) {
if (this.isDestroyed) {
return;
}
const message: Writeable<BroadcastMessage> = {
...source,
version: 1,
tag: this.currentTag,
srcInstance: this.instanceId
}
if (newTag) {
message.expectedTag = this.currentTag
message.tag = newTag
this.currentTag = newTag
}
if (dst) {
message.dstInstance = dst
}
// window.console.trace('[@hookstate/broadcasted]: sending message', this.topic, message);
this.broadcastRef.channel.postMessage(message)
}
onDestroy() {
this.isDestroyed = true;
unsubscribeBroadcastChannel(this.broadcastRef)
}
onSet(p: PluginCallbacksOnSetArgument) {
if (this.isBroadcastEnabled) {
this.submitValue(
'value' in p ? { path: p.path, value: p.value } : { path: p.path },
generateUniqueId())
}
}
getTopic() {
return this.topic;
}
getInitial() {
return undefined;
}
}
interface BroadcastedExtensions {
topic(): string
}
// tslint:disable-next-line: function-name
export function Broadcasted<S>(
topic: string,
onLeader?: (link: State<StateValueAtRoot>, wasFollower: boolean) => void
): () => Plugin;
export function Broadcasted<S>(
self: State<S>
): BroadcastedExtensions;
export function Broadcasted<S>(
selfOrTopic: State<S> | string,
onLeader?: (link: State<StateValueAtRoot>, wasFollower: boolean) => void
): (() => Plugin) | BroadcastedExtensions {
if (typeof selfOrTopic !== 'string') {
const self = selfOrTopic as State<S>;
const [instance, ] = self.attach(PluginID);
if (instance instanceof Error) {
throw instance;
}
const inst = instance as BroadcastedPluginInstance;
return {
topic() {
return inst.getTopic();
}
}
}
return () => ({
id: PluginID,
init: (state) => {
return new BroadcastedPluginInstance(selfOrTopic as string, state, onLeader);
}
})
} | the_stack |
import { View } from 'tns-core-modules/ui/core/view';
import { topmost } from "tns-core-modules/ui/frame";
import { ios as iosUtils } from "tns-core-modules/utils/utils";
import { CardBrand, CardCommon, CreditCardViewBase, PaymentMethodCommon, Source, StripePaymentIntentCommon, StripePaymentIntentStatus, Token } from './stripe.common';
export * from "./stripe.common";
export class Stripe {
constructor(apiKey: string) {
STPPaymentConfiguration.sharedConfiguration().publishableKey = apiKey;
}
setStripeAccount(accountId: string) {
STPAPIClient.sharedClient().stripeAccount = accountId;
STPPaymentConfiguration.sharedConfiguration().stripeAccount = accountId;
}
createToken(card: CardCommon, cb: (error: Error, token: Token) => void): void {
if (!card) {
if (typeof cb === 'function') {
cb(new Error('Invalid card'), null);
}
return;
}
const apiClient = STPAPIClient.sharedClient();
apiClient.createTokenWithCardCompletion(
card.native,
callback(cb, (token: STPToken) => <Token>{
id: token.tokenId,
bankAccount: token.bankAccount,
card: card, // token.card is incomplete
created: new Date(token.created),
livemode: token.livemode,
android: null,
ios: token
})
);
}
createSource(card: CardCommon, cb: (error: Error, source: Source) => void): void {
if (!card) {
if (typeof cb === 'function') {
cb(new Error('Invalid card'), null);
}
return;
}
const sourceParams = STPSourceParams.cardParamsWithCard(card.native);
const apiClient = STPAPIClient.sharedClient();
apiClient.createSourceWithParamsCompletion(
sourceParams, callback(cb, (source: STPSource) => <Source>{
id: source.stripeID,
amount: source.amount,
card: card,
clientSecret: source.clientSecret,
created: new Date(source.created),
currency: source.currency,
livemode: source.livemode,
metadata: source.metadata
})
);
}
createPaymentMethod(card: CardCommon, cb: (error: Error, pm: PaymentMethod) => void): void {
if (!card) {
if (typeof cb === 'function') {
cb(new Error('Invalid card'), null);
}
return;
}
const apiClient = STPAPIClient.sharedClient();
const cardParams = STPPaymentMethodCardParams.new();
if (card.cvc) cardParams.cvc = card.cvc;
if (card.expMonth) cardParams.expMonth = card.expMonth;
if (card.expYear) cardParams.expYear = card.expYear;
if (card.number) cardParams.number = card.number;
const billing = STPPaymentMethodBillingDetails.new();
billing.address = STPPaymentMethodAddress.new();
if (card.addressLine1) billing.address.line1 = card.addressLine1;
if (card.addressLine2) billing.address.line2 = card.addressLine2;
if (card.addressCity) billing.address.city = card.addressCity;
if (card.addressState) billing.address.state = card.addressState;
if (card.addressZip) billing.address.postalCode = card.addressZip;
if (card.addressCountry) billing.address.country = card.addressCountry;
const params = STPPaymentMethodParams.paramsWithCardBillingDetailsMetadata(cardParams, billing, null);
apiClient.createPaymentMethodWithParamsCompletion(
params,
callback(cb, (pm) => PaymentMethod.fromNative(pm))
);
}
retrievePaymentIntent(clientSecret: string, cb: (error: Error, pm: StripePaymentIntent) => void): void {
const apiClient = STPAPIClient.sharedClient();
apiClient.retrievePaymentIntentWithClientSecretCompletion(
clientSecret,
callback(cb, (pi) => StripePaymentIntent.fromNative(pi))
);
}
confirmSetupIntent(paymentMethodId: string, clientSecret: string, cb: (error: Error, pm: StripeSetupIntent) => void): void {
STPPaymentHandler.sharedHandler().confirmSetupIntentWithAuthenticationContextCompletion(
new StripeSetupIntentParams(paymentMethodId, clientSecret).native,
this._getAuthentificationContext(),
(status: STPPaymentHandlerActionStatus, si: STPSetupIntent, error: NSError) => {
if (error) {
cb(new Error(error.toLocaleString()), null);
} else {
cb(null, StripeSetupIntent.fromNative(si));
}
}
);
}
authenticateSetupIntent(clientSecret: string, returnUrl: string, cb: (error: Error, pm: StripeSetupIntent) => void): void {
STPPaymentHandler.sharedHandler().handleNextActionForSetupIntentWithAuthenticationContextReturnURLCompletion(
clientSecret,
this._getAuthentificationContext(),
returnUrl,
(status: STPPaymentHandlerActionStatus, pi: STPSetupIntent, error: NSError) => {
if (error) {
cb(new Error(error.toLocaleString()), null);
} else {
cb(null, StripeSetupIntent.fromNative(pi));
}
}
);
}
confirmPaymentIntent(params: StripePaymentIntentParams, cb: (error: Error, pm: StripePaymentIntent) => void): void {
STPPaymentHandler.sharedHandler().confirmPaymentWithAuthenticationContextCompletion(
params.native,
this._getAuthentificationContext(),
(status: STPPaymentHandlerActionStatus, pi: STPPaymentIntent, error: NSError) => {
if (error) {
cb(new Error(error.toLocaleString()), null);
} else {
cb(null, StripePaymentIntent.fromNative(pi));
}
}
);
}
authenticatePaymentIntent(clientSecret: string, returnUrl: string, cb: (error: Error, pm: StripePaymentIntent) => void): void {
STPPaymentHandler.sharedHandler().handleNextActionForPaymentWithAuthenticationContextReturnURLCompletion(
clientSecret,
this._getAuthentificationContext(),
returnUrl,
(status: STPPaymentHandlerActionStatus, pi: STPPaymentIntent, error: NSError) => {
if (error) {
cb(new Error(error.toLocaleString()), null);
} else {
cb(null, StripePaymentIntent.fromNative(pi));
}
}
);
}
/*
*. Private
*/
private _getAuthentificationContext(): STPPaymentContext {
const authContext = STPPaymentContext.alloc();
const rootVC = topmost().currentPage.ios;
authContext.hostViewController = iosUtils.getVisibleViewController(rootVC);
authContext.authenticationPresentingViewController = () => {
return authContext.hostViewController;
};
return authContext;
}
}
function callback(
cb: (error: Error, value: any) => void,
cvt: (value: any) => any):
(value: any, err: NSError) => void {
return (value: any, error: NSError) => {
if (!error) {
if (typeof cb === 'function') {
cb(null, cvt(value));
}
} else {
if (typeof cb === 'function') {
cb(new Error(error.toLocaleString()), null);
}
}
};
}
export class Card implements CardCommon {
native: STPCardParams;
private _brand: CardBrand;
private _last4: string;
constructor(
cardNumber: string,
cardExpMonth: number,
cardExpYear: number,
cardCVC: string
) {
if (cardNumber && cardExpMonth && cardExpYear && cardCVC) {
this.native = STPCardParams.alloc().init();
this.native.number = cardNumber;
this.native.expMonth = cardExpMonth;
this.native.expYear = cardExpYear;
this.native.cvc = cardCVC;
}
}
public static fromNative(card: STPCardParams): Card {
const newCard = new Card(null, null, null, null);
newCard.native = card;
return newCard;
}
public static fromNativePaymentMethod(pm: STPPaymentMethod): Card {
const newCard = new Card(null, null, null, null);
const card = STPCardParams.alloc().init();
card.addressCountry = pm.card.country;
card.expMonth = pm.card.expMonth;
card.expYear = pm.card.expYear;
newCard._last4 = pm.card.last4;
newCard._brand = Card.toCardBrand(pm.card.brand);
newCard.native = card;
return newCard;
}
validateNumber(): boolean {
let isValid: boolean = false;
const state = STPCardValidator.validationStateForNumberValidatingCardBrand(
this.native.number,
true
);
switch (state) {
case STPCardValidationState.Valid:
isValid = true;
break;
case STPCardValidationState.Incomplete:
isValid = false;
break;
case STPCardValidationState.Invalid:
isValid = false;
break;
}
return isValid;
}
validateCVC(): boolean {
let isValid: boolean = false;
const brand = STPCardValidator.brandForNumber(this.native.number);
const state = STPCardValidator.validationStateForCVCCardBrand(
this.native.cvc,
brand
);
switch (state) {
case STPCardValidationState.Valid:
isValid = true;
break;
case STPCardValidationState.Incomplete:
isValid = false;
break;
case STPCardValidationState.Invalid:
isValid = false;
break;
}
return isValid;
}
validateCard(): boolean {
try {
return (
STPCardValidator.validationStateForCard(this.native) ===
STPCardValidationState.Valid
);
} catch (ex) {
return false;
}
}
validateExpMonth(): boolean {
let isValid: boolean = false;
const state = STPCardValidator.validationStateForExpirationMonth(
String(this.native.expMonth)
);
switch (state) {
case STPCardValidationState.Valid:
isValid = true;
break;
case STPCardValidationState.Incomplete:
isValid = false;
break;
case STPCardValidationState.Invalid:
isValid = false;
break;
}
return isValid;
}
validateExpiryDate(): boolean {
let isValid: boolean = false;
const state = STPCardValidator.validationStateForExpirationYearInMonth(
String(this.native.expYear),
String(this.native.expMonth)
);
switch (state) {
case STPCardValidationState.Valid:
isValid = true;
break;
case STPCardValidationState.Incomplete:
isValid = false;
break;
case STPCardValidationState.Invalid:
isValid = false;
break;
}
return isValid;
}
get number(): string {
return this.native.number;
}
get cvc(): string {
return this.native.cvc;
}
get expMonth(): number {
return this.native.expMonth;
}
get expYear(): number {
return this.native.expYear;
}
get name(): string {
return this.native.name;
}
set name(value: string) {
this.native.name = value;
}
get addressLine1(): string {
return this.native.addressLine1;
}
set addressLine1(value: string) {
this.native.addressLine1 = value;
}
get addressLine2(): string {
return this.native.addressLine2;
}
set addressLine2(value: string) {
this.native.addressLine2 = value;
}
get addressCity(): string {
return this.native.addressCity;
}
set addressCity(value: string) {
this.native.addressCity = value;
}
get addressZip(): string {
return this.native.addressZip;
}
set addressZip(value: string) {
this.native.addressZip = value;
}
get addressState(): string {
return this.native.addressState;
}
set addressState(value: string) {
this.native.addressState = value;
}
get addressCountry(): string {
return this.native.addressCountry;
}
set addressCountry(value: string) {
this.native.addressCountry = value;
}
get currency(): string {
return this.native.currency;
}
set currency(value: string) {
this.native.currency = value;
}
get last4(): string {
if (!this._last4) this._last4 = this.native.last4();
return this._last4;
}
get brand(): CardBrand {
if (!this._brand) this._brand = Card.toCardBrand(STPCardValidator.brandForNumber(this.native.number));
return this._brand;
}
private static toCardBrand(brand: STPCardBrand): CardBrand {
switch (brand) {
case STPCardBrand.Visa:
return 'Visa';
case STPCardBrand.Amex:
return 'Amex';
case STPCardBrand.MasterCard:
return 'MasterCard';
case STPCardBrand.Discover:
return 'Discover';
case STPCardBrand.JCB:
return 'JCB';
case STPCardBrand.DinersClub:
return 'DinersClub';
case STPCardBrand.UnionPay:
return 'UnionPay';
}
return 'Unknown';
}
private static fromCardBrand(brand: CardBrand): STPCardBrand {
switch (brand.toLowerCase()) {
case 'visa':
return STPCardBrand.Visa;
case 'amex':
case 'americanexpress':
case 'american_express':
case 'american express':
return STPCardBrand.Amex;
case 'mastercard':
return STPCardBrand.MasterCard;
case 'discover':
return STPCardBrand.Discover;
case 'jcb':
return STPCardBrand.JCB;
case 'dinersclub':
case 'diners_club':
case 'diners club':
return STPCardBrand.DinersClub;
case 'unionpay':
case 'union pay':
return STPCardBrand.UnionPay;
}
return STPCardBrand.Unknown;
}
/**
* Not available in IOS
*/
get fingerprint(): string {
return '';
}
/**
* Not available in IOS
*/
get funding(): string {
return '';
}
get country(): string {
return this.native.addressCountry;
}
/**
* Returns an image for a card given its brand.
* The returned value can be used as [src] in an Image tag.
*/
static cardImage(brand: CardBrand): any {
return STPImageLibrary.brandImageForCardBrand(Card.fromCardBrand(brand));
}
}
export class CreditCardView extends CreditCardViewBase {
public createNativeView(): STPPaymentCardTextField {
return STPPaymentCardTextField.alloc().initWithFrame(
CGRectMake(10, 10, 300, 44)
);
}
/**
* Initializes properties/listeners of the native view.
*/
initNativeView(): void {
// When nativeView is tapped we get the owning JS object through this field.
(<any>this.nativeView).owner = this;
super.initNativeView();
}
/**
* Clean up references to the native view and resets nativeView to its original state.
* If you have changed nativeView in some other way except through setNative callbacks
* you have a chance here to revert it back to its original state
* so that it could be reused later.
*/
disposeNativeView(): void {
(<any>this.nativeView).owner = null;
super.disposeNativeView();
}
get card(): Card {
try {
const stpCardParams = STPCardParams.alloc();
stpCardParams.cvc = this.nativeView.cardParams.cvc;
stpCardParams.number = this.nativeView.cardParams.number;
stpCardParams.expMonth = this.nativeView.cardParams.expMonth;
stpCardParams.expYear = this.nativeView.cardParams.expYear;
const valid =
STPCardValidator.validationStateForCard(stpCardParams) ===
STPCardValidationState.Valid;
return valid
? new Card(
this.nativeView.cardParams.number,
this.nativeView.cardParams.expMonth,
this.nativeView.cardParams.expYear,
this.nativeView.cardParams.cvc
)
: null;
} catch (ex) {
return null;
}
}
}
export class PaymentMethod implements PaymentMethodCommon {
native: STPPaymentMethod;
static fromNative(native: STPPaymentMethod): PaymentMethod {
const pm = new PaymentMethod();
pm.native = native;
return pm;
}
get id(): string { return this.native.stripeId; }
get created(): Date { return new Date(this.native.created); }
get type(): "card" { return this.native.type === STPPaymentMethodType.Card ? "card" : null; }
get billingDetails(): object { return this.native.billingDetails; }
get card(): CardCommon { return Card.fromNativePaymentMethod(this.native); }
get customerId(): string { return this.native.customerId; }
get metadata(): object { return this.native.metadata; }
}
class StripeIntent {
native: STPSetupIntent | STPPaymentIntent;
get created(): Date { return new Date(this.native.created); }
get clientSecret(): string { return this.native.clientSecret; }
get status(): StripePaymentIntentStatus {
switch (this.native.status) {
case STPPaymentIntentStatus.Canceled:
return StripePaymentIntentStatus.Canceled;
case STPPaymentIntentStatus.Processing:
return StripePaymentIntentStatus.Processing;
case STPPaymentIntentStatus.RequiresAction:
return StripePaymentIntentStatus.RequiresAction;
case STPPaymentIntentStatus.RequiresCapture:
return StripePaymentIntentStatus.RequiresCapture;
case STPPaymentIntentStatus.RequiresConfirmation:
return StripePaymentIntentStatus.RequiresConfirmation;
case STPPaymentIntentStatus.RequiresPaymentMethod:
return StripePaymentIntentStatus.RequiresPaymentMethod;
case STPPaymentIntentStatus.Succeeded:
return StripePaymentIntentStatus.Succeeded;
}
return null;
}
get requiresAction(): boolean { return this.native.status === STPPaymentIntentStatus.RequiresAction; }
get isSuccess(): boolean { return this.status === StripePaymentIntentStatus.Succeeded; }
get requiresConfirmation(): boolean { return this.status === StripePaymentIntentStatus.RequiresConfirmation; }
get requiresCapture(): boolean { return this.status === StripePaymentIntentStatus.RequiresCapture; }
get description(): string { return this.native.description; }
}
export class StripePaymentIntent extends StripeIntent implements StripePaymentIntentCommon {
native: STPPaymentIntent;
static fromNative(native: STPPaymentIntent): StripePaymentIntent {
const pi = new StripePaymentIntent();
pi.native = native;
return pi;
}
static fromApi(json: any): StripePaymentIntent {
const native = STPPaymentIntent.decodedObjectFromAPIResponse(json);
return StripePaymentIntent.fromNative(native);
}
get id(): string { return this.native.stripeId; }
get amount(): number { return this.native.amount; }
get currency(): string { return this.native.currency; }
get captureMethod(): "manual" | "automatic" {
switch (this.native.captureMethod) {
case STPPaymentIntentCaptureMethod.Automatic:
return "automatic";
case STPPaymentIntentCaptureMethod.Manual:
return "manual";
}
return null;
}
}
export class StripePaymentIntentParams {
clientSecret: string;
paymentMethodParams: any;
paymentMethodId: string;
sourceParams: any;
sourceId: string;
returnURL: string; // a URL that opens your app
get native(): STPPaymentIntentParams {
const n = STPPaymentIntentParams.alloc().initWithClientSecret(this.clientSecret);
n.paymentMethodParams = this.paymentMethodParams;
n.paymentMethodId = this.paymentMethodId;
n.sourceParams = this.sourceParams;
n.sourceId = this.sourceId;
n.returnURL = this.returnURL;
return n;
}
}
export class StripeSetupIntent extends StripeIntent {
native: STPSetupIntent;
static fromNative(native: STPSetupIntent): StripeSetupIntent {
const si = new StripeSetupIntent();
si.native = native;
return si;
}
get id(): string { return this.native.stripeID; }
get paymentMethodId(): string { return this.native.paymentMethodID; }
}
export class StripeSetupIntentParams {
native: STPSetupIntentConfirmParams;
constructor(paymentMethodId: string, clientSecret: string) {
this.native = STPSetupIntentConfirmParams.alloc();
this.native.paymentMethodID = paymentMethodId;
this.native.clientSecret = clientSecret;
}
}
export class StripeRedirectSession {
native: STPRedirectContext;
readonly state: StripeRedirectState;
constructor(paymentIntent: StripePaymentIntent, cb: (error: Error, clientSecret: string) => void) {
this.native = STPRedirectContext.alloc().initWithPaymentIntentCompletion(
paymentIntent.native,
callback(cb, (clientSecret) => clientSecret)
);
}
startRedirectFlow(view: View): void {
this.native.startRedirectFlowFromViewController(view.viewController);
}
cancel(): void {
this.native.cancel();
}
}
export const enum StripeRedirectState {
NotStarted = 0,
InProgress = 1,
Cancelled = 2,
Completed = 3
} | the_stack |
import { Component, INotifyPropertyChanged, NotifyPropertyChanges, Property, closest } from '@syncfusion/ej2-base';
import { EmitType, Event, EventHandler, MouseEventArgs } from '@syncfusion/ej2-base';
import { addClass, isRippleEnabled, removeClass, rippleEffect, isNullOrUndefined } from '@syncfusion/ej2-base';
import { SwitchModel } from './switch-model';
import { rippleMouseHandler, destroy, preRender, ChangeEventArgs, setHiddenInput } from './../common/common';
const DISABLED: string = 'e-switch-disabled';
const RIPPLE: string = 'e-ripple-container';
const RIPPLE_CHECK: string = 'e-ripple-check';
const RTL: string = 'e-rtl';
const WRAPPER: string = 'e-switch-wrapper';
const ACTIVE: string = 'e-switch-active';
/**
* The Switch is a graphical user interface element that allows you to toggle between checked and unchecked states.
* ```html
* <input type="checkbox" id="switch"/>
* <script>
* var switchObj = new Switch({});
* switchObj.appendTo("#switch");
* </script>
* ```
*/
@NotifyPropertyChanges
export class Switch extends Component<HTMLInputElement> implements INotifyPropertyChanged {
private tagName: string;
private isFocused: boolean = false;
private isDrag: boolean = false;
private delegateMouseUpHandler: Function;
private delegateKeyUpHandler: Function;
private formElement: HTMLFormElement;
private initialSwitchCheckedValue: boolean;
/**
* Triggers when Switch state has been changed by user interaction.
*
* @event change
*/
@Event()
public change: EmitType<ChangeEventArgs>;
/**
* Triggers once the component rendering is completed.
*
* @event created
*/
@Event()
public created: EmitType<Event>;
/**
* Specifies a value that indicates whether the Switch is `checked` or not.
* When set to `true`, the Switch will be in `checked` state.
*
* @default false
*/
@Property(false)
public checked: boolean;
/**
* You can add custom styles to the Switch by using this property.
*
* @default ''
*/
@Property('')
public cssClass: string;
/**
* Specifies a value that indicates whether the Switch is `disabled` or not.
* When set to `true`, the Switch will be in `disabled` state.
*
* @default false
*/
@Property(false)
public disabled: boolean;
/**
* Defines `name` attribute for the Switch.
* It is used to reference form data (Switch value) after a form is submitted.
*
* @default ''
*/
@Property('')
public name: string;
/**
* Specifies a text that indicates the Switch is in checked state.
*
* @default ''
*/
@Property('')
public onLabel: string;
/**
* Specifies a text that indicates the Switch is in unchecked state.
*
* @default ''
*/
@Property('')
public offLabel: string;
/**
* Defines `value` attribute for the Switch.
* It is a form data passed to the server when submitting the form.
*
* @default ''
*/
@Property('')
public value: string;
/**
* Constructor for creating the widget.
*
* @private
*
* @param {SwitchModel} options switch model
* @param {string | HTMLInputElement} element target element
*
*/
constructor(options?: SwitchModel, element?: string | HTMLInputElement) {
super(options, <string | HTMLInputElement>element);
}
private changeState(state?: boolean): void {
let ariaState: string;
let rippleSpan: Element;
const wrapper: Element = this.getWrapper();
const bar: Element = wrapper.querySelector('.e-switch-inner');
const handle: Element = wrapper.querySelector('.e-switch-handle');
if (isRippleEnabled) {
rippleSpan = wrapper.getElementsByClassName(RIPPLE)[0];
}
if (state) {
addClass([bar, handle], ACTIVE);
ariaState = 'true';
this.element.checked = true;
this.checked = true;
if (rippleSpan) {
addClass([rippleSpan], [RIPPLE_CHECK]);
}
} else {
removeClass([bar, handle], ACTIVE);
ariaState = 'false';
this.element.checked = false;
this.checked = false;
if (rippleSpan) {
removeClass([rippleSpan], [RIPPLE_CHECK]);
}
}
wrapper.setAttribute('aria-checked', ariaState);
}
private clickHandler(evt?: Event): void {
this.isDrag = false;
this.focusOutHandler();
this.changeState(!this.checked);
this.element.focus();
const changeEventArgs: ChangeEventArgs = { checked: this.element.checked, event: evt };
this.trigger('change', changeEventArgs);
}
/**
* Destroys the Switch widget.
*
* @returns {void}
*/
public destroy(): void {
super.destroy();
if (!this.disabled) {
this.unWireEvents();
}
destroy(this, this.getWrapper(), this.tagName);
}
private focusHandler(): void {
this.isFocused = true;
}
private focusOutHandler(): void {
this.getWrapper().classList.remove('e-focus');
}
/**
* Gets the module name.
*
* @private
* @returns {string} - Module Name
*/
protected getModuleName(): string {
return 'switch';
}
/**
* Gets the properties to be maintained in the persistence state.
*
* @private
* @returns {string} - Persist data
*/
public getPersistData(): string {
return this.addOnPersist(['checked']);
}
private getWrapper(): Element {
return this.element.parentElement;
}
private initialize(): void {
if (isNullOrUndefined(this.initialSwitchCheckedValue)) {
this.initialSwitchCheckedValue = this.checked;
}
if (this.name) {
this.element.setAttribute('name', this.name);
}
if (this.value) {
this.element.setAttribute('value', this.value);
}
if (this.checked) {
this.changeState(true);
}
if (this.disabled) {
this.setDisabled();
}
if (this.onLabel || this.offLabel) {
this.setLabel(this.onLabel, this.offLabel);
}
}
private initWrapper(): void {
let wrapper: Element = this.element.parentElement;
if (!wrapper.classList.contains(WRAPPER)) {
wrapper = this.createElement('div', {
className: WRAPPER, attrs: { 'role': 'switch', 'aria-checked': 'false' }
});
this.element.parentNode.insertBefore(wrapper, this.element);
}
const switchInner: Element = this.createElement('span', { className: 'e-switch-inner' });
const onLabel: Element = this.createElement('span', { className: 'e-switch-on' });
const offLabel: Element = this.createElement('span', { className: 'e-switch-off' });
const handle: Element = this.createElement('span', { className: 'e-switch-handle' });
wrapper.appendChild(this.element);
setHiddenInput(this, wrapper);
switchInner.appendChild(onLabel);
switchInner.appendChild(offLabel);
wrapper.appendChild(switchInner);
wrapper.appendChild(handle);
if (isRippleEnabled) {
const rippleSpan: HTMLElement = this.createElement('span', { className: RIPPLE });
handle.appendChild(rippleSpan);
rippleEffect(rippleSpan, { duration: 400, isCenterRipple: true });
}
wrapper.classList.add('e-wrapper');
if (this.enableRtl) {
wrapper.classList.add(RTL);
}
if (this.cssClass) {
addClass([wrapper], this.cssClass.split(' '));
}
}
/**
* Called internally if any of the property value changes.
*
* @private
* @param {SwitchModel} newProp - Specifies New Properties
* @param {SwitchModel} oldProp - Specifies Old Properties
* @returns {void}
*/
public onPropertyChanged(newProp: SwitchModel, oldProp: SwitchModel): void {
const wrapper: Element = this.getWrapper();
for (const prop of Object.keys(newProp)) {
switch (prop) {
case 'checked':
this.changeState(newProp.checked);
break;
case 'disabled':
if (newProp.disabled) {
this.setDisabled();
this.unWireEvents();
} else {
this.element.disabled = false;
wrapper.classList.remove(DISABLED);
wrapper.setAttribute('aria-disabled', 'false');
this.wireEvents();
}
break;
case 'value':
this.element.setAttribute('value', newProp.value);
break;
case 'name':
this.element.setAttribute('name', newProp.name);
break;
case 'onLabel':
case 'offLabel':
this.setLabel(newProp.onLabel, newProp.offLabel);
break;
case 'enableRtl':
if (newProp.enableRtl) {
wrapper.classList.add(RTL);
} else {
wrapper.classList.remove(RTL);
}
break;
case 'cssClass':
if (oldProp.cssClass) {
removeClass([wrapper], oldProp.cssClass.split(' '));
}
if (newProp.cssClass) {
addClass([wrapper], newProp.cssClass.split(' '));
}
break;
}
}
}
/**
* Initialize Angular, React and Unique ID support.
*
* @private
* @returns {void}
*/
protected preRender(): void {
const element: HTMLInputElement = this.element;
this.formElement = <HTMLFormElement>closest(this.element, 'form');
this.tagName = this.element.tagName;
preRender(this, 'EJS-SWITCH', WRAPPER, element, this.getModuleName());
}
/**
* Initialize control rendering.
*
* @private
* @returns {void}
*/
protected render(): void {
this.initWrapper();
this.initialize();
if (!this.disabled) {
this.wireEvents();
}
this.renderComplete();
}
private rippleHandler(e: MouseEvent): void {
const rippleSpan: Element = this.getWrapper().getElementsByClassName(RIPPLE)[0];
rippleMouseHandler(e, rippleSpan);
if (e.type === 'mousedown' && (e.currentTarget as Element).classList.contains('e-switch-wrapper') && e.which === 1) {
this.isDrag = true;
this.isFocused = false;
}
}
private rippleTouchHandler(eventType: string): void {
const rippleSpan: Element = this.getWrapper().getElementsByClassName(RIPPLE)[0];
if (rippleSpan) {
const event: MouseEvent = document.createEvent('MouseEvents');
event.initEvent(eventType, false, true);
rippleSpan.dispatchEvent(event);
}
}
private setDisabled(): void {
const wrapper: Element = this.getWrapper();
this.element.disabled = true;
wrapper.classList.add(DISABLED);
wrapper.setAttribute('aria-disabled', 'true');
}
private setLabel(onText: string, offText: string): void {
const wrapper: Element = this.getWrapper();
if (onText) {
wrapper.querySelector('.e-switch-on').textContent = onText;
}
if (offText) {
wrapper.querySelector('.e-switch-off').textContent = offText;
}
}
private switchFocusHandler(): void {
if (this.isFocused) {
this.getWrapper().classList.add('e-focus');
}
}
private switchMouseUp(e: MouseEventArgs): void {
const target: Element = e.target as Element;
if (e.type === 'touchmove') {
e.preventDefault();
}
if (e.type === 'touchstart') {
this.isDrag = true;
this.rippleTouchHandler('mousedown');
}
if (this.isDrag) {
if ((e.type === 'mouseup' && target.className.indexOf('e-switch') < 0) || e.type === 'touchend') {
this.clickHandler(e);
this.rippleTouchHandler('mouseup');
e.preventDefault();
}
}
}
private formResetHandler(): void {
this.checked = this.initialSwitchCheckedValue;
this.element.checked = this.initialSwitchCheckedValue;
}
/**
* Toggle the Switch component state into checked/unchecked.
*
* @returns {void}
*/
public toggle(): void {
this.clickHandler();
}
private wireEvents(): void {
const wrapper: Element = this.getWrapper();
this.delegateMouseUpHandler = this.switchMouseUp.bind(this);
this.delegateKeyUpHandler = this.switchFocusHandler.bind(this);
EventHandler.add(wrapper, 'click', this.clickHandler, this);
EventHandler.add(this.element, 'focus', this.focusHandler, this);
EventHandler.add(this.element, 'focusout', this.focusOutHandler, this);
EventHandler.add(this.element, 'mouseup', this.delegateMouseUpHandler, this);
EventHandler.add(this.element, 'keyup', this.delegateKeyUpHandler, this);
EventHandler.add(wrapper, 'mousedown mouseup', this.rippleHandler, this);
EventHandler.add(wrapper, 'touchstart touchmove touchend', this.switchMouseUp, this);
if (this.formElement) {
EventHandler.add(this.formElement, 'reset', this.formResetHandler, this);
}
}
private unWireEvents(): void {
const wrapper: Element = this.getWrapper();
EventHandler.remove(wrapper, 'click', this.clickHandler);
EventHandler.remove(this.element, 'focus', this.focusHandler);
EventHandler.remove(this.element, 'focusout', this.focusOutHandler);
EventHandler.remove(this.element, 'mouseup', this.delegateMouseUpHandler);
EventHandler.remove(this.element, 'keyup', this.delegateKeyUpHandler);
EventHandler.remove(wrapper, 'mousedown mouseup', this.rippleHandler);
EventHandler.remove(wrapper, 'touchstart touchmove touchend', this.switchMouseUp);
if (this.formElement) {
EventHandler.remove(this.formElement, 'reset', this.formResetHandler);
}
}
/**
* Click the switch element
* its native method
*
* @public
* @returns {void}
*/
public click(): void {
this.element.click();
}
/**
* Sets the focus to Switch
* its native method
*
* @public
*/
public focusIn(): void {
this.element.focus();
}
} | the_stack |
import * as debug_ from "debug";
import { shell } from "electron";
import * as fs from "fs";
import { inject, injectable } from "inversify";
import * as moment from "moment";
import * as path from "path";
import { acceptedExtensionObject } from "readium-desktop/common/extension";
import { lcpLicenseIsNotWellFormed } from "readium-desktop/common/lcp";
import { LcpInfo, LsdStatus } from "readium-desktop/common/models/lcp";
import { ToastType } from "readium-desktop/common/models/toast";
import { readerActions, toastActions } from "readium-desktop/common/redux/actions/";
import { Translator } from "readium-desktop/common/services/translator";
import { PublicationViewConverter } from "readium-desktop/main/converter/publication";
import {
PublicationDocument, PublicationDocumentWithoutTimestampable,
} from "readium-desktop/main/db/document/publication";
import { LcpSecretRepository } from "readium-desktop/main/db/repository/lcp-secret";
import { PublicationRepository } from "readium-desktop/main/db/repository/publication";
import { diSymbolTable } from "readium-desktop/main/diSymbolTable";
import { decryptPersist, encryptPersist } from "readium-desktop/main/fs/persistCrypto";
import { RootState } from "readium-desktop/main/redux/states";
import { PublicationStorage } from "readium-desktop/main/storage/publication-storage";
import { IS_DEV } from "readium-desktop/preprocessor-directives";
import { ContentType } from "readium-desktop/utils/contentType";
import { toSha256Hex } from "readium-desktop/utils/lcp";
import { tryCatch } from "readium-desktop/utils/tryCatch";
import { Store } from "redux";
import { lsdRenew_ } from "@r2-lcp-js/lsd/renew";
import { lsdReturn_ } from "@r2-lcp-js/lsd/return";
import { launchStatusDocumentProcessing } from "@r2-lcp-js/lsd/status-document-processing";
import { LCP } from "@r2-lcp-js/parser/epub/lcp";
import { LSD } from "@r2-lcp-js/parser/epub/lsd";
import { TaJsonDeserialize, TaJsonSerialize } from "@r2-lcp-js/serializable";
import { Publication as R2Publication } from "@r2-shared-js/models/publication";
import { injectBufferInZip } from "@r2-utils-js/_utils/zip/zipInjector";
import { extractCrc32OnZip } from "../crc";
import { lcpActions } from "../redux/actions";
import { streamerCachedPublication } from "../streamerNoHttp";
import { DeviceIdManager } from "./device";
import { lcpHashesFilePath } from "../di";
// import { Server } from "@r2-streamer-js/http/server";
// import { JsonMap } from "readium-desktop/typings/json";
// Logger
const debug = debug_("readium-desktop:main#services/lcp");
const CONFIGREPOSITORY_LCP_SECRETS = "CONFIGREPOSITORY_LCP_SECRETS";
// object map with keys = PublicationDocument.identifier,
// and values = object tuple of single passphrase + provider (cached here to avoid costly lookup in Publication DB)
// this way, we can query all passphrases associated with a particular publication,
// or alternatively query all passphrases known for a given LCP provider
// (as in practice passphrases are sometimes shared between different publications from the same provider)
type TLCPSecrets = Record<string, { passphrase?: string, provider?: string }>;
@injectable()
export class LcpManager {
@inject(diSymbolTable["publication-view-converter"])
private readonly publicationViewConverter!: PublicationViewConverter;
@inject(diSymbolTable["publication-storage"])
private readonly publicationStorage!: PublicationStorage;
@inject(diSymbolTable["lcp-secret-repository"])
private readonly lcpSecretRepository!: LcpSecretRepository;
// @inject(diSymbolTable.streamer)
// private readonly streamer!: Server;
@inject(diSymbolTable["publication-repository"])
private readonly publicationRepository!: PublicationRepository;
@inject(diSymbolTable["device-id-manager"])
private readonly deviceIdManager!: DeviceIdManager;
@inject(diSymbolTable.store)
private readonly store!: Store<RootState>;
@inject(diSymbolTable.translator)
private readonly translator!: Translator;
public async absorbDBToJson() {
await this.getAllSecrets();
debug("+++++ LCP secrets absorbDBToJson");
}
public async getAllSecrets(): Promise<TLCPSecrets> {
debug("LCP getAllSecrets ...");
const buff = await tryCatch(() => fs.promises.readFile(lcpHashesFilePath), "");
if (buff) {
debug("LCP getAllSecrets from JSON");
const str = decryptPersist(buff, CONFIGREPOSITORY_LCP_SECRETS, lcpHashesFilePath);
if (!str) {
return {};
}
const json = JSON.parse(str);
return json;
}
debug("LCP getAllSecrets from DB (migration) ...");
const lcpSecretDocs = await this.lcpSecretRepository.findAll();
const json: TLCPSecrets = {};
for (const lcpSecretDoc of lcpSecretDocs) {
const id = lcpSecretDoc.publicationIdentifier;
if (!json[id]) {
json[id] = {};
}
if (lcpSecretDoc.secret) {
// note: due to the old DB schema,
// in theory a single publication ID could have multiple secrets
// so this potentially overrides the previous one.
// however in practice a given LCP-protected publication only has a single working passphrase
json[id].passphrase = lcpSecretDoc.secret;
if (!json[id].provider) {
const pubs = await this.publicationRepository.findByPublicationIdentifier(id);
if (pubs) {
for (const pub of pubs) { // should be just one
if (pub.lcp?.provider) {
json[id].provider = pub.lcp.provider;
break;
}
}
}
}
}
}
debug("LCP getAllSecrets DB TO JSON", json);
const str = JSON.stringify(json);
const encrypted = encryptPersist(str, CONFIGREPOSITORY_LCP_SECRETS, lcpHashesFilePath);
fs.promises.writeFile(lcpHashesFilePath, encrypted);
return json;
}
public async getSecrets(doc: PublicationDocument): Promise<string[]> {
debug("LCP getSecrets ... ", doc.identifier);
const secrets: string[] = [];
const allSecrets = await this.getAllSecrets();
const ids = Object.keys(allSecrets);
for (const id of ids) {
const val = allSecrets[id];
if (val.passphrase) {
const provider = doc.lcp?.provider;
if (doc.identifier === id ||
provider && val.provider && provider === val.provider) {
secrets.push(val.passphrase);
}
}
}
debug("LCP getSecrets: ", secrets);
return secrets;
// const lcpSecretDocs = await this.lcpSecretRepository.findByPublicationIdentifier(
// doc.identifier,
// );
// const secrets = lcpSecretDocs.map((doc) => doc.secret).filter((secret) => secret);
// return secrets;
}
public async saveSecret(doc: PublicationDocument, lcpHashedPassphrase: string) {
debug("LCP saveSecret ... ", doc.identifier);
// await this.lcpSecretRepository.save({
// publicationIdentifier: doc.identifier,
// secret: lcpHashedPassphrase,
// });
const allSecrets = await this.getAllSecrets();
if (!allSecrets[doc.identifier]) {
allSecrets[doc.identifier] = {};
}
allSecrets[doc.identifier].passphrase = lcpHashedPassphrase;
if (doc.lcp?.provider) {
allSecrets[doc.identifier].provider = doc.lcp.provider;
}
debug("LCP saveSecret: ", allSecrets);
const str = JSON.stringify(allSecrets);
const encrypted = encryptPersist(str, CONFIGREPOSITORY_LCP_SECRETS, lcpHashesFilePath);
fs.promises.writeFile(lcpHashesFilePath, encrypted);
}
public async injectLcplIntoZip_(epubPath: string, lcpStr: string) {
const extension = path.extname(epubPath);
const isAudioBook = new RegExp(`\\${acceptedExtensionObject.audiobook}$`).test(extension) ||
new RegExp(`\\${acceptedExtensionObject.audiobookLcp}$`).test(extension) ||
new RegExp(`\\${acceptedExtensionObject.audiobookLcpAlt}$`).test(extension);
const isDivina = new RegExp(`\\${acceptedExtensionObject.divina}$`).test(extension);
const isLcpPdf = new RegExp(`\\${acceptedExtensionObject.pdfLcp}$`).test(extension);
const epubPathTMP = epubPath + ".tmplcpl";
await new Promise<void>((resolve, reject) => {
injectBufferInZip(
epubPath,
epubPathTMP,
Buffer.from(lcpStr, "utf8"),
((!isAudioBook && !isDivina && !isLcpPdf) ? "META-INF/" : "") + "license.lcpl",
(e: any) => {
debug("injectLcplIntoZip_ - injectBufferInZip ERROR!");
debug(e);
reject(e);
},
() => {
resolve();
});
});
// Replace epub without LCP with a new one containing LCPL
fs.unlinkSync(epubPath);
await new Promise<void>((resolve, _reject) => {
setTimeout(() => {
resolve();
}, 200); // to avoid issues with some filesystems (allow extra completion time)
});
fs.renameSync(epubPathTMP, epubPath);
await new Promise<void>((resolve, _reject) => {
setTimeout(() => {
resolve();
}, 200); // to avoid issues with some filesystems (allow extra completion time)
});
}
public async injectLcplIntoZip(epubPath: string, lcp: LCP) {
const jsonSource = lcp.JsonSource ? lcp.JsonSource : JSON.stringify(TaJsonSerialize(lcp));
await this.injectLcplIntoZip_(epubPath, jsonSource);
}
// public async injectLcpl(
// publicationDocument: PublicationDocument,
// lcp: LCP,
// ): Promise<PublicationDocument> {
// // Get epub file path
// const epubPath = this.publicationStorage.getPublicationEpubPath(
// publicationDocument.identifier,
// );
// await this.injectLcplIntoZip(epubPath, lcp);
// const r2Publication = await this.unmarshallR2Publication(publicationDocument); // , false
// r2Publication.LCP = lcp;
// try {
// await this.processStatusDocument(
// publicationDocument.identifier,
// r2Publication,
// );
// debug(r2Publication.LCP);
// debug(r2Publication.LCP.LSD);
// } catch (err) {
// debug(err);
// }
// if ((r2Publication as any).__LCP_LSD_UPDATE_COUNT) {
// debug("processStatusDocument LCP updated.");
// }
// const newPublicationDocument: PublicationDocumentWithoutTimestampable = Object.assign(
// {},
// publicationDocument,
// {
// hash: await extractCrc32OnZip(epubPath),
// },
// );
// this.updateDocumentLcp(newPublicationDocument, r2Publication.LCP);
// return this.publicationRepository.save(newPublicationDocument);
// }
public updateDocumentLcp(
publicationDocument: PublicationDocumentWithoutTimestampable,
r2LCP: LCP,
skipFilesystemCache = false,
) {
// if (!publicationDocument.resources) {
// publicationDocument.resources = {};
// }
if (r2LCP) {
// Legacy Base64 data blobs
// const r2LCPStr = r2LCP.JsonSource ?? JSON.stringify(TaJsonSerialize(r2LCP));
// publicationDocument.resources.r2LCPBase64 = Buffer.from(r2LCPStr).toString("base64");
// const r2LCPJson = r2LCP.JsonSource ? JSON.parse(r2LCP.JsonSource) : TaJsonSerialize(r2LCP);
// publicationDocument.resources.r2LCPJson = r2LCPJson;
if (!skipFilesystemCache) {
this.publicationViewConverter.updateLcpCache(publicationDocument, r2LCP);
}
// if (r2LCP.LSD) {
// // Legacy Base64 data blobs
// // const r2LSDStr = JSON.stringify(r2LSDJson);
// // publicationDocument.resources.r2LSDBase64 = Buffer.from(r2LSDStr).toString("base64");
// const r2LSDJson = TaJsonSerialize(r2LCP.LSD);
// publicationDocument.resources.r2LSDJson = r2LSDJson;
// }
publicationDocument.lcp = this.convertLcpLsdInfo(
r2LCP,
// Legacy Base64 data blobs
// publicationDocument.resources.r2LCPBase64,
// publicationDocument.resources.r2LSDBase64
// publicationDocument.resources.r2LCPJson,
// publicationDocument.resources.r2LSDJson,
);
}
}
// public async unmarshallR2Publication(
// publicationDocument: PublicationDocument,
// // requiresLCP: boolean,
// ): Promise<R2Publication> {
// // let r2Publication: R2Publication;
// // Legacy Base64 data blobs
// // const mustParse = !publicationDocument.resources ||
// // !publicationDocument.resources.r2PublicationBase64 ||
// // (requiresLCP && !publicationDocument.resources.r2LCPBase64);
// // const mustParse = !publicationDocument.resources ||
// // !publicationDocument.resources.r2PublicationJson ||
// // (
// // requiresLCP
// // // && !publicationDocument.resources.r2LCPJson
// // );
// // if (mustParse) {
// const epubPath = this.publicationStorage.getPublicationEpubPath(
// publicationDocument.identifier,
// );
// const r2Publication = await PublicationParsePromise(epubPath);
// // just like when calling lsdLcpUpdateInject():
// // r2Publication.LCP.ZipPath is set to META-INF/license.lcpl
// // r2Publication.LCP.init(); is called to prepare for decryption (native NodeJS plugin)
// // r2Publication.LCP.JsonSource is set
// // after PublicationParsePromise, cleanup zip handler
// // (no need to fetch ZIP data beyond this point)
// r2Publication.freeDestroy();
// // } else {
// // // Legacy Base64 data blobs
// // // const r2PublicationBase64 = publicationDocument.resources.r2PublicationBase64;
// // // const r2PublicationStr = Buffer.from(r2PublicationBase64, "base64").toString("utf-8");
// // // const r2PublicationJson = JSON.parse(r2PublicationStr);
// // r2Publication = TaJsonDeserialize(publicationDocument.resources.r2PublicationJson, R2Publication);
// // }
// // if (!r2Publication.LCP &&
// // publicationDocument.resources &&
// // publicationDocument.resources.r2LCPJson) {
// // // Legacy Base64 data blobs
// // // const r2LCPBase64 = publicationDocument.resources.r2LCPBase64;
// // // const r2LCPStr = Buffer.from(r2LCPBase64, "base64").toString("utf-8");
// // // const r2LCPJson = JSON.parse(r2LCPStr);
// // const r2LCPJson = publicationDocument.resources.r2LCPJson;
// // if (lcpLicenseIsNotWellFormed(r2LCPJson)) {
// // throw new Error(`LCP license malformed: ${JSON.stringify(r2LCPJson)}`);
// // }
// // const r2LCP = TaJsonDeserialize(r2LCPJson, LCP);
// // const r2LCPStr = JSON.stringify(r2LCPJson);
// // r2LCP.JsonSource = r2LCPStr;
// // r2Publication.LCP = r2LCP;
// // }
// // if (r2Publication.LCP &&
// // publicationDocument.resources &&
// // publicationDocument.resources.r2LSDJson) {
// // // Legacy Base64 data blobs
// // // const r2LSDBase64 = publicationDocument.resources.r2LSDBase64;
// // // const r2LSDStr = Buffer.from(r2LSDBase64, "base64").toString("utf-8");
// // // const r2LSDJson = JSON.parse(r2LSDStr);
// // const r2LSDJson = publicationDocument.resources.r2LSDJson;
// // const r2LSD = TaJsonDeserialize(r2LSDJson, LSD);
// // r2Publication.LCP.LSD = r2LSD;
// // }
// return r2Publication;
// }
public async checkPublicationLicenseUpdate(
publicationDocument: PublicationDocument,
): Promise<PublicationDocument> {
const rootState = this.store.getState();
if (rootState.lcp.publicationFileLocks[publicationDocument.identifier]) {
// skip LSD processStatusDocument()
return Promise.resolve(publicationDocument);
// return Promise.reject(`Publication file lock busy ${publicationDocument.identifier}`);
}
this.store.dispatch(lcpActions.publicationFileLock.build({ [publicationDocument.identifier]: true }));
try {
const r2Publication = await this.publicationViewConverter.unmarshallR2Publication(publicationDocument); // , true
return await this.checkPublicationLicenseUpdate_(publicationDocument, r2Publication);
} finally {
this.store.dispatch(lcpActions.publicationFileLock.build({ [publicationDocument.identifier]: false }));
}
}
public async checkPublicationLicenseUpdate_(
publicationDocument: PublicationDocument,
r2Publication: R2Publication,
): Promise<PublicationDocument> {
let redoHash = false;
if (r2Publication.LCP) {
try {
await this.processStatusDocument(
publicationDocument.identifier,
r2Publication,
);
debug(r2Publication.LCP);
debug(r2Publication.LCP.LSD);
} catch (err) {
debug(err);
}
if ((r2Publication as any).__LCP_LSD_UPDATE_COUNT) {
debug("processStatusDocument LCP updated.");
redoHash = true;
}
}
const epubPath = this.publicationStorage.getPublicationEpubPath(
publicationDocument.identifier,
);
const newPublicationDocument: PublicationDocumentWithoutTimestampable = Object.assign(
{},
publicationDocument,
{
hash: redoHash ? await extractCrc32OnZip(epubPath) : publicationDocument.hash,
},
);
this.updateDocumentLcp(newPublicationDocument, r2Publication.LCP);
const newPubDocument = await this.publicationRepository.save(newPublicationDocument);
return Promise.resolve(newPubDocument);
}
public async renewPublicationLicense(
publicationDocument: PublicationDocument,
): Promise<PublicationDocument> {
const rootState = this.store.getState();
if (rootState.lcp.publicationFileLocks[publicationDocument.identifier]) {
return Promise.reject(`Publication file lock busy ${publicationDocument.identifier}`);
}
this.store.dispatch(lcpActions.publicationFileLock.build({ [publicationDocument.identifier]: true }));
try {
const locale = rootState.i18n.locale;
const httpHeaders = {
"Accept-Language": `${locale},en-US;q=0.7,en;q=0.5`,
"User-Agent": "readium-desktop",
};
// TODO - IDEALLY AS WELL:
// agentOptions: {
// rejectUnauthorized: IS_DEV ? false : true,
// },
const r2Publication = await this.publicationViewConverter.unmarshallR2Publication(publicationDocument); // , true
let newPubDocument = await this.checkPublicationLicenseUpdate_(publicationDocument, r2Publication);
let redoHash = false;
if (r2Publication.LCP?.LSD?.Links) {
const renewLink = r2Publication.LCP.LSD.Links.find((l) => {
return l.HasRel("renew");
});
if (!renewLink) {
debug("!renewLink");
this.store.dispatch(toastActions.openRequest.build(ToastType.Error,
`LCP [${this.translator.translate("publication.renewButton")}] 👎`,
));
return newPubDocument;
}
if (renewLink.Type !== ContentType.Lsd) {
if (renewLink.Type === ContentType.Html) {
await shell.openExternal(renewLink.Href);
return newPubDocument;
}
debug(`renewLink.Type: ${renewLink.Type}`);
this.store.dispatch(toastActions.openRequest.build(ToastType.Error,
`LCP [${this.translator.translate("publication.renewButton")}] 👎`,
));
return newPubDocument;
}
// const nowMs = new Date().getTime();
// const numberOfDays = 2;
// const laterMs = nowMs + (numberOfDays * 24 * 60 * 60 * 1000);
// const later = new Date(laterMs);
// const endDateStr = later.toISOString();
// debug(`======== RENEW DATE 1: ${endDateStr}`);
const endDateStr: string | undefined = undefined; // TODO: user input?
const endDate = endDateStr ? moment(endDateStr).toDate() : undefined;
let renewResponseLsd: LSD;
try {
renewResponseLsd =
await lsdRenew_(endDate, r2Publication.LCP.LSD, this.deviceIdManager, httpHeaders);
} catch (err) {
debug(err);
const str = this.stringifyLsdError(err);
this.store.dispatch(toastActions.openRequest.build(ToastType.Error,
`LCP [${this.translator.translate("publication.renewButton")}]: ${str}`,
));
}
if (renewResponseLsd) {
debug(renewResponseLsd);
r2Publication.LCP.LSD = renewResponseLsd;
redoHash = false;
try {
await this.processStatusDocument(
publicationDocument.identifier,
r2Publication,
);
debug(r2Publication.LCP);
debug(r2Publication.LCP.LSD);
} catch (err) {
debug("Error processStatusDocument", err);
}
if ((r2Publication as any).__LCP_LSD_UPDATE_COUNT) {
debug("processStatusDocument LCP updated.");
redoHash = true;
}
const newEndDate = r2Publication.LCP && r2Publication.LCP.Rights && r2Publication.LCP.Rights.End ?
r2Publication.LCP.Rights.End.toISOString() : "";
this.store.dispatch(toastActions.openRequest.build(ToastType.Success,
`LCP [${this.translator.translate("publication.renewButton")}] ${newEndDate}`,
));
const epubPath = this.publicationStorage.getPublicationEpubPath(
publicationDocument.identifier,
);
const newPublicationDocument: PublicationDocumentWithoutTimestampable = Object.assign(
{},
publicationDocument,
{
hash: redoHash ? await extractCrc32OnZip(epubPath) : publicationDocument.hash,
},
);
this.updateDocumentLcp(newPublicationDocument, r2Publication.LCP);
newPubDocument = await this.publicationRepository.save(newPublicationDocument);
} else {
this.store.dispatch(toastActions.openRequest.build(ToastType.Error,
`LCP [${this.translator.translate("publication.renewButton")}] 👎`,
));
}
}
return Promise.resolve(newPubDocument);
} finally {
this.store.dispatch(lcpActions.publicationFileLock.build({ [publicationDocument.identifier]: false }));
}
}
public async returnPublication(
publicationDocument: PublicationDocument,
): Promise<PublicationDocument> {
const rootState = this.store.getState();
if (rootState.lcp.publicationFileLocks[publicationDocument.identifier]) {
return Promise.reject(`Publication file lock busy ${publicationDocument.identifier}`);
}
this.store.dispatch(lcpActions.publicationFileLock.build({ [publicationDocument.identifier]: true }));
try {
const locale = rootState.i18n.locale;
const httpHeaders = {
"Accept-Language": `${locale},en-US;q=0.7,en;q=0.5`,
"User-Agent": "readium-desktop",
};
// TODO - IDEALLY AS WELL:
// agentOptions: {
// rejectUnauthorized: IS_DEV ? false : true,
// },
const r2Publication = await this.publicationViewConverter.unmarshallR2Publication(publicationDocument); // , true
let newPubDocument = await this.checkPublicationLicenseUpdate_(publicationDocument, r2Publication);
let redoHash = false;
if (r2Publication.LCP?.LSD?.Links) {
const returnLink = r2Publication.LCP.LSD.Links.find((l) => {
return l.HasRel("return");
});
if (!returnLink) {
debug("!returnLink");
this.store.dispatch(toastActions.openRequest.build(ToastType.Error,
`LCP [${this.translator.translate("publication.returnButton")}] 👎`,
));
return newPubDocument;
}
if (returnLink.Type !== ContentType.Lsd) {
if (returnLink.Type === ContentType.Html || returnLink.Type === ContentType.Xhtml) {
await shell.openExternal(returnLink.Href);
return newPubDocument;
}
debug(`returnLink.Type: ${returnLink.Type}`);
this.store.dispatch(toastActions.openRequest.build(ToastType.Error,
`LCP [${this.translator.translate("publication.returnButton")}] 👎`,
));
return newPubDocument;
}
let returnResponseLsd: LSD;
try {
returnResponseLsd =
await lsdReturn_(r2Publication.LCP.LSD, this.deviceIdManager, httpHeaders);
} catch (err) {
debug(err);
const str = this.stringifyLsdError(err);
this.store.dispatch(toastActions.openRequest.build(ToastType.Error,
`LCP [${this.translator.translate("publication.returnButton")}]: ${str}`,
));
}
if (returnResponseLsd) {
debug(returnResponseLsd);
r2Publication.LCP.LSD = returnResponseLsd;
redoHash = false;
try {
await this.processStatusDocument(
publicationDocument.identifier,
r2Publication,
);
debug(r2Publication.LCP);
debug(r2Publication.LCP.LSD);
} catch (err) {
debug(err);
}
if ((r2Publication as any).__LCP_LSD_UPDATE_COUNT) {
debug("processStatusDocument LCP updated.");
redoHash = true;
}
const newEndDate = r2Publication.LCP && r2Publication.LCP.Rights && r2Publication.LCP.Rights.End ?
r2Publication.LCP.Rights.End.toISOString() : "";
this.store.dispatch(toastActions.openRequest.build(ToastType.Success,
`LCP [${this.translator.translate("publication.returnButton")}] ${newEndDate}`,
));
const epubPath = this.publicationStorage.getPublicationEpubPath(
publicationDocument.identifier,
);
const newPublicationDocument: PublicationDocumentWithoutTimestampable = Object.assign(
{},
publicationDocument,
{
hash: redoHash ? await extractCrc32OnZip(epubPath) : publicationDocument.hash,
},
);
this.updateDocumentLcp(newPublicationDocument, r2Publication.LCP);
newPubDocument = await this.publicationRepository.save(newPublicationDocument);
} else {
this.store.dispatch(toastActions.openRequest.build(ToastType.Error,
`LCP [${this.translator.translate("publication.returnButton")}] 👎`,
));
}
}
return Promise.resolve(newPubDocument);
} finally {
this.store.dispatch(lcpActions.publicationFileLock.build({ [publicationDocument.identifier]: false }));
}
}
public convertUnlockPublicationResultToString(val: any): string | undefined {
let message: string | undefined;
if (typeof val === "string") {
message = val;
} else if (typeof val === "number") {
switch (val as number) {
case 0: {
message = "NONE: " + val;
break;
}
case 1: {
// message = "INCORRECT PASSPHRASE: " + val;
message = this.translator.translate("publication.userKeyCheckInvalid");
break;
}
case 11: {
// message = "LICENSE_OUT_OF_DATE: " + val;
message = this.translator.translate("publication.licenseOutOfDate");
break;
}
case 101: {
// message = "CERTIFICATE_REVOKED: " + val;
message = this.translator.translate("publication.certificateRevoked");
break;
}
case 102: {
// message = "CERTIFICATE_SIGNATURE_INVALID: " + val;
message = this.translator.translate("publication.certificateSignatureInvalid");
break;
}
case 111: {
// message = "LICENSE_SIGNATURE_DATE_INVALID: " + val;
message = this.translator.translate("publication.licenseSignatureDateInvalid");
break;
}
case 112: {
// message = "LICENSE_SIGNATURE_INVALID: " + val;
message = this.translator.translate("publication.licenseSignatureInvalid");
break;
}
case 121: {
message = "CONTEXT_INVALID: " + val;
break;
}
case 131: {
message = "CONTENT_KEY_DECRYPT_ERROR: " + val;
break;
}
case 141: {
// message = "USER_KEY_CHECK_INVALID: " + val;
message = this.translator.translate("publication.userKeyCheckInvalid");
break;
}
case 151: {
message = "CONTENT_DECRYPT_ERROR: " + val;
break;
}
default: {
message = "Unknown error?! " + val;
}
}
} else if (val && typeof val === "object"
// val.toString &&
// typeof val.toString === "function"
) {
message = (val as object).toString();
}
return message;
}
// if the publication is not yet loaded in the streamer (streamer.cachedPublication())
// then we just unlock a transient in-memory R2Publication, so must make sure to subsequently unlock
// the "proper" streamer-hosted publication in order to decrypt resources!
// TODO: improve this horrible returned union type!
public async unlockPublication(publicationDocument: PublicationDocument, passphrase: string | undefined):
Promise<string | number | null | undefined> {
let lcpPasses: string[] | undefined;
let passphraseHash: string | undefined;
if (passphrase) {
passphraseHash = toSha256Hex(passphrase);
lcpPasses = [passphraseHash];
} else {
const secrets = await this.getSecrets(publicationDocument);
if (!secrets || !secrets.length) {
return null;
}
lcpPasses = secrets;
}
const publicationIdentifier = publicationDocument.identifier;
const epubPath = this.publicationStorage.getPublicationEpubPath(publicationIdentifier);
// const r2Publication = await this.streamer.loadOrGetCachedPublication(epubPath);
// let r2Publication = _USE_HTTP_STREAMER ?
// this.streamer.cachedPublication(epubPath) :
// streamerCachedPublication(epubPath);
let r2Publication = streamerCachedPublication(epubPath);
if (!r2Publication) {
r2Publication = await this.publicationViewConverter.unmarshallR2Publication(publicationDocument); // , true
// if (r2Publication.LCP) {
// r2Publication.LCP.init();
// }
}
// else {
// // The streamer at this point should not host an instance of this R2Publication,
// // because we normally ensure readers are closed before performing LCP/LSD
// debug(`>>>>>>> streamer.cachedPublication() ?! ${publicationIdentifier} ${epubPath}`);
// }
if (!r2Publication) {
debug("unlockPublication !r2Publication ?");
return null;
}
if (!r2Publication.LCP) {
debug("unlockPublication !r2Publication.LCP ?");
return null;
}
try {
await r2Publication.LCP.tryUserKeys(lcpPasses);
debug("LCP pass okay");
if (passphraseHash) {
await this.saveSecret(publicationDocument, passphraseHash);
}
} catch (err) {
debug("FAIL publication.LCP.tryUserKeys()", err);
return err;
// DRMErrorCode (from r2-lcp-client)
// 1 === NO CORRECT PASSPHRASE / UERKEY IN GIVEN ARRAY
// // No error
// NONE = 0,
// /**
// WARNING ERRORS > 10
// **/
// // License is out of date (check start and end date)
// LICENSE_OUT_OF_DATE = 11,
// /**
// CRITICAL ERRORS > 100
// **/
// // Certificate has been revoked in the CRL
// CERTIFICATE_REVOKED = 101,
// // Certificate has not been signed by CA
// CERTIFICATE_SIGNATURE_INVALID = 102,
// // License has been issued by an expired certificate
// LICENSE_SIGNATURE_DATE_INVALID = 111,
// // License signature does not match
// LICENSE_SIGNATURE_INVALID = 112,
// // The drm context is invalid
// CONTEXT_INVALID = 121,
// // Unable to decrypt encrypted content key from user key
// CONTENT_KEY_DECRYPT_ERROR = 131,
// // User key check invalid
// USER_KEY_CHECK_INVALID = 141,
// // Unable to decrypt encrypted content from content key
// CONTENT_DECRYPT_ERROR = 151
}
// import { doTryLcpPass } from "@r2-navigator-js/electron/main/lcp";
// try {
// await doTryLcpPass(
// this.streamer,
// epubPath,
// lcpPasses,
// true, // isSha256Hex
// );
// debug("LCP pass okay");
// if (passphraseHash) {
// await this.saveSecret(publicationDocument, passphraseHash);
// }
// } catch (err) {
// return err;
// }
return undefined;
}
// , r2LSDJson: JsonMap
// , r2LCPJson: JsonMap
public convertLcpLsdInfo(lcp: LCP): LcpInfo {
let dateStr1 = "";
try {
dateStr1 = lcp.Issued?.toISOString();
} catch (err) {
debug(err);
}
let dateStr2 = "";
try {
dateStr2 = lcp.Updated?.toISOString();
} catch (err) {
debug(err);
}
let dateStr3 = "";
try {
dateStr3 = lcp.Rights?.Start?.toISOString();
} catch (err) {
debug(err);
}
let dateStr4 = "";
try {
dateStr4 = lcp.Rights?.End?.toISOString();
} catch (err) {
debug(err);
}
const lcpInfo: LcpInfo = {
provider: lcp.Provider,
issued: dateStr1,
updated: dateStr2,
rights: lcp.Rights ? {
copy: lcp.Rights.Copy,
print: lcp.Rights.Print,
start: dateStr3,
end: dateStr4,
} : undefined,
// r2LCPJson,
// Legacy Base64 data blobs
// r2LCPBase64,
textHint: lcp.Encryption.UserKey.TextHint ? lcp.Encryption.UserKey.TextHint : "",
};
if (lcp.Links) {
const statusLink = lcp.Links.find((link) => {
return link.Rel === "status";
});
if (statusLink) {
lcpInfo.lsd = {
statusUrl: statusLink.Href,
// r2LSDJson,
// Legacy Base64 data blobs
// r2LSDBase64,
};
}
const urlHint = lcp.Links.find((link) => {
return link.Rel === "hint";
});
if (typeof urlHint?.Href === "string") {
lcpInfo.urlHint = {
href: urlHint.Href,
title: urlHint.Title ?? undefined,
type: urlHint.Type ?? undefined,
};
}
}
if (lcp.LSD && lcpInfo.lsd) {
let dateStr5 = "";
try {
dateStr5 = lcp.LSD.Updated?.License?.toISOString();
} catch (err) {
debug(err);
}
let dateStr6 = "";
try {
dateStr6 = lcp.LSD.Updated?.Status?.toISOString();
} catch (err) {
debug(err);
}
lcpInfo.lsd.lsdStatus = {
id: lcp.LSD.ID,
status: lcp.LSD.Status,
message: lcp.LSD.Message,
updated: {
license: dateStr5,
status: dateStr6,
},
// events: lcp.LSD.Events ? lcp.LSD.Events.map((ev) => {
// let dateStr7 = "";
// try {
// dateStr7 = ev.TimeStamp?.toISOString();
// } catch (err) {
// debug(err);
// }
// return {
// id: ev.ID,
// name: ev.Name,
// timeStamp: dateStr7,
// type: ev.Type, // r2-lcp-js TypeEnum
// };
// }) : undefined,
links: lcp.LSD.Links ? lcp.LSD.Links.map((link) => {
return {
length: link.Length,
href: link.Href,
title: link.Title,
type: link.Type,
templated: link.Templated,
profile: link.Profile,
hash: link.Hash,
rel: link.Rel,
};
}) : undefined,
} as LsdStatus;
}
return lcpInfo;
}
public async processStatusDocument(
publicationDocumentIdentifier: string,
r2Publication: R2Publication): Promise<void> {
(r2Publication as any).__LCP_LSD_UPDATE_COUNT = 0;
return this.processStatusDocument_(publicationDocumentIdentifier, r2Publication);
}
private async processStatusDocument_(
publicationDocumentIdentifier: string,
r2Publication: R2Publication): Promise<void> {
if (!r2Publication.LCP) {
return Promise.reject("processStatusDocument NO LCP data!");
}
const locale = this.store.getState().i18n.locale;
const httpHeaders = {
"Accept-Language": `${locale},en-US;q=0.7,en;q=0.5`,
"User-Agent": "readium-desktop",
};
// TODO - IDEALLY AS WELL:
// agentOptions: {
// rejectUnauthorized: IS_DEV ? false : true,
// },
return new Promise(async (resolve, reject) => {
const callback = async (r2LCPStr: string | undefined) => {
debug("launchStatusDocumentProcessing DONE.");
debug(r2LCPStr);
if (r2LCPStr) {
let atLeastOneReaderIsOpen = false;
const readers = this.store.getState().win.session.reader;
if (readers) {
for (const reader of Object.values(readers)) {
if (reader.publicationIdentifier === publicationDocumentIdentifier) {
atLeastOneReaderIsOpen = true;
break;
}
}
}
if (atLeastOneReaderIsOpen) {
this.store.dispatch(readerActions.closeRequestFromPublication.build(
publicationDocumentIdentifier));
await new Promise<void>((res, _rej) => {
setTimeout(() => {
res();
}, 500); // allow extra completion time to ensure the filesystem ZIP streams are closed
});
}
try {
const prevLSD = r2Publication.LCP.LSD;
// const epubPath_ = await lsdLcpUpdateInject(
// licenseUpdateJson,
// r2Publication,
// epubPath);
const r2LCPJson = global.JSON.parse(r2LCPStr);
debug(r2LCPJson);
if (lcpLicenseIsNotWellFormed(r2LCPJson)) {
const rej = `LCP license malformed: ${JSON.stringify(r2LCPJson)}`;
debug(rej);
reject(rej);
return;
}
let r2LCP: LCP;
try {
r2LCP = TaJsonDeserialize(r2LCPJson, LCP);
} catch (erorz) {
debug(erorz);
reject(erorz);
return;
}
r2LCP.JsonSource = r2LCPStr;
r2Publication.LCP = r2LCP;
// will be updated below via another round of processStatusDocument_()
r2Publication.LCP.LSD = prevLSD;
const epubPath = this.publicationStorage.getPublicationEpubPath(
publicationDocumentIdentifier,
);
await this.injectLcplIntoZip_(epubPath, r2LCPStr);
// Protect against infinite loop due to incorrect LCP / LSD server dates
if (!(r2Publication as any).__LCP_LSD_UPDATE_COUNT) {
(r2Publication as any).__LCP_LSD_UPDATE_COUNT = 1;
} else {
(r2Publication as any).__LCP_LSD_UPDATE_COUNT++;
}
if ((r2Publication as any).__LCP_LSD_UPDATE_COUNT > 2) {
debug("__LCP_LSD_UPDATE_COUNT!?");
resolve();
} else {
try {
// loop to re-init LSD in updated LCP
await this.processStatusDocument_(
publicationDocumentIdentifier,
r2Publication);
// TODO: publicationFileLock by checkPublicationLicenseUpdate(), so does not work
if (atLeastOneReaderIsOpen) {
this.store.dispatch(readerActions.openRequest.build(publicationDocumentIdentifier));
}
resolve();
} catch (err) {
debug(err);
reject(err);
}
}
} catch (err) {
debug(err);
reject(err);
}
} else {
resolve();
}
};
// Uncomment this to bypass LSD checks (just in case of huge network timeouts during tests)
if (IS_DEV && process.env.LCP_SKIP_LSD) {
await callback(undefined);
return;
}
try {
await launchStatusDocumentProcessing(
r2Publication.LCP,
this.deviceIdManager,
callback,
httpHeaders,
);
} catch (err) {
debug(err);
reject(err);
}
});
}
// HTTP statusCode < 200 || >= 300.
// "err" can be:
//
// a number (HTTP status code) when no response body is available.
//
// an object with the `httpStatusCode` property (number)
// and httpResponseBody (string) when the response body cannot be parsed to JSON.
//
// an object with the `httpStatusCode` property (number)
// and other arbitrary JSON properties,
// depending on the server response.
// Typically, compliant LCP/LSD servers are expected to return
// Problem Details JSON (RFC7807),
// which provides `title` `type` and `details` JSON properties.
// See https://readium.org/technical/readium-lsd-specification/#31-handling-errors
private stringifyLsdError(err: any): string {
if (typeof err === "number") {
return `${err}`;
}
if (!err) {
return "";
}
if (typeof err === "object") {
if (err.httpStatusCode) {
if (err.httpResponseBody) {
return `${err.httpStatusCode} (${err.httpResponseBody})`;
}
if (err.title && err.detail) {
return `${err.httpStatusCode} (${err.title} - ${err.detail})`;
}
}
return JSON.stringify(err);
}
return err;
}
} | the_stack |
import { expect } from 'chai';
import * as sinon from 'sinon';
import {
discoverEmulators,
EMULATOR_HOST_ENV_VARS,
getEmulatorHostAndPort
} from '../../src/impl/discovery';
import { HostAndPort } from '../../src/public_types';
import { restoreEnvVars, stashEnvVars } from '../test_utils';
describe('discoverEmulators()', () => {
it('finds all running emulators', async () => {
const emulators = await discoverEmulators(getEmulatorHostAndPort('hub')!);
expect(emulators).to.deep.equal({
database: {
host: 'localhost',
port: 9002
},
firestore: {
host: 'localhost',
port: 9003
},
storage: {
host: 'localhost',
port: 9199
},
hub: {
host: 'localhost',
port: 4400
}
});
});
it('connect to IPv6 addresses correctly', async () => {
const fetch = sinon.fake(async () => {
return {
ok: true,
async json() {
return {};
}
};
});
const emulators = await discoverEmulators(
{ host: '::1', port: 1111 },
fetch as any
);
expect(fetch).to.be.calledOnceWith(new URL('http://[::1]:1111/emulators')); // bracketed
expect(emulators).to.deep.equal({});
});
it('throws error if emulator hub is unreachable', async () => {
// Connect to port:0. Should always fail (although error codes may differ among OSes).
await expect(
discoverEmulators({ host: '127.0.0.1', port: 0 })
).to.be.rejectedWith(/EADDRNOTAVAIL|ECONNREFUSED/);
});
it('throws if response status is not 2xx', async () => {
const fetch = sinon.fake(async () => {
return {
ok: false,
status: 666,
async json() {
return {};
}
};
});
await expect(
discoverEmulators({ host: '127.0.0.1', port: 4444 }, fetch as any)
).to.be.rejectedWith(/HTTP Error 666/);
});
});
describe('getEmulatorHostAndPort()', () => {
context('without env vars', () => {
beforeEach(() => {
stashEnvVars();
});
afterEach(() => {
restoreEnvVars();
});
it('returns undefined if config option is not set', async () => {
const result = getEmulatorHostAndPort('hub');
expect(result).to.be.undefined;
});
it('returns undefined if config option does not contain host/port', async () => {
const result = getEmulatorHostAndPort('hub', {
rules: '/* security rules only, no host/port */'
});
expect(result).to.be.undefined;
});
it('removes brackets from IPv6 hosts', async () => {
const result = getEmulatorHostAndPort('hub', {
host: '[::1]',
port: 1111
});
expect(result?.host).to.equal('::1');
});
it('throws if only host is present', async () => {
expect(() =>
getEmulatorHostAndPort('hub', {
host: '[::1]'
} as HostAndPort)
).to.throw(/hub.port=undefined/);
});
it('throws if only port is present', async () => {
expect(() =>
getEmulatorHostAndPort('database', {
port: 1234
} as HostAndPort)
).to.throw(/Invalid configuration database.host=undefined/);
});
it('connect to 127.0.0.1 if host is wildcard 0.0.0.0', async () => {
const result = getEmulatorHostAndPort('hub', {
host: '0.0.0.0',
port: 1111
});
// Do not connect to 0.0.0.0 which is invalid and won't work on some OSes.
expect(result?.host).to.equal('127.0.0.1');
});
it('connect to [::1] if host is wildcard [::]', async () => {
const result = getEmulatorHostAndPort('hub', { host: '::1', port: 1111 });
// Do not connect to :: which is invalid and won't work on some OSes.
expect(result?.host).to.equal('::1');
});
it('uses discovered host/port if both config and env var are unset', async () => {
const result = getEmulatorHostAndPort('hub', undefined, {
hub: { host: '::1', port: 3333 }
});
expect(result?.host).to.equal('::1');
expect(result?.port).to.equal(3333);
});
it('returns undefined if none of config, env var, discovered contains emulator', async () => {
const result = getEmulatorHostAndPort('database', undefined, {
hub: { host: '::1', port: 3333 } /* only hub, no database */
});
expect(result).to.be.undefined;
});
it('uses hub host as fallback if discovered host is wildcard 0.0.0.0/[::]', async () => {
const result = getEmulatorHostAndPort('database', undefined, {
database: { host: '0.0.0.0', port: 1111 },
hub: { host: '10.0.0.1', port: 3333 }
});
// If we can reach hub via 10.0.0.1 but database has host 0.0.0.0, it is very likely that
// database is also running on 10.0.0.1 and listening on all IPv4 addresses.
expect(result?.host).to.equal('10.0.0.1');
expect(result?.port).to.equal(1111);
const result2 = getEmulatorHostAndPort('database', undefined, {
database: { host: '::', port: 2222 },
hub: { host: '10.0.0.1', port: 3333 }
});
// The situation is less ideal when database listens on all IPv6 addresses, but we'll still
// try the same host as hub, hoping that the OS running database forwards v6 to v4.
expect(result2?.host).to.equal('10.0.0.1');
expect(result2?.port).to.equal(2222);
});
it('uses hub host as fallback if config host is wildcard 0.0.0.0/[::]', async () => {
// We apply the same logic to manually specified {host: '0.0.0.0'}, although it is a bit
// unclear what the developer actually means in that case. If we get this wrong though, the
// developer can always manually specify a non-wildcard address instead.
const discovered = {
hub: { host: '10.0.0.1', port: 3333 }
};
const result = getEmulatorHostAndPort(
'database',
{
host: '0.0.0.0',
port: 1111
},
discovered
);
expect(result?.host).to.equal('10.0.0.1');
expect(result?.port).to.equal(1111);
const result2 = getEmulatorHostAndPort(
'database',
{
host: '[::]',
port: 2222
},
discovered
);
expect(result2?.host).to.equal('10.0.0.1');
expect(result2?.port).to.equal(2222);
});
});
context('with env vars', () => {
beforeEach(() => {
stashEnvVars();
});
afterEach(() => {
restoreEnvVars();
});
it('parses IPv4 host + port correctly from env var', async () => {
process.env[EMULATOR_HOST_ENV_VARS.hub] = '127.0.0.1:3445';
const result = getEmulatorHostAndPort('hub');
expect(result?.host).to.equal('127.0.0.1');
expect(result?.port).to.equal(3445);
});
it('throws if port is not a number', async () => {
process.env[EMULATOR_HOST_ENV_VARS.hub] = '127.0.0.1:hhh';
expect(() => getEmulatorHostAndPort('hub')).to.throw(
/Invalid format in environment variable FIREBASE_EMULATOR_HUB/
);
});
it('parses IPv6 host + port correctly from env var and removes brackets', async () => {
process.env[EMULATOR_HOST_ENV_VARS.hub] = '[::1]:3445';
const result = getEmulatorHostAndPort('hub');
expect(result?.host).to.equal('::1');
expect(result?.port).to.equal(3445);
});
it('parses env var with IPv6 host but no port correctly', async () => {
process.env[EMULATOR_HOST_ENV_VARS.hub] = '[::1]';
const result = getEmulatorHostAndPort('hub');
expect(result?.host).to.equal('::1');
expect(result?.port).to.equal(80); // default port
});
it('parses env var with host but no port correctly', async () => {
process.env[EMULATOR_HOST_ENV_VARS.hub] = 'myhub.example.com';
const result = getEmulatorHostAndPort('hub');
expect(result?.host).to.equal('myhub.example.com');
expect(result?.port).to.equal(80); // default port
});
it('connect to 127.0.0.1 if host is wildcard 0.0.0.0', async () => {
process.env[EMULATOR_HOST_ENV_VARS.hub] = '0.0.0.0:3445';
const result = getEmulatorHostAndPort('hub');
// Do not connect to 0.0.0.0 which is invalid and won't work on some OSes.
expect(result?.host).to.equal('127.0.0.1');
});
it('connect to [::1] if host is wildcard [::]', async () => {
process.env[EMULATOR_HOST_ENV_VARS.hub] = '[::]:3445';
const result = getEmulatorHostAndPort('hub');
// Do not connect to :: which is invalid and won't work on some OSes.
expect(result?.host).to.equal('::1');
});
it('prefers config value over env var', async () => {
process.env[EMULATOR_HOST_ENV_VARS.hub] = '127.0.0.1:3445'; // ignored
const result = getEmulatorHostAndPort('hub', {
host: 'localhost',
port: 1234
});
expect(result?.host).to.equal('localhost');
expect(result?.port).to.equal(1234);
});
it('takes host and port from env var if config has no host/port', async () => {
process.env[EMULATOR_HOST_ENV_VARS.hub] = '127.0.0.1:3445';
const result = getEmulatorHostAndPort('hub', {
rules: '/* security rules only, no host/port */'
});
expect(result?.host).to.equal('127.0.0.1');
expect(result?.port).to.equal(3445);
});
it('uses hub host as fallback if host from env var is wildcard 0.0.0.0/[::]', async () => {
process.env[EMULATOR_HOST_ENV_VARS.database] = '0.0.0.0:1111';
const result = getEmulatorHostAndPort('database', undefined, {
hub: { host: '10.0.0.1', port: 3333 }
});
// If we can reach hub via 10.0.0.1 but database has host 0.0.0.0, it is very likely that
// database is also running on 10.0.0.1 and listening on all IPv4 addresses.
expect(result?.host).to.equal('10.0.0.1');
expect(result?.port).to.equal(1111);
process.env[EMULATOR_HOST_ENV_VARS.database] = '[::]:2222';
const result2 = getEmulatorHostAndPort('database', undefined, {
hub: { host: '10.0.0.1', port: 3333 }
});
// The situation is less ideal when database listens on all IPv6 addresses, but we'll still
// try the same host as hub, hoping that the OS running database forwards v6 to v4.
expect(result2?.host).to.equal('10.0.0.1');
expect(result2?.port).to.equal(2222);
});
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.