text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { logError } from "@codestream/webview/logger"; import { Link } from "@codestream/webview/Stream/Link"; import React, { useState, useEffect, useMemo } from "react"; import { FormattedMessage } from "react-intl"; import { useDispatch, useSelector } from "react-redux"; import { CodeStreamState } from "../store"; import { HostApi } from "../webview-api"; import Icon from "./Icon"; import { Checkbox } from "../src/components/Checkbox"; import styled from "styled-components"; import { Button } from "../src/components/Button"; import { setUserStatus, setUserPreference, connectProvider } from "./actions"; import { setCurrentCodemark, setStartWorkCard } from "../store/context/actions"; import { CSMe, FileStatus } from "@codestream/protocols/api"; import { InlineMenu } from "../src/components/controls/InlineMenu"; import { useDidMount, useRect } from "../utilities/hooks"; import { GetBranchesRequestType, CreateBranchRequestType, SwitchBranchRequestType, MoveThirdPartyCardRequestType, GetReposScmRequestType, ReposScm, UpdateThirdPartyStatusRequestType, DidChangeDataNotificationType, ChangeDataType, FetchRemoteBranchRequestType, FetchBranchCommitsStatusRequestType } from "@codestream/protocols/agent"; import IssueDropdown, { Row } from "./CrossPostIssueControls/IssueDropdown"; import { ConfigureBranchNames } from "./ConfigureBranchNames"; import { MarkdownText } from "./MarkdownText"; import { getProviderConfig, isConnected, getConnectedSharingTargets } from "../store/providers/reducer"; import { SharingAttributes } from "./SharingControls"; import { CreateCodemarkIcons } from "./CreateCodemarkIcons"; import { PanelHeader } from "../src/components/PanelHeader"; import ScrollBox from "./ScrollBox"; import { WebviewPanels } from "../ipc/webview.protocol.common"; import { ModifiedRepos } from "./ModifiedRepos"; import Tooltip from "./Tooltip"; import { OpenReviews } from "./OpenReviews"; import { OpenPullRequests } from "./OpenPullRequests"; import { Modal } from "./Modal"; import { OpenUrlRequestType } from "@codestream/protocols/webview"; import { isFeatureEnabled } from "../store/apiVersioning/reducer"; import { GitTimeline, BranchLineDown, BranchCurve, BranchLineAcross, GitBranch } from "./Flow"; import KeystrokeDispatcher from "../utilities/keystroke-dispatcher"; import { ButtonRow } from "../src/components/Dialog"; import { ExtensionTitle } from "./Sidebar"; import { ScmError } from "../store/editorContext/reducer"; import { confirmPopup } from "./Confirm"; const StyledCheckbox = styled(Checkbox)` color: var(--text-color-subtle); margin-bottom: 10px; `; const StatusInput = styled.div` position: relative; margin: 7px 0 20px 0; width: 100%; .clear { position: absolute; right: 2px; top: 1px; padding: 8px 10px; } input#status-input { border: 1px solid var(--base-border-color); font-size: 14px !important; // padding: 8px 40px 8px 42px !important; padding: 8px 40px 8px 10px !important; width: 100%; &::placeholder { font-size: 14px !important; } } `; const CardTitle = styled.span` font-size: 16px; position: relative; padding-left: 28px; padding-right: 28px; line-height: 20px; display: inline-block; width: 100%; .icon, .ticket-icon { margin-left: -28px; display: inline-block; transform: scale(1.25); padding: 0 8px 0 3px; vertical-align: -2px; } & + & { margin-left: 20px; } .link-to-ticket { position: absolute; top: 0; right: 0; .icon { padding-right: 0; margin-left: 0; } } `; const MonoMenu = styled(InlineMenu)` font-family: Menlo, Consolas, "DejaVu Sans Mono", monospace; white-space: normal; > .icon { margin-right: 5px; } `; const SCMError = styled.div` margin: 20px 0 0 0; font-size: smaller; font-family: Menlo, Consolas, "DejaVu Sans Mono", monospace; white-space: pre-wrap; color: var(--font-color-highlight); `; const CardDescription = styled.div` // padding: 10px; // border: 1px solid var(--base-border-color); margin: -5px 0 20px 28px; // background: var(--app-background-color); `; const CardLink = styled.div` text-align: right; font-size: smaller; margin: -18px 0 15px 0; `; export const HeaderLink = styled.span` float: right; cursor: pointer; .icon { opacity: 0.7; &:hover { opacity: 1; } } display: none; .narrow-icon { margin-right: 5px; } padding: 0px 5px; `; export const StatusSection = styled.div` padding: 30px 0 5px 0; .icon { margin-right: 5px; &.ticket, &.link-external { margin-right: 0; } } border-bottom: 1px solid var(--base-border-color); .instructions { display: none; padding: 0 20px 20px 20px; text-align: center; } &.show-instructions .instructions { display: block; } &:hover ${HeaderLink} { display: inline; } `; // @ts-ignore export const WideStatusSection = styled(StatusSection)` padding-left: 0; padding-right: 0; `; export const H4 = styled.h4` // position: fixed; color: var(--text-color-highlight); // font-weight: 600; // font-size: 11px; // text-transform: uppercase; // margin: -25px 0 5px 0; // padding-left: 20px; .toggle { opacity: 0; margin: 0 5px 0 -13px; vertical-align: -1px; transition: opacity 0.1s; } &:hover .toggle { opacity: 1; } `; export const RoundedSearchLink = styled(HeaderLink)` padding: 3px 3px 3px 3px; &.collapsed { padding: 3px 4px 3px 4px; } .icon { margin-right: 0; } display: flex; .accordion { display: inline-block; width: 130px; transition: width 0.1s; overflow: hidden; white-space: nowrap; height: 16px; line-height: 16px; margin: 0; #search-input { width: 90px; background: transparent !important; font-size: 13px !important; padding: 0 5px !important; margin: 0 0 !important; &:focus { outline: none; } } .icon { float: right; vertical-align: -1px; margin-right: 4px; } } &.collapsed .accordion { width: 0; } `; const HR = styled.div` border-top: 1px solid var(--base-border-color); margin: 0 0 20px 0; `; const BranchDiagram = styled.div` transition: max-height 0.2s, opacity 0.4s; max-height: 400px; height: auto; overflow: hidden; &.closed { max-height: 0; opacity: 0; } margin: 0 0 0 30px; // background: #000; position: relative; ${GitTimeline} { width: 100px; &:after { display: none; } transition: all 0.2s; } ${GitBranch} { margin-left: -20px; transition: all 0.2s; } ${BranchLineDown} { margin-left: -20px; top: 50px; bottom: 51px; height: auto; transition: all 0.2s; } ${BranchLineAcross} { margin-left: -20px; width: 25px; top: auto; bottom: 28px; transition: all 0.2s; } ${BranchCurve} { margin-left: -20px; top: auto; bottom: 28px; transition: all 0.2s; } .pull-option { margin: 5px 0; } .branch-info { margin-left: 110px; position: relative; padding: 0; } .base-branch { transition: all 0.2s; margin-top: 20px; min-height: 50px; .change-base-branch { margin: 5px 0; } } .local-branch { transition: all 0.2s; margin-bottom: 20px; } @media only screen and (max-width: 430px) { ${GitTimeline} { top: 9px; width: 30px; left: 0; } ${GitBranch} { margin-left: 0; left: 10px; top: 5px; .icon { display: none; } width: 10px; height: 10px; &:before { width: 4px; height: 4px; top: 3px; left: 3px; } } ${BranchLineDown} { margin-left: 0; left: 13px; top: 15px; bottom: 38px; height: auto; } ${BranchLineAcross} { margin-left: 0; width: 10px; left: 20px; } ${BranchCurve} { margin-left: 0; width: 20px; height: 20px; left: 13px; } .branch-info { margin-left: 40px; } .base-branch { margin-top: 0; } x.local-branch { bottom: 0; } } } `; const Priority = styled.div` // margin: 5px 0; margin: -5px 0 20px 28px; img { width: 16px; height: 16px; margin-left: 5px; transform: scale(1.25); vertical-align: -2px; } `; export const EMPTY_STATUS = { label: "", ticketId: "", ticketUrl: "", ticketProvider: "", invisible: false }; const EMPTY_ARRAY = []; interface Props { card: any; onClose: (e?: any) => void; } export const StartWork = (props: Props) => { const dispatch = useDispatch(); const derivedState = useSelector((state: CodeStreamState) => { const currentUser = state.users[state.session.userId!] as CSMe; const teamId = state.context.currentTeamId; let status = currentUser.status && currentUser.status[teamId] && "label" in currentUser.status[teamId] ? currentUser.status[teamId] : EMPTY_STATUS; // const now = new Date().getTime(); // if (status.expires && status.expires < now) status = EMPTY_STATUS; const team = state.teams[teamId]; const settings = team.settings || {}; const { preferences = {} } = state; const workPrefs = preferences["startWork"] || {}; const currentTeamId = state.context.currentTeamId; const preferencesForTeam = state.preferences[currentTeamId] || {}; // this is what we've persisted in the server as the last selection the user made const lastShareAttributes: SharingAttributes | undefined = preferencesForTeam.lastShareAttributes; const shareTargets = getConnectedSharingTargets(state); const selectedShareTarget = shareTargets.find( target => target.teamId === (state.context.shareTargetTeamId || (lastShareAttributes && lastShareAttributes.providerTeamId)) ); const isConnectedToSlack = isConnected(state, { name: "slack" }, "users.profile:write"); const updateSlack = Object.keys(workPrefs).includes("updateSlack") ? workPrefs.updateSlack : true; const adminIds = team.adminIds || []; const defaultBranchTicketTemplate = "feature/{title}"; const issueReposDefaultBranch = state.preferences.issueReposDefaultBranch || {}; return { status, repos: state.repos, invisible: status.invisible || false, teamName: team.name, currentUserId: state.session.userId!, currentUserName: state.users[state.session.userId!].username, modifiedReposByTeam: currentUser.modifiedRepos ? currentUser.modifiedRepos[teamId] : undefined, webviewFocused: state.context.hasFocus, textEditorUri: state.editorContext.textEditorUri, branchMaxLength: settings.branchMaxLength || 40, defaultBranchTicketTemplate, branchTicketTemplate: settings.branchTicketTemplate || defaultBranchTicketTemplate, branchPreserveCase: settings.branchPreserveCase, createBranch: Object.keys(workPrefs).includes("createBranch") ? workPrefs.createBranch : true, moveCard: Object.keys(workPrefs).includes("moveCard") ? workPrefs.moveCard : true, updateSlack: isConnectedToSlack ? updateSlack : false, slackConfig: getProviderConfig(state, "slack"), // msTeamsConfig: getProviderConfig(state, "msteams"), isConnectedToSlack, issueReposDefaultBranch, selectedShareTarget: selectedShareTarget || shareTargets[0], isCurrentUserAdmin: adminIds.includes(state.session.userId!), shareToSlackSupported: isFeatureEnabled(state, "shareStatusToSlack"), teamId }; }); const { card } = props; const { status } = derivedState; const [loading, setLoading] = useState(false); const [scmError, setScmError] = useState(""); const [label, setLabel] = useState(card.label || ""); const [loadingSlack, setLoadingSlack] = useState(false); const [currentBranch, setCurrentBranch] = useState(""); const [editingBranch, setEditingBranch] = useState(false); const [branches, setBranches] = useState(EMPTY_ARRAY as string[]); const [customBranchName, setCustomBranchName] = useState(""); const [configureBranchNames, setConfigureBranchNames] = useState(false); const [openRepos, setOpenRepos] = useState<ReposScm[]>(EMPTY_ARRAY); const [repoUri, setRepoUri] = useState(""); const [currentRepoId, setCurrentRepoId] = useState(""); const [currentRepoName, setCurrentRepoName] = useState(""); const [fromBranch, setFromBranch] = useState(""); const inputRef = React.useRef<HTMLInputElement>(null); const [commitsBehindOrigin, setCommitsBehindOrigin] = useState(0); const [unexpectedPullError, setUnexpectedPullError] = useState(""); const [pullSubmitting, setPullSubmitting] = useState(false); const [isFromBranchDefault, setIsFromBranchDefault] = useState(false); const { moveCard, updateSlack, createBranch } = derivedState; const setUpdateSlack = value => { if (!derivedState.isConnectedToSlack) { setLoadingSlack(true); dispatch(connectProvider(derivedState.slackConfig!.id, "Status")); } else { dispatch(setUserPreference(["startWork", "updateSlack"], value)); } }; const disposables: { dispose(): void }[] = []; const toggleEditingBranch = value => { setEditingBranch(value); }; useEffect(() => { if (editingBranch && !disposables.length) { disposables.push( KeystrokeDispatcher.withLevel(), KeystrokeDispatcher.onKeyDown( "Escape", event => { toggleEditingBranch(false); }, { source: "StatusPanel.tsx (toggleEditingBranch)", level: -1 } ) ); } else { disposables && disposables.forEach(_ => _.dispose()); } }, [editingBranch]); useEffect(() => { fetchBranchCommitsStatus(); }, [fromBranch]); const cardDescription = useMemo(() => { let description = ""; if (card && card.body) { description = card.body.replace(/\[Open in IDE\].*/, ""); if (card.provider.id === "github*com" || card.provider.id === "github/enterprise") { description = description.replace(/<!--[\s\S]*?-->/, "") } } return description; }, [card]); const setMoveCard = value => dispatch(setUserPreference(["startWork", "moveCard"], value)); const setCreateBranch = value => dispatch(setUserPreference(["startWork", "createBranch"], value)); const handleChangeStatus = value => { setLabel(value || ""); }; const selectCard = card => { // make sure we've got the most up-to-date set of branches getBranches(); }; const dateToken = () => { const now = new Date(); const year = now.getFullYear(); const month = now.getMonth() + 1; const date = now.getDate(); return `${year}-${month > 9 ? month : "0" + month}-${date > 9 ? date : "0" + date}`; }; const replaceTicketTokens = (template: string, card, title: string = "") => { let tokenId = ""; let providerToken = ""; if (card && card.tokenId) { tokenId = card.tokenId; title = card.title; providerToken = card.providerToken; } const str = template .replace(/\{id\}/g, tokenId) .replace(/\{username\}/g, derivedState.currentUserName) .replace(/\{team\}/g, derivedState.teamName) .replace(/\{date\}/g, dateToken()) .replace(/\{title\}/g, title) .replace(/\{provider\}/g, providerToken) .replace(/["\\|<>\*\?:]/g, "") .trim() .replace(/[\s]+/g, "-") .substr(0, derivedState.branchMaxLength); return derivedState.branchPreserveCase ? str : str.toLowerCase(); }; const fetchBranchCommitsStatus = async () => { const commitsStatus = await HostApi.instance.send(FetchBranchCommitsStatusRequestType, { repoId: currentRepoId, branchName: fromBranch || currentBranch }); setCommitsBehindOrigin(+commitsStatus.commitsBehindOrigin); }; const getBranches = async (uri?: string): Promise<{ openRepos?: ReposScm[] }> => { const response = await HostApi.instance.send(GetReposScmRequestType, { inEditorOnly: true, includeCurrentBranches: true, includeProviders: true }); if (response && response.repositories) { setOpenRepos(response.repositories); } if (uri) { setRepoUri(uri); } let branchInfo = await HostApi.instance.send(GetBranchesRequestType, { uri: uri || derivedState.textEditorUri || "" }); // didn't find scm info for the current editor URI // try to get it from one of the open repos in your editor if (!branchInfo.scm || branchInfo.error) { if (response.repositories && response.repositories.length) { branchInfo = await HostApi.instance.send(GetBranchesRequestType, { uri: response.repositories[0].folder.uri }); setRepoUri(response.repositories[0].folder.uri); } } if (branchInfo.scm && !branchInfo.error) { let defaultBranch = derivedState.issueReposDefaultBranch[branchInfo.scm.repoId]; if ( !defaultBranch || (branchInfo.scm.branches && !branchInfo.scm.branches.some(branchName => branchName === defaultBranch)) ) { defaultBranch = branchInfo.scm.current; dispatch( setUserPreference(["issueReposDefaultBranch"], { [branchInfo.scm.repoId]: defaultBranch }) ); } setBranches(branchInfo.scm.branches); setFromBranch(""); setCurrentBranch(defaultBranch); setCurrentRepoId(branchInfo.scm.repoId); const repoId = branchInfo.scm.repoId; const repoName = derivedState.repos[repoId] ? derivedState.repos[repoId].name : "repo"; setCurrentRepoName(repoName); const commitsStatus = await HostApi.instance.send(FetchBranchCommitsStatusRequestType, { repoId: branchInfo.scm.repoId, branchName: defaultBranch }); setCommitsBehindOrigin(+commitsStatus.commitsBehindOrigin); } return { openRepos: response ? response.repositories : [] }; }; useDidMount(() => { getBranches(); if (card.moveCardOptions && card.moveCardOptions.length) { const index = card.moveCardOptions.findIndex(option => option.to ? option.to.id === card.idList : option.id === card.idList ); const next = card.moveCardOptions[index + 1]; if (next) setMoveCardDestination(next); else setMoveCardDestination(card.moveCardOptions[0]); } const disposable = HostApi.instance.on(DidChangeDataNotificationType, async (e: any) => { if (e.type === ChangeDataType.Workspace) { await getBranches(); } }); return () => { disposable && disposable.dispose(); }; }); const showMoveCardCheckbox = React.useMemo(() => { return card && card.moveCardOptions && card.moveCardOptions.length > 0; }, [card, label]); const showCreateBranchCheckbox = React.useMemo(() => { return label && branches && branches.length > 0; }, [label, branches]); const showUpdateSlackCheckbox = React.useMemo(() => { return label && derivedState.shareToSlackSupported; }, [label, derivedState.shareToSlackSupported]); const newBranch = React.useMemo(() => { if (customBranchName) return customBranchName; if (card && card.branchName) return card.branchName; return ( replaceTicketTokens(derivedState.branchTicketTemplate, card, label) || replaceTicketTokens(derivedState.defaultBranchTicketTemplate, card, label) ); }, [ label, card, customBranchName, derivedState.branchTicketTemplate, derivedState.branchPreserveCase ]); const branch = React.useMemo(() => { if (customBranchName) return customBranchName; if (card && card.branchName) return card.branchName; return ( replaceTicketTokens(derivedState.branchTicketTemplate, card, label) || replaceTicketTokens(derivedState.defaultBranchTicketTemplate, card, label) ); }, [ label, card, customBranchName, derivedState.branchTicketTemplate, derivedState.branchPreserveCase ]); const save = async () => { setLoading(true); const { slackConfig } = derivedState; const createTheBranchNow = showCreateBranchCheckbox && createBranch && branch.length > 0 && (repoUri || derivedState.textEditorUri); const moveTheCardNow = showMoveCardCheckbox && moveCard && card && moveCardDestinationId; const updateSlackNow = slackConfig && showUpdateSlackCheckbox && updateSlack; try { if (createTheBranchNow) { const uri = repoUri || derivedState.textEditorUri || ""; const request = branches.includes(branch) ? SwitchBranchRequestType : CreateBranchRequestType; const result = await HostApi.instance.send(request, { branch, uri, fromBranch: fromBranch || currentBranch }); // FIXME handle error if (result.error) { console.warn("ERROR FROM SET BRANCH: ", result.error); setScmError(result.error); setLoading(false); return; } } if (moveTheCardNow) { const response = await HostApi.instance.send(MoveThirdPartyCardRequestType, { providerId: card.providerId, cardId: card.id, listId: moveCardDestinationId }); } if (slackConfig && updateSlackNow) { const response = await HostApi.instance.send(UpdateThirdPartyStatusRequestType, { providerId: slackConfig.id, providerTeamId: derivedState.selectedShareTarget.teamId, text: "Working on: " + label, icon: ":desktop_computer:" }); } } catch (e) { console.warn("ERROR: " + e); } finally { HostApi.instance.track("Work Started", { "Branch Created": createTheBranchNow, "Ticket Selected": card ? card.providerIcon : "", "Ticket Moved": moveTheCardNow ? true : false, "Status Set": updateSlackNow }); } const ticketId = card ? card.id : ""; const ticketUrl = card ? card.url : ""; const ticketProvider = card ? card.providerIcon : ""; await dispatch( setUserStatus( label, ticketId, ticketUrl, ticketProvider, derivedState.invisible, derivedState.teamId ) ); cancel(); }; const cancel = () => { setLabel(""); setScmError(""); setLoadingSlack(false); dispatch(setStartWorkCard(undefined)); props.onClose(); }; const clearAndSave = () => { setLoadingSlack(false); dispatch(setUserStatus("", "", "", "", derivedState.invisible, derivedState.teamId)); dispatch(setStartWorkCard(undefined)); // FIXME clear out slack status }; const saveLabel = !branch || branch == currentBranch || !createBranch ? "Start Work" : branches.includes(branch) ? "Switch Branch & Start Work" : "Create Branch & Start Work"; const branchMenuItems = [] as any; //branches.map(branch => makeMenuItem(branch, false)) as any; if (newBranch) { branchMenuItems.unshift( { label: "Edit Branch Name", key: "edit", icon: <Icon name="pencil" />, action: () => toggleEditingBranch(true) }, { label: "Configure Branch Naming", key: "configure", icon: <Icon name="gear" />, action: () => setConfigureBranchNames(true), disabled: !!card.branchName || !derivedState.isCurrentUserAdmin, subtext: card.branchName ? "Disabled: branch name comes from 3rd party card" : derivedState.isCurrentUserAdmin ? "" : "Disabled: admin only" } ); } const baseBranchMenuItems = branches.map(branch => { const iconName = branch == currentBranch ? "arrow-right" : "blank"; return { label: <span className="monospace">{branch}</span>, key: branch, icon: <Icon name={iconName} />, action: () => { setFromBranch(branch); setIsFromBranchDefault(derivedState.issueReposDefaultBranch[currentRepoId] === branch); } }; }); const repoMenuItems = (openRepos || []).map(repo => { const repoId = repo.id || ""; return { icon: <Icon name={repo.id === currentRepoId ? "arrow-right" : "blank"} />, label: derivedState.repos[repoId] ? derivedState.repos[repoId].name : repo.folder.name, key: repo.id, action: () => getBranches(repo.folder.uri) }; }); const setMoveCardDestination = option => { setMoveCardDestinationId(option.id); setMoveCardDestinationLabel(option.name); }; const [moveCardDestinationId, setMoveCardDestinationId] = React.useState(""); const [moveCardDestinationLabel, setMoveCardDestinationLabel] = React.useState(""); const moveCardItems = !card || !card.moveCardOptions ? [] : card.moveCardOptions.map(option => { const selected = option.to ? option.to.id === card.idList : option.id === card.idList; return { label: option.name, icon: <Icon name={selected ? "arrow-right" : "blank"} />, key: option.id, action: () => setMoveCardDestination(option) }; }); const onPullSubmit = async (event: React.SyntheticEvent) => { setUnexpectedPullError(""); setPullSubmitting(true); try { await HostApi.instance.send(FetchRemoteBranchRequestType, { repoId: currentRepoId, branchName: fromBranch || currentBranch }); await fetchBranchCommitsStatus(); } catch (error) { logError(error, {}); logError(`Unexpected error during branch pulling : ${error}`, {}); confirmPopup({ title: "Git Error", message: ( <div style={{ fontSize: "13px" }}> <FormattedMessage id="error.unexpected" defaultMessage="Something went wrong. Please try again, or pull origin manually." />{" "} <SCMError>{error}</SCMError> </div> ), buttons: [ { label: "Close", className: "control-button" }, { label: "Contact Support", action: () => { HostApi.instance.send(OpenUrlRequestType, { url: "https://help.codestream.com/" }); } } ] }); // setUnexpectedPullError(error); } finally { setPullSubmitting(false); } }; return ( <> {configureBranchNames && ( <Modal translucent verticallyCenter> <ConfigureBranchNames onClose={() => setConfigureBranchNames(false)} /> </Modal> )} {card && ( <Modal translucent onClose={cancel}> <Dialog className="codemark-form-container"> <div className="codemark-form standard-form vscroll"> <fieldset className="form-body" style={{ padding: "0px" }}> <div id="controls"> <StatusInput> {card.id ? ( <CardTitle> {card.typeIcon ? ( <img className="ticket-icon" src={card.typeIcon} /> ) : card.providerIcon ? ( <Icon className="ticket-icon" name={card.providerIcon} /> ) : null} {card.label || card.title} {card.url && ( <div className="link-to-ticket" onClick={() => HostApi.instance.send(OpenUrlRequestType, { url: card.url }) } > <Icon title="Open on web" className="clickable" name="globe" /> </div> )} {card.providerId === "codestream" && ( <div className="link-to-ticket" onClick={e => { cancel(); dispatch(setCurrentCodemark(card.id)); }} > <Icon className="clickable" name="description" /> </div> )} </CardTitle> ) : ( <> <h3>What are you working on?</h3> <input id="status-input" ref={inputRef} name="status" value={label} className="input-text control" autoFocus={true} type="text" onChange={e => handleChangeStatus(e.target.value)} placeholder="Enter Description" onKeyDown={e => { if (e.key == "Escape") cancel(); if (e.key == "Enter") save(); }} /> </> )} </StatusInput> {(card.priorityName || card.priorityIcon) && ( <Priority> <b>Priority: </b> {card.priorityName} {card.priorityIcon && <img src={card.priorityIcon} />} </Priority> )} {card && card.body && ( <CardDescription> <MarkdownText text={cardDescription} /> </CardDescription> )} {card && card.title && <HR />} {showMoveCardCheckbox && ( <StyledCheckbox name="move-issue" checked={moveCard} onChange={v => setMoveCard(v)} > {card && card.moveCardLabel}{" "} <InlineMenu items={moveCardItems}> {moveCardDestinationLabel || "make selection"} </InlineMenu> </StyledCheckbox> )} {showCreateBranchCheckbox && ( <> <StyledCheckbox name="create-branch" checked={createBranch} onChange={v => setCreateBranch(v)} > Set up a branch in{" "} <span style={{ whiteSpace: "nowrap" }}> <MonoMenu items={repoMenuItems}> <span style={{ whiteSpace: "nowrap" }}> <Icon name="repo" /> {currentRepoName} </span> </MonoMenu> </span> </StyledCheckbox> <BranchDiagram className={createBranch ? "open" : "closed"}> <GitTimeline /> <BranchLineDown /> <BranchCurve /> <BranchLineAcross /> <GitBranch className="no-hover"> <Icon name="git-branch" /> </GitBranch> <div className="branch-info"> <div className="base-branch"> <MonoMenu items={baseBranchMenuItems}> <Tooltip title="Base Branch" align={{ offset: [15, 0] }}> <span>{fromBranch || currentBranch}</span> </Tooltip> </MonoMenu> {commitsBehindOrigin > 0 && ( <div className="pull-option"> <Icon name="info" /> {commitsBehindOrigin} commit {commitsBehindOrigin > 1 ? "s" : ""} behind origin{" "} <Button size="subcompact" onClick={onPullSubmit} isLoading={pullSubmitting} > Pull </Button> </div> )} {fromBranch && ( <StyledCheckbox className="change-base-branch" name="change-base-branch-request" checked={isFromBranchDefault} onChange={value => { const isBranchDefault = !isFromBranchDefault; setIsFromBranchDefault(isBranchDefault); dispatch( setUserPreference(["issueReposDefaultBranch"], { [currentRepoId]: isBranchDefault ? fromBranch : "" }) ); setCurrentBranch(fromBranch); }} > Always use{" "} <span className="monospace highlight"> {fromBranch || currentBranch} </span>{" "} as base branch </StyledCheckbox> )} </div> <div className="local-branch"> {editingBranch ? ( <input id="branch-input" name="branch" value={customBranchName || branch} className="input-text control" autoFocus={true} type="text" onChange={e => setCustomBranchName(e.target.value)} placeholder="Enter branch name" onBlur={() => toggleEditingBranch(false)} onKeyPress={e => { if (e.key == "Enter") toggleEditingBranch(false); }} style={{ width: "200px" }} /> ) : ( <MonoMenu items={branchMenuItems}> <Tooltip title="Local Branch" align={{ offset: [15, 0] }}> <span>{branch}</span> </Tooltip> </MonoMenu> )} </div> </div> </BranchDiagram> </> )} {showUpdateSlackCheckbox && ( <StyledCheckbox name="update-slack" checked={updateSlack} loading={loadingSlack && !derivedState.isConnectedToSlack} onChange={v => setUpdateSlack(v)} > Update my status on Slack </StyledCheckbox> )} <div style={{ height: "5px" }}></div> {scmError && <SCMError>{scmError}</SCMError>} <ButtonRow> <Button onClick={cancel} variant="secondary"> Cancel </Button> <Button onClick={save} isLoading={loading} variant={label.length ? "primary" : "secondary"} disabled={!label.length} > {saveLabel} </Button> </ButtonRow> </div> </fieldset> </div> </Dialog> </Modal> )} </> ); }; const Dialog = styled.div` padding: 5px 5px 15px 5px; text-align: left; // max-width: 500px; width: 100%; margin: 0 auto; display: inline-block; `;
the_stack
import { NetworkOrSignerOrProvider, TransactionResult } from "../types"; import { SDKOptions } from "../../schema/sdk-options"; import { IStorage } from "../interfaces"; import { RPCConnectionHandler } from "./rpc-connection-handler"; import { BigNumber, BytesLike, constants, ContractInterface, ethers, utils, } from "ethers"; import invariant from "tiny-invariant"; import { extractConstructorParams, extractConstructorParamsFromAbi, extractFunctions, fetchContractMetadataFromAddress, fetchPreDeployMetadata, fetchSourceFilesFromMetadata, } from "../../common/feature-detection"; import { AbiFunction, ContractParam, ContractSource, PublishedContract, PublishedContractSchema, } from "../../schema/contracts/custom"; import { ContractWrapper } from "./contract-wrapper"; import { ContractPublisher as OnChainContractPublisher, IContractPublisher, } from "contracts"; import { getContractPublisherAddress } from "../../constants"; import ContractPublisherAbi from "../../../abis/ContractPublisher.json"; import { ContractPublishedEvent } from "contracts/ContractPublisher"; /** * Handles publishing contracts (EXPERIMENTAL) * @internal */ export class ContractPublisher extends RPCConnectionHandler { private storage: IStorage; private publisher: ContractWrapper<OnChainContractPublisher>; constructor( network: NetworkOrSignerOrProvider, options: SDKOptions, storage: IStorage, ) { super(network, options); this.storage = storage; this.publisher = new ContractWrapper<OnChainContractPublisher>( network, getContractPublisherAddress(), ContractPublisherAbi, options, ); } public override updateSignerOrProvider( network: NetworkOrSignerOrProvider, ): void { super.updateSignerOrProvider(network); this.publisher.updateSignerOrProvider(network); } /** * @internal * @param metadataUri */ public async extractConstructorParams( metadataUri: string, ): Promise<ContractParam[]> { return extractConstructorParams(metadataUri, this.storage); } /** * @internal * @param predeployMetadataUri */ public async extractFunctions( predeployMetadataUri: string, ): Promise<AbiFunction[]> { return extractFunctions(predeployMetadataUri, this.storage); } public async fetchFullContractMetadataFromPredeployUri(predeployUri: string) { return fetchPreDeployMetadata(predeployUri, this.storage); } /** * @internal * @param address */ public async fetchContractMetadataFromAddress(address: string) { return fetchContractMetadataFromAddress( address, this.getProvider(), this.storage, ); } /** * @internal * @param address */ public async fetchContractSourcesFromAddress( address: string, ): Promise<ContractSource[]> { const metadata = await this.fetchContractMetadataFromAddress(address); return await fetchSourceFilesFromMetadata(metadata, this.storage); } /** * @interface * @param publisherAddress */ public async getAll(publisherAddress: string): Promise<PublishedContract[]> { const data = await this.publisher.readContract.getAllPublishedContracts( publisherAddress, ); return data.map((d) => this.toPublishedContract(d)); } /** * @internal * @param publisherAddress * @param contractId */ public async getAllVersions( publisherAddress: string, contractId: string, ): Promise<PublishedContract[]> { const contractStructs = await this.publisher.readContract.getPublishedContractVersions( publisherAddress, contractId, ); if (contractStructs.length === 0) { throw Error("Not found"); } return contractStructs.map((d) => this.toPublishedContract(d)); } public async getLatest( publisherAddress: string, contractId: string, ): Promise<PublishedContract> { const model = await this.publisher.readContract.getPublishedContract( publisherAddress, contractId, ); return this.toPublishedContract(model); } public async publish( metadataUri: string, ): Promise<TransactionResult<PublishedContract>> { return (await this.publishBatch([metadataUri]))[0]; } public async publishBatch( predeployUris: string[], ): Promise<TransactionResult<PublishedContract>[]> { const signer = this.getSigner(); invariant(signer, "A signer is required"); const publisher = await signer.getAddress(); const fullMetadatas = await Promise.all( predeployUris.map(async (predeployUri) => { const fullMetadata = await this.fetchFullContractMetadataFromPredeployUri(predeployUri); return { bytecode: fullMetadata.bytecode.startsWith("0x") ? fullMetadata.bytecode : `0x${fullMetadata.bytecode}`, predeployUri, fullMetadata, }; }), ); const encoded = fullMetadatas.map((meta) => { const bytecodeHash = utils.solidityKeccak256(["bytes"], [meta.bytecode]); const contractId = meta.fullMetadata.name; return this.publisher.readContract.interface.encodeFunctionData( "publishContract", [ publisher, meta.predeployUri, bytecodeHash, constants.AddressZero, contractId, ], ); }); const receipt = await this.publisher.multiCall(encoded); const events = this.publisher.parseLogs<ContractPublishedEvent>( "ContractPublished", receipt.logs, ); if (events.length < 1) { throw new Error("No ContractDeployed event found"); } return events.map((e) => { const contract = e.args.publishedContract; return { receipt, data: async () => this.toPublishedContract(contract), }; }); } public async unpublish( publisher: string, contractId: string, ): Promise<TransactionResult> { return { receipt: await this.publisher.sendTransaction("unpublishContract", [ publisher, contractId, ]), }; } /** * @internal * @param publisherAddress * @param contractId * @param constructorParamValues * @param contractMetadata */ public async deployPublishedContract( publisherAddress: string, contractId: string, constructorParamValues: any[], ): Promise<string> { // TODO this gets the latest version, should we allow deploying a certain version? const contract = await this.publisher.readContract.getPublishedContract( publisherAddress, contractId, ); return this.deployContract( contract.publishMetadataUri, constructorParamValues, ); } /** * @internal * @param publishMetadataUri * @param constructorParamValues */ public async deployContract( publishMetadataUri: string, constructorParamValues: any[], ) { const signer = this.getSigner(); invariant(signer, "A signer is required"); const metadata = await fetchPreDeployMetadata( publishMetadataUri, this.storage, ); const bytecode = metadata.bytecode.startsWith("0x") ? metadata.bytecode : `0x${metadata.bytecode}`; if (!ethers.utils.isHexString(bytecode)) { throw new Error(`Contract bytecode is invalid.\n\n${bytecode}`); } const constructorParamTypes = extractConstructorParamsFromAbi( metadata.abi, ).map((p) => p.type); const paramValues = this.convertParamValues( constructorParamTypes, constructorParamValues, ); return this.deployContractWithAbi(metadata.abi, bytecode, paramValues); } private convertParamValues( constructorParamTypes: string[], constructorParamValues: any[], ) { // check that both arrays are same length if (constructorParamTypes.length !== constructorParamValues.length) { throw Error("Passed the wrong number of constructor arguments"); } return constructorParamTypes.map((p, index) => { if (p === "tuple" || p.endsWith("[]")) { if (typeof constructorParamValues[index] === "string") { return JSON.parse(constructorParamValues[index]); } else { return constructorParamValues[index]; } } if (p === "bytes32") { invariant( ethers.utils.isHexString(constructorParamValues[index]), `Could not parse bytes32 value. Expected valid hex string but got "${constructorParamValues[index]}".`, ); return ethers.utils.hexZeroPad(constructorParamValues[index], 32); } if (p.startsWith("bytes")) { invariant( ethers.utils.isHexString(constructorParamValues[index]), `Could not parse bytes value. Expected valid hex string but got "${constructorParamValues[index]}".`, ); return ethers.utils.toUtf8Bytes(constructorParamValues[index]); } if (p.startsWith("uint") || p.startsWith("int")) { return BigNumber.from(constructorParamValues[index].toString()); } return constructorParamValues[index]; }); } /** * @internal * @param abi * @param bytecode * @param constructorParams */ public async deployContractWithAbi( abi: ContractInterface, bytecode: BytesLike | { object: string }, constructorParams: Array<any>, ): Promise<string> { const signer = this.getSigner(); invariant(signer, "Signer is required to deploy contracts"); const deployer = await new ethers.ContractFactory(abi, bytecode) .connect(signer) .deploy(...constructorParams); const deployedContract = await deployer.deployed(); // TODO parse transaction receipt return deployedContract.address; } private toPublishedContract( contractModel: IContractPublisher.CustomContractInstanceStruct, ) { return PublishedContractSchema.parse({ id: contractModel.contractId, timestamp: contractModel.publishTimestamp, metadataUri: contractModel.publishMetadataUri, // TODO download }); } }
the_stack
import { runQuery } from "schema/v2/test/utils" import { toGlobalId } from "graphql-relay" import gql from "lib/gql" import sinon from "sinon" describe("artworksConnection", () => { let context describe(`Provides filter results`, () => { beforeEach(() => { context = { authenticatedLoaders: {}, unauthenticatedLoaders: { filterArtworksLoader: sinon .stub() .withArgs("filter/artworks", { gene_id: "500-1000-ce", aggregations: ["total"], for_sale: true, }) .returns( Promise.resolve({ hits: [ { id: "oseberg-norway-queens-ship", title: "Queen's Ship", artists: [], }, ], aggregations: { total: { value: 10, }, }, }) ), }, } }) it("returns a connection, and makes one gravity call when args passed inline", async () => { const query = gql` { artworksConnection( geneID: "500-1000-ce" first: 10 after: "" aggregations: [TOTAL] medium: "*" forSale: true ) { edges { node { slug } } } } ` const { artworksConnection } = await runQuery(query, context) expect(artworksConnection.edges).toEqual([ { node: { slug: "oseberg-norway-queens-ship" } }, ]) }) it("returns a connection, and makes one gravity call when using variables", async () => { const query = gql` query GeneFilter($count: Int, $cursor: String) { artworksConnection( geneID: "500-1000-ce" first: $count after: $cursor aggregations: [TOTAL] medium: "*" forSale: true ) { edges { node { slug } } } } ` const variableValues = { count: 10, cursor: "", } const { artworksConnection } = await runQuery( query, context, variableValues ) expect(artworksConnection.edges).toEqual([ { node: { slug: "oseberg-norway-queens-ship" } }, ]) }) it("implements the NodeInterface", async () => { const query = gql` { artworksConnection( first: 10 geneID: "500-1000-ce" forSale: true aggregations: [TOTAL] medium: "*" ) { id } } ` const filterOptions = { aggregations: ["total"], for_sale: true, gene_id: "500-1000-ce", page: 1, size: 10, } const expectedId = toGlobalId( "filterArtworksConnection", JSON.stringify(filterOptions) ) const { artworksConnection } = await runQuery(query, context) expect(artworksConnection.id).toEqual(expectedId) }) it("fetches FilterArtworks using the node root field", async () => { const filterOptions = { aggregations: ["total"], for_sale: true, gene_id: "500-1000-ce", page: 1, size: 10, } const generatedId = toGlobalId( "filterArtworksConnection", JSON.stringify(filterOptions) ) const query = gql` { node(id: "${generatedId}") { id } } ` const { node } = await runQuery(query, context) expect(node.id).toEqual(generatedId) }) }) describe(`Passes along an incoming page param over cursors`, () => { beforeEach(() => { context = { authenticatedLoaders: {}, unauthenticatedLoaders: { filterArtworksLoader: sinon .stub() .withArgs("filter/artworks", { gene_id: "500-1000-ce", aggregations: ["total"], for_sale: true, page: 20, size: 30, }) .returns( Promise.resolve({ hits: [ { id: "oseberg-norway-queens-ship", title: "Queen's Ship", artists: [], }, ], aggregations: { total: { value: 1000 } }, }) ), }, } }) it("returns filtered artworks, and makes a gravity call", async () => { const query = gql` { artworksConnection( aggregations: [TOTAL] medium: "*" forSale: true page: 20 first: 30 after: "" ) { pageInfo { endCursor } edges { node { slug } } } } ` const { artworksConnection } = await runQuery(query, context) expect(artworksConnection.edges).toEqual([ { node: { slug: "oseberg-norway-queens-ship" } }, ]) // Check that the cursor points to the end of page 20, size 30. // Base64 encoded string: `arrayconnection:599` expect(artworksConnection.pageInfo.endCursor).toEqual( "YXJyYXljb25uZWN0aW9uOjU5OQ==" ) }) }) describe(`Pagination for the last page`, () => { beforeEach(() => { context = { authenticatedLoaders: {}, unauthenticatedLoaders: { filterArtworksLoader: sinon .stub() .withArgs("filter/artworks") .returns( Promise.resolve({ hits: [ { id: "oseberg-norway-queens-ship-0", cursor: Buffer.from("artwork:297").toString("base64"), }, { id: "oseberg-norway-queens-ship-1", cursor: Buffer.from("artwork:298").toString("base64"), }, { id: "oseberg-norway-queens-ship-2", cursor: Buffer.from("artwork:299").toString("base64"), }, { id: "oseberg-norway-queens-ship-3", cursor: Buffer.from("artwork:300").toString("base64"), }, ], aggregations: { total: { value: 303, }, }, }) ), }, } }) it("caps pagination results to 100", async () => { const query = gql` { artworksConnection(first: 3, after: "${Buffer.from( "artwork:297" ).toString("base64")}", aggregations:[TOTAL]) { pageInfo { hasNextPage } } } ` const { artworksConnection } = await runQuery(query, context) expect(artworksConnection.pageInfo.hasNextPage).toBeFalsy() }) }) describe(`Returns proper pagination information`, () => { beforeEach(() => { context = { authenticatedLoaders: {}, unauthenticatedLoaders: { filterArtworksLoader: sinon .stub() .withArgs("filter/artworks") .returns( Promise.resolve({ hits: [ { id: "oseberg-norway-queens-ship-0", }, { id: "oseberg-norway-queens-ship-1", }, { id: "oseberg-norway-queens-ship-2", }, { id: "oseberg-norway-queens-ship-3", }, ], aggregations: { total: { value: 5, }, }, }) ), }, } }) it("returns `true` for `hasNextPage` when there is more data", async () => { const query = gql` { artworksConnection(first: 4, after: "", aggregations: [TOTAL]) { pageInfo { hasNextPage } } } ` const { artworksConnection } = await runQuery(query, context) expect(artworksConnection.pageInfo.hasNextPage).toBeTruthy() }) }) describe(`Connection argument validation`, () => { beforeEach(() => { context = { authenticatedLoaders: {}, unauthenticatedLoaders: { filterArtworksLoader: jest.fn(), }, } }) it("throws an error when `first`, `last` and `size` are missing", async () => { expect.assertions(1) const query = gql` { artworksConnection(aggregations: [TOTAL]) { pageInfo { hasNextPage } } } ` await expect(runQuery(query, context)).rejects.toThrow( "You must pass either `first`, `last` or `size`." ) }) }) describe(`When requesting personalized arguments`, () => { beforeEach(() => { context = { authenticatedLoaders: { filterArtworksLoader: () => Promise.resolve({ hits: [ { id: "oseberg-norway-queens-ship-0", }, ], aggregations: { total: { value: 303, }, }, }), }, unauthenticatedLoaders: {}, } }) it("returns results using the personalized loader", async () => { const query = gql` { artworksConnection( first: 1 after: "" aggregations: [TOTAL] includeArtworksByFollowedArtists: true ) { edges { node { slug } } } } ` const { artworksConnection } = await runQuery(query, context) expect(artworksConnection.edges).toEqual([ { node: { slug: "oseberg-norway-queens-ship-0" } }, ]) }) }) describe("Merchandisable artists aggregation", () => { beforeEach(() => { const mockArtworkResults = { hits: [ { id: "kawaii-artwork-1" }, { id: "kawaii-artwork-2" }, { id: "kawaii-artwork-3" }, ], aggregations: { total: { value: 42 }, merchandisable_artists: { "id-1": { name: "Takashi Murakami", count: 42 }, "id-2": { name: "Yamaguchi Ai", count: 42 }, "id-3": { name: "Yoshitomo Nara", count: 42 }, "id-4": { name: "Aya Takano", count: 42 }, "id-5": { name: "Amano Yoshitaka", count: 42 }, }, }, } const mockArtistResults = [ { _id: "id-1", id: "takashi-murakami", name: "Takashi Murakami" }, { _id: "id-2", id: "yamaguchi-ai", name: "Yamaguchi Ai" }, { _id: "id-3", id: "yoshitomo-nara", name: "Yoshitomo Nara" }, { _id: "id-4", id: "aya-takano", name: "Aya Takano" }, { _id: "id-5", id: "amano-yoshitaka", name: "Amano Yoshitaka" }, ] context = { authenticatedLoaders: {}, unauthenticatedLoaders: { filterArtworksLoader: jest.fn(() => Promise.resolve(mockArtworkResults) ), }, artistsLoader: jest.fn( // mock implementation to filter over the mock results above ({ ids }) => Promise.resolve({ body: mockArtistResults.filter(({ _id }) => ids.includes(_id)), headers: {}, }) ), } }) it("returns all artists by default", async () => { const query = gql` { artworksConnection( geneID: "kawaii" first: 3 aggregations: [MERCHANDISABLE_ARTISTS] ) { merchandisableArtists { slug } edges { node { slug } } } } ` const { artworksConnection } = await runQuery(query, context) const artistIdsToLoad = context.artistsLoader.mock.calls[0][0].ids expect(artistIdsToLoad).toEqual(["id-1", "id-2", "id-3", "id-4", "id-5"]) expect(artworksConnection.merchandisableArtists).toHaveLength(5) expect(artworksConnection.merchandisableArtists).toEqual([ { slug: "takashi-murakami" }, { slug: "yamaguchi-ai" }, { slug: "yoshitomo-nara" }, { slug: "aya-takano" }, { slug: "amano-yoshitaka" }, ]) }) it("can limit the number of returned artists", async () => { const query = gql` { artworksConnection( geneID: "kawaii" first: 3 aggregations: [MERCHANDISABLE_ARTISTS] ) { merchandisableArtists(size: 2) { slug } edges { node { slug } } } } ` const { artworksConnection } = await runQuery(query, context) const artistIdsToLoad = context.artistsLoader.mock.calls[0][0].ids expect(artistIdsToLoad).toEqual(["id-1", "id-2"]) expect(artworksConnection.merchandisableArtists).toHaveLength(2) expect(artworksConnection.merchandisableArtists).toEqual([ { slug: "takashi-murakami" }, { slug: "yamaguchi-ai" }, ]) }) }) describe("Accepting an `input` argument", () => { beforeEach(() => { context = { authenticatedLoaders: {}, unauthenticatedLoaders: { filterArtworksLoader: sinon .stub() .withArgs("filter/artworks", { gene_id: "500-1000-ce", aggregations: ["total"], for_sale: true, }) .returns( Promise.resolve({ hits: [ { id: "oseberg-norway-queens-ship", title: "Queen's Ship", artists: [], }, ], aggregations: { total: { value: 10, }, }, }) ), }, } }) it("returns a connection", async () => { const query = gql` { artworksConnection( input: { geneID: "500-1000-ce" first: 10 after: "" aggregations: [TOTAL] medium: "*" forSale: true } ) { edges { node { slug } } } } ` const { artworksConnection } = await runQuery(query, context) expect(artworksConnection.edges).toEqual([ { node: { slug: "oseberg-norway-queens-ship" } }, ]) }) it("prefers `input` arguments over ones specified in the root", async () => { const query = gql` { artworksConnection( aggregations: [] medium: null input: { geneID: "500-1000-ce" first: 10 after: "" aggregations: [TOTAL] medium: "*" forSale: true } ) { edges { node { slug } } } } ` const { artworksConnection } = await runQuery(query, context) expect(artworksConnection.edges).toEqual([ { node: { slug: "oseberg-norway-queens-ship" } }, ]) }) }) })
the_stack
import React from 'react'; import { render } from '@test/utils'; import { Table, BaseTable, PrimaryTable, EnhancedTable } from '..'; const data = new Array(5).fill(null).map((item, index) => ({ id: index + 100, index: index + 100, instance: `JQTest${index + 1}`, status: index % 2, owner: 'jenny;peter', description: 'test', })); const SIMPLE_COLUMNS = [ { title: 'Index', colKey: 'index' }, { title: 'Instance', colKey: 'instance' }, ]; // 4 类表格组件同时测试 const TABLES = [Table, BaseTable, PrimaryTable, EnhancedTable]; // 每一种表格组件都需要单独测试,避免出现组件之间属性或事件透传不成功的情况 TABLES.forEach((TTable) => { describe(TTable.name, () => { // 测试边框 describe(':props.bordered', () => { it('bordered default value is true', () => { const { container } = render(<TTable rowKey="index" bordered data={data} columns={SIMPLE_COLUMNS}></TTable>); expect(container.firstChild).toHaveClass('t-table--bordered'); }); it('bordered={true} works fine', () => { const { container } = render( <TTable rowKey="index" bordered={true} data={data} columns={SIMPLE_COLUMNS}></TTable>, ); expect(container.firstChild).toHaveClass('t-table--bordered'); }); it('bordered={false} works fine', () => { const { container } = render( <TTable rowKey="index" bordered={false} data={data} columns={SIMPLE_COLUMNS}></TTable>, ); expect(container.firstChild).toHaveClass('t-table'); }); }); // 测试边框 describe(':props.rowAttributes', () => { it('props.rowAttributes could be an object', () => { const { container } = render( <TTable rowKey="index" rowAttributes={{ 'data-level': 'level-1' }} data={data} columns={SIMPLE_COLUMNS} ></TTable>, ); const trWrapper = container.querySelector('tbody').querySelector('tr'); expect(trWrapper.getAttribute('data-level')).toBe('level-1'); }); it('props.rowAttributes could be an Array<object>', () => { const rowAttrs = [{ 'data-level': 'level-1' }, { 'data-name': 'tdesign' }]; const { container } = render( <TTable rowKey="index" rowAttributes={rowAttrs} data={data} columns={SIMPLE_COLUMNS}></TTable>, ); const trWrapper = container.querySelector('tbody').querySelector('tr'); expect(trWrapper.getAttribute('data-level')).toBe('level-1'); expect(trWrapper.getAttribute('data-name')).toBe('tdesign'); }); it('props.rowAttributes could be a function', () => { const rowAttrs = () => [{ 'data-level': 'level-1' }, { 'data-name': 'tdesign' }]; const { container } = render( <TTable rowKey="index" rowAttributes={rowAttrs} data={data} columns={SIMPLE_COLUMNS}></TTable>, ); const trWrapper = container.querySelector('tbody').querySelector('tr'); expect(trWrapper.getAttribute('data-level')).toBe('level-1'); expect(trWrapper.getAttribute('data-name')).toBe('tdesign'); }); it('props.rowAttributes could be a Array<Function>', () => { const rowAttrs = [() => [{ 'data-level': 'level-1' }, { 'data-name': 'tdesign' }]]; const { container } = render( <TTable rowKey="index" rowAttributes={rowAttrs} data={data} columns={SIMPLE_COLUMNS}></TTable>, ); const trWrapper = container.querySelector('tbody').querySelector('tr'); expect(trWrapper.getAttribute('data-level')).toBe('level-1'); expect(trWrapper.getAttribute('data-name')).toBe('tdesign'); }); }); describe(':props.rowClassName', () => { it('props.rowClassName could be a string', () => { const rowClassName = 'tdesign-class'; const { container } = render( <TTable rowKey="index" rowClassName={rowClassName} data={data} columns={SIMPLE_COLUMNS}></TTable>, ); const trWrapper = container.querySelector('tbody').querySelector('tr'); expect(trWrapper.getAttribute('class')).toBe(rowClassName); }); it('props.rowClassName could be an object ', () => { const rowClassName = { 'tdesign-class': true, 'tdesign-class-next': false, }; const { container } = render( <TTable rowKey="index" rowClassName={rowClassName} data={data} columns={SIMPLE_COLUMNS}></TTable>, ); const trWrapper = container.querySelector('tbody').querySelector('tr'); expect(trWrapper.getAttribute('class')).toBe('tdesign-class'); }); it('props.rowClassName could be an Array ', () => { const rowClassName = [ 'tdesign-class-default', { 'tdesign-class': true, 'tdesign-class-next': false, }, ]; const { container } = render( <TTable rowKey="index" rowClassName={rowClassName} data={data} columns={SIMPLE_COLUMNS}></TTable>, ); const trWrapper = container.querySelector('tbody').querySelector('tr'); expect(trWrapper.getAttribute('class')).toBe('tdesign-class-default tdesign-class'); }); it('props.rowClassName could be a function ', () => { const rowClassName = () => ({ 'tdesign-class': true, 'tdesign-class-next': false, }); const { container } = render( <TTable rowKey="index" rowClassName={rowClassName} data={data} columns={SIMPLE_COLUMNS}></TTable>, ); const trWrapper = container.querySelector('tbody').querySelector('tr'); expect(trWrapper.getAttribute('class')).toBe('tdesign-class'); }); }); // // 测试空数据 describe(':props.empty', () => { it('empty default value is 暂无数据', () => { const { container } = render(<TTable rowKey="index" data={[]} columns={SIMPLE_COLUMNS}></TTable>); expect(container.querySelector('.t-table__empty')).toBeTruthy(); expect(container.querySelector('.t-table__empty').innerHTML).toBe('暂无数据'); }); it('props.empty=Empty Data', () => { const { container } = render( <TTable rowKey="index" data={[]} empty="Empty Data" columns={SIMPLE_COLUMNS}></TTable>, ); expect(container.querySelector('.t-table__empty')).toBeTruthy(); expect(container.querySelector('.t-table__empty').innerHTML).toBe('Empty Data'); }); it('props.empty works fine as a children', () => { const emptyText = 'Empty Data Rendered By children'; const { container } = render( <TTable rowKey="index" data={[]} empty={<div className="render-function-class">{emptyText}</div>} columns={SIMPLE_COLUMNS} ></TTable>, ); expect(container.querySelector('.t-table__empty')).toBeTruthy(); expect(container.querySelector('.render-function-class')).toBeTruthy(); expect(container.querySelector('.render-function-class').innerHTML).toBe(emptyText); }); }); // 测试第一行通栏 describe(':props.firstFullRow', () => { it('props.firstFullRow could be string', () => { const { container } = render( <TTable firstFullRow="This is a full row at first." rowKey="index" data={data} columns={SIMPLE_COLUMNS} ></TTable>, ); expect(container.querySelector('.t-table__row--full')).toBeTruthy(); }); it('props.firstFullRow works fine as a children', () => { const { container } = render( <TTable firstFullRow={<span>This is a full row at first.</span>} rowKey="index" data={data} columns={SIMPLE_COLUMNS} ></TTable>, ); expect(container.querySelector('.t-table__row--full')).toBeTruthy(); expect(container.querySelector('.t-table__first-full-row')).toBeTruthy(); }); }); // 测试最后一行通栏 describe(':props.lastFullRow', () => { it('props.lastFullRow could be string', () => { const { container } = render( <TTable lastFullRow="This is a full row at last." rowKey="index" data={data} columns={SIMPLE_COLUMNS} ></TTable>, ); expect(container.querySelector('.t-table__row--full')).toBeTruthy(); }); it('props.lastFullRow works fine as a children', () => { const { container } = render( <TTable lastFullRow={<span>This is a full row at last.</span>} rowKey="index" data={data} columns={SIMPLE_COLUMNS} ></TTable>, ); expect(container.querySelector('.t-table__row--full')).toBeTruthy(); expect(container.querySelector('.t-table__last-full-row')).toBeTruthy(); }); }); describe(':props.loading', () => { it('props.loading = true works fine', () => { const { container } = render( <TTable rowKey="index" data={data} columns={SIMPLE_COLUMNS} loading={true}></TTable>, ); expect(container.querySelector('.t-loading')).toBeTruthy(); expect(container.querySelector('.t-icon-loading')).toBeTruthy(); }); it('props.loading works fine as a function', () => { const { container } = render( <TTable rowKey="index" data={data} columns={SIMPLE_COLUMNS} loading={'function loading'}></TTable>, ); expect(container.querySelector('.t-loading')).toBeTruthy(); expect(container.querySelector('.t-icon-loading')).toBeTruthy(); expect(container.querySelector('.t-loading__text')).toBeTruthy(); expect(container.querySelector('.t-loading__text').innerHTML).toBe('function loading'); }); it('props.loading hide loading icon with `loadingProps`', () => { const { container } = render( <TTable rowKey="index" data={data} columns={SIMPLE_COLUMNS} loading={'function loading'} loadingProps={{ indicator: false }} ></TTable>, ); expect(container.querySelector('.t-loading')).toBeTruthy(); expect(container.querySelector('.t-icon-loading')).toBeFalsy(); expect(container.querySelector('.t-loading__text')).toBeTruthy(); expect(container.querySelector('.t-loading__text').innerHTML).toBe('function loading'); }); }); describe(':props.verticalAlign', () => { it('props.verticalAlign default value is middle, do not need t-vertical-align-middle', () => { const { container } = render( <TTable rowKey="index" data={data} columns={SIMPLE_COLUMNS} verticalAlign="middle"></TTable>, ); // 垂直居中对齐不需要 t-vertical-align-middle expect(container.querySelector('.t-table').getAttribute('class')).toBe('t-table'); }); it('props.verticalAlign = bottom', () => { const { container } = render( <TTable rowKey="index" data={data} columns={SIMPLE_COLUMNS} verticalAlign="bottom"></TTable>, ); expect(container.querySelector('.t-table').getAttribute('class')).toBe('t-table t-vertical-align-bottom'); }); it('props.verticalAlign = top', () => { const { container } = render( <TTable rowKey="index" data={data} columns={SIMPLE_COLUMNS} verticalAlign="top"></TTable>, ); expect(container.querySelector('.t-table').getAttribute('class')).toBe('t-table t-vertical-align-top'); }); it('props.verticalAlign = middle, do not need t-vertical-align-middle', () => { const { container } = render( <TTable rowKey="index" data={data} columns={SIMPLE_COLUMNS} verticalAlign="middle"></TTable>, ); // 垂直居中对齐不需要 t-vertical-align-middle expect(container.querySelector('.t-table').getAttribute('class')).toBe('t-table'); }); }); describe(':props.topContent', () => { it('props.topContent could be a string', () => { const topContentText = 'This is top content'; const { container } = render( <TTable topContent={topContentText} rowKey="index" data={data} columns={SIMPLE_COLUMNS}></TTable>, ); expect(container.querySelector('.t-table__top-content')).toBeTruthy(); expect(container.querySelector('.t-table__top-content').innerHTML).toBe(topContentText); }); it('props.topContent could be a function', () => { const topContentText = 'This is top content'; const { container } = render( <TTable topContent={<span>{topContentText}</span>} rowKey="index" data={data} columns={SIMPLE_COLUMNS} ></TTable>, ); expect(container.querySelector('.t-table__top-content')).toBeTruthy(); expect(container.querySelector('.t-table__top-content').innerHTML).toBe(`<span>${topContentText}</span>`); }); }); }); });
the_stack
import 'isomorphic-form-data'; import { fetch } from 'cross-fetch'; namespace Models { /** * Documents List */ export type DocumentList<Document extends Models.Document> = { /** * Total number of items available on the server. */ sum: number; /** * List of documents. */ documents: Document[]; } /** * Sessions List */ export type SessionList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of sessions. */ sessions: Session[]; } /** * Logs List */ export type LogList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of logs. */ logs: Log[]; } /** * Files List */ export type FileList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of files. */ files: File[]; } /** * Teams List */ export type TeamList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of teams. */ teams: Team[]; } /** * Memberships List */ export type MembershipList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of memberships. */ memberships: Membership[]; } /** * Executions List */ export type ExecutionList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of executions. */ executions: Execution[]; } /** * Countries List */ export type CountryList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of countries. */ countries: Country[]; } /** * Continents List */ export type ContinentList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of continents. */ continents: Continent[]; } /** * Languages List */ export type LanguageList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of languages. */ languages: Language[]; } /** * Currencies List */ export type CurrencyList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of currencies. */ currencies: Currency[]; } /** * Phones List */ export type PhoneList<> = { /** * Total number of items available on the server. */ sum: number; /** * List of phones. */ phones: Phone[]; } /** * Document */ export type Document<> = { /** * Document ID. */ $id: string; /** * Collection ID. */ $collection: string; /** * Document read permissions. */ $read: string[]; /** * Document write permissions. */ $write: string[]; } /** * Log */ export type Log<> = { /** * Event name. */ event: string; /** * User ID. */ userId: string; /** * User Email. */ userEmail: string; /** * User Name. */ userName: string; /** * API mode when event triggered. */ mode: string; /** * IP session in use when the session was created. */ ip: string; /** * Log creation time in Unix timestamp. */ time: number; /** * Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). */ osCode: string; /** * Operating system name. */ osName: string; /** * Operating system version. */ osVersion: string; /** * Client type. */ clientType: string; /** * Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). */ clientCode: string; /** * Client name. */ clientName: string; /** * Client version. */ clientVersion: string; /** * Client engine name. */ clientEngine: string; /** * Client engine name. */ clientEngineVersion: string; /** * Device name. */ deviceName: string; /** * Device brand name. */ deviceBrand: string; /** * Device model name. */ deviceModel: string; /** * Country two-character ISO 3166-1 alpha code. */ countryCode: string; /** * Country name. */ countryName: string; } /** * User */ export type User<Preferences extends Models.Preferences> = { /** * User ID. */ $id: string; /** * User name. */ name: string; /** * User registration date in Unix timestamp. */ registration: number; /** * User status. Pass `true` for enabled and `false` for disabled. */ status: boolean; /** * Unix timestamp of the most recent password update */ passwordUpdate: number; /** * User email address. */ email: string; /** * Email verification status. */ emailVerification: boolean; /** * User preferences as a key-value object */ prefs: Preferences; } /** * Preferences */ export type Preferences<> = { } /** * Session */ export type Session<> = { /** * Session ID. */ $id: string; /** * User ID. */ userId: string; /** * Session expiration date in Unix timestamp. */ expire: number; /** * Session Provider. */ provider: string; /** * Session Provider User ID. */ providerUid: string; /** * Session Provider Token. */ providerToken: string; /** * IP in use when the session was created. */ ip: string; /** * Operating system code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/os.json). */ osCode: string; /** * Operating system name. */ osName: string; /** * Operating system version. */ osVersion: string; /** * Client type. */ clientType: string; /** * Client code name. View list of [available options](https://github.com/appwrite/appwrite/blob/master/docs/lists/clients.json). */ clientCode: string; /** * Client name. */ clientName: string; /** * Client version. */ clientVersion: string; /** * Client engine name. */ clientEngine: string; /** * Client engine name. */ clientEngineVersion: string; /** * Device name. */ deviceName: string; /** * Device brand name. */ deviceBrand: string; /** * Device model name. */ deviceModel: string; /** * Country two-character ISO 3166-1 alpha code. */ countryCode: string; /** * Country name. */ countryName: string; /** * Returns true if this the current user session. */ current: boolean; } /** * Token */ export type Token<> = { /** * Token ID. */ $id: string; /** * User ID. */ userId: string; /** * Token secret key. This will return an empty string unless the response is returned using an API key or as part of a webhook payload. */ secret: string; /** * Token expiration date in Unix timestamp. */ expire: number; } /** * JWT */ export type Jwt<> = { /** * JWT encoded string. */ jwt: string; } /** * Locale */ export type Locale<> = { /** * User IP address. */ ip: string; /** * Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format */ countryCode: string; /** * Country name. This field support localization. */ country: string; /** * Continent code. A two character continent code &quot;AF&quot; for Africa, &quot;AN&quot; for Antarctica, &quot;AS&quot; for Asia, &quot;EU&quot; for Europe, &quot;NA&quot; for North America, &quot;OC&quot; for Oceania, and &quot;SA&quot; for South America. */ continentCode: string; /** * Continent name. This field support localization. */ continent: string; /** * True if country is part of the Europian Union. */ eu: boolean; /** * Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format */ currency: string; } /** * File */ export type File<> = { /** * File ID. */ $id: string; /** * File read permissions. */ $read: string[]; /** * File write permissions. */ $write: string[]; /** * File name. */ name: string; /** * File creation date in Unix timestamp. */ dateCreated: number; /** * File MD5 signature. */ signature: string; /** * File mime type. */ mimeType: string; /** * File original size in bytes. */ sizeOriginal: number; } /** * Team */ export type Team<> = { /** * Team ID. */ $id: string; /** * Team name. */ name: string; /** * Team creation date in Unix timestamp. */ dateCreated: number; /** * Total sum of team members. */ sum: number; } /** * Membership */ export type Membership<> = { /** * Membership ID. */ $id: string; /** * User ID. */ userId: string; /** * Team ID. */ teamId: string; /** * User name. */ name: string; /** * User email address. */ email: string; /** * Date, the user has been invited to join the team in Unix timestamp. */ invited: number; /** * Date, the user has accepted the invitation to join the team in Unix timestamp. */ joined: number; /** * User confirmation status, true if the user has joined the team or false otherwise. */ confirm: boolean; /** * User list of roles */ roles: string[]; } /** * Execution */ export type Execution<> = { /** * Execution ID. */ $id: string; /** * Execution read permissions. */ $read: string[]; /** * Function ID. */ functionId: string; /** * The execution creation date in Unix timestamp. */ dateCreated: number; /** * The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. */ trigger: string; /** * The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. */ status: string; /** * The script exit code. */ exitCode: number; /** * The script stdout output string. Logs the last 4,000 characters of the execution stdout output. */ stdout: string; /** * The script stderr output string. Logs the last 4,000 characters of the execution stderr output */ stderr: string; /** * The script execution time in seconds. */ time: number; } /** * Country */ export type Country<> = { /** * Country name. */ name: string; /** * Country two-character ISO 3166-1 alpha code. */ code: string; } /** * Continent */ export type Continent<> = { /** * Continent name. */ name: string; /** * Continent two letter code. */ code: string; } /** * Language */ export type Language<> = { /** * Language name. */ name: string; /** * Language two-character ISO 639-1 codes. */ code: string; /** * Language native name. */ nativeName: string; } /** * Currency */ export type Currency<> = { /** * Currency symbol. */ symbol: string; /** * Currency name. */ name: string; /** * Currency native symbol. */ symbolNative: string; /** * Number of decimal digits. */ decimalDigits: number; /** * Currency digit rounding. */ rounding: number; /** * Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format. */ code: string; /** * Currency plural name */ namePlural: string; } /** * Phone */ export type Phone<> = { /** * Phone code. */ code: string; /** * Country two-character ISO 3166-1 alpha code. */ countryCode: string; /** * Country name. */ countryName: string; } } type Payload = { [key: string]: any; } type Headers = { [key: string]: string; } type RealtimeResponse = { type: 'error'|'event'|'connected'|'response'; data: RealtimeResponseAuthenticated|RealtimeResponseConnected|RealtimeResponseError|RealtimeResponseEvent<unknown>; } type RealtimeRequest = { type: 'authentication'; data: RealtimeRequestAuthenticate; } export type RealtimeResponseEvent<T extends unknown> = { event: string; channels: string[]; timestamp: number; payload: T; } type RealtimeResponseError = { code: number; message: string; } type RealtimeResponseConnected = { channels: string[]; user?: object; } type RealtimeResponseAuthenticated = { to: string; success: boolean; user: object; } type RealtimeRequestAuthenticate = { session: string; } type Realtime = { socket?: WebSocket; timeout?: number; url?: string; lastMessage?: RealtimeResponse; channels: Set<string>; subscriptions: Map<number, { channels: string[]; callback: (payload: RealtimeResponseEvent<any>) => void }>; subscriptionsCounter: number; reconnect: boolean; reconnectAttempts: number; getTimeout: () => number; connect: () => void; createSocket: () => void; cleanUp: (channels: string[]) => void; onMessage: (event: MessageEvent) => void; } class AppwriteException extends Error { code: number; response: string; constructor(message: string, code: number = 0, response: string = '') { super(message); this.name = 'AppwriteException'; this.message = message; this.code = code; this.response = response; } } class Appwrite { config = { endpoint: 'https://HOSTNAME/v1', endpointRealtime: '', project: '', jwt: '', locale: '', }; headers: Headers = { 'x-sdk-version': 'appwrite:web:6.0.1', 'X-Appwrite-Response-Format': '0.12.0', }; /** * Set Endpoint * * Your project endpoint * * @param {string} endpoint * * @returns {this} */ setEndpoint(endpoint: string): this { this.config.endpoint = endpoint; this.config.endpointRealtime = this.config.endpointRealtime || this.config.endpoint.replace('https://', 'wss://').replace('http://', 'ws://'); return this; } /** * Set Realtime Endpoint * * @param {string} endpointRealtime * * @returns {this} */ setEndpointRealtime(endpointRealtime: string): this { this.config.endpointRealtime = endpointRealtime; return this; } /** * Set Project * * Your project ID * * @param value string * * @return {this} */ setProject(value: string): this { this.headers['X-Appwrite-Project'] = value; this.config.project = value; return this; } /** * Set JWT * * Your secret JSON Web Token * * @param value string * * @return {this} */ setJWT(value: string): this { this.headers['X-Appwrite-JWT'] = value; this.config.jwt = value; return this; } /** * Set Locale * * @param value string * * @return {this} */ setLocale(value: string): this { this.headers['X-Appwrite-Locale'] = value; this.config.locale = value; return this; } private realtime: Realtime = { socket: undefined, timeout: undefined, url: '', channels: new Set(), subscriptions: new Map(), subscriptionsCounter: 0, reconnect: true, reconnectAttempts: 0, lastMessage: undefined, connect: () => { clearTimeout(this.realtime.timeout); this.realtime.timeout = window?.setTimeout(() => { this.realtime.createSocket(); }, 50); }, getTimeout: () => { switch (true) { case this.realtime.reconnectAttempts < 5: return 1000; case this.realtime.reconnectAttempts < 15: return 5000; case this.realtime.reconnectAttempts < 100: return 10_000; default: return 60_000; } }, createSocket: () => { if (this.realtime.channels.size < 1) return; const channels = new URLSearchParams(); channels.set('project', this.config.project); this.realtime.channels.forEach(channel => { channels.append('channels[]', channel); }); const url = this.config.endpointRealtime + '/realtime?' + channels.toString(); if ( url !== this.realtime.url || // Check if URL is present !this.realtime.socket || // Check if WebSocket has not been created this.realtime.socket?.readyState > WebSocket.OPEN // Check if WebSocket is CLOSING (3) or CLOSED (4) ) { if ( this.realtime.socket && this.realtime.socket?.readyState < WebSocket.CLOSING // Close WebSocket if it is CONNECTING (0) or OPEN (1) ) { this.realtime.reconnect = false; this.realtime.socket.close(); } this.realtime.url = url; this.realtime.socket = new WebSocket(url); this.realtime.socket.addEventListener('message', this.realtime.onMessage); this.realtime.socket.addEventListener('open', _event => { this.realtime.reconnectAttempts = 0; }); this.realtime.socket.addEventListener('close', event => { if ( !this.realtime.reconnect || ( this.realtime?.lastMessage?.type === 'error' && // Check if last message was of type error (<RealtimeResponseError>this.realtime?.lastMessage.data).code === 1008 // Check for policy violation 1008 ) ) { this.realtime.reconnect = true; return; } const timeout = this.realtime.getTimeout(); console.error(`Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`, event.reason); setTimeout(() => { this.realtime.reconnectAttempts++; this.realtime.createSocket(); }, timeout); }) } }, onMessage: (event) => { try { const message: RealtimeResponse = JSON.parse(event.data); this.realtime.lastMessage = message; switch (message.type) { case 'connected': const cookie = JSON.parse(window.localStorage.getItem('cookieFallback') ?? '{}'); const session = cookie?.[`a_session_${this.config.project}`]; const messageData = <RealtimeResponseConnected>message.data; if (session && !messageData.user) { this.realtime.socket?.send(JSON.stringify(<RealtimeRequest>{ type: 'authentication', data: { session } })); } break; case 'event': let data = <RealtimeResponseEvent<unknown>>message.data; if (data?.channels) { const isSubscribed = data.channels.some(channel => this.realtime.channels.has(channel)); if (!isSubscribed) return; this.realtime.subscriptions.forEach(subscription => { if (data.channels.some(channel => subscription.channels.includes(channel))) { setTimeout(() => subscription.callback(data)); } }) } break; case 'error': throw message.data; default: break; } } catch (e) { console.error(e); } }, cleanUp: channels => { this.realtime.channels.forEach(channel => { if (channels.includes(channel)) { let found = Array.from(this.realtime.subscriptions).some(([_key, subscription] )=> { return subscription.channels.includes(channel); }) if (!found) { this.realtime.channels.delete(channel); } } }) } } /** * Subscribes to Appwrite events and passes you the payload in realtime. * * @param {string|string[]} channels * Channel to subscribe - pass a single channel as a string or multiple with an array of strings. * * Possible channels are: * - account * - collections * - collections.[ID] * - collections.[ID].documents * - documents * - documents.[ID] * - files * - files.[ID] * - executions * - executions.[ID] * - functions.[ID] * - teams * - teams.[ID] * - memberships * - memberships.[ID] * @param {(payload: RealtimeMessage) => void} callback Is called on every realtime update. * @returns {() => void} Unsubscribes from events. */ subscribe<T extends unknown>(channels: string | string[], callback: (payload: RealtimeResponseEvent<T>) => void): () => void { let channelArray = typeof channels === 'string' ? [channels] : channels; channelArray.forEach(channel => this.realtime.channels.add(channel)); const counter = this.realtime.subscriptionsCounter++; this.realtime.subscriptions.set(counter, { channels: channelArray, callback }); this.realtime.connect(); return () => { this.realtime.subscriptions.delete(counter); this.realtime.cleanUp(channelArray); this.realtime.connect(); } } private async call(method: string, url: URL, headers: Headers = {}, params: Payload = {}): Promise<any> { method = method.toUpperCase(); headers = { ...headers, ...this.headers } let options: RequestInit = { method, headers, credentials: 'include' }; if (typeof window !== 'undefined' && window.localStorage) { headers['X-Fallback-Cookies'] = window.localStorage.getItem('cookieFallback') ?? ''; } if (method === 'GET') { for (const [key, value] of Object.entries(this.flatten(params))) { url.searchParams.append(key, value); } } else { switch (headers['content-type']) { case 'application/json': options.body = JSON.stringify(params); break; case 'multipart/form-data': let formData = new FormData(); for (const key in params) { if (Array.isArray(params[key])) { params[key].forEach((value: any) => { formData.append(key + '[]', value); }) } else { formData.append(key, params[key]); } } options.body = formData; delete headers['content-type']; break; } } try { let data = null; const response = await fetch(url.toString(), options); if (response.headers.get('content-type')?.includes('application/json')) { data = await response.json(); } else { data = { message: await response.text() }; } if (400 <= response.status) { throw new AppwriteException(data?.message, response.status, data); } const cookieFallback = response.headers.get('X-Fallback-Cookies'); if (typeof window !== 'undefined' && window.localStorage && cookieFallback) { window.console.warn('Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.'); window.localStorage.setItem('cookieFallback', cookieFallback); } return data; } catch (e) { if (e instanceof AppwriteException) { throw e; } throw new AppwriteException((<Error>e).message); } } private flatten(data: Payload, prefix = ''): Payload { let output: Payload = {}; for (const key in data) { let value = data[key]; let finalKey = prefix ? `${prefix}[${key}]` : key; if (Array.isArray(value)) { output = Object.assign(output, this.flatten(value, finalKey)); } else { output[finalKey] = value; } } return output; } account = { /** * Get Account * * Get currently logged in user data as JSON object. * * @throws {AppwriteException} * @returns {Promise} */ get: async <Preferences extends Models.Preferences>(): Promise<Models.User<Preferences>> => { let path = '/account'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Account * * Use this endpoint to allow a new user to register a new account in your * project. After the user registration completes successfully, you can use * the [/account/verfication](/docs/client/account#accountCreateVerification) * route to start verifying the user email address. To allow the new user to * login to their new account, you need to create a new [account * session](/docs/client/account#accountCreateSession). * * @param {string} userId * @param {string} email * @param {string} password * @param {string} name * @throws {AppwriteException} * @returns {Promise} */ create: async <Preferences extends Models.Preferences>(userId: string, email: string, password: string, name?: string): Promise<Models.User<Preferences>> => { if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } let path = '/account'; let payload: Payload = {}; if (typeof userId !== 'undefined') { payload['userId'] = userId; } if (typeof email !== 'undefined') { payload['email'] = email; } if (typeof password !== 'undefined') { payload['password'] = password; } if (typeof name !== 'undefined') { payload['name'] = name; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Delete Account * * Delete a currently logged in user account. Behind the scene, the user * record is not deleted but permanently blocked from any access. This is done * to avoid deleted accounts being overtaken by new users with the same email * address. Any user-related resources like documents or storage files should * be deleted separately. * * @throws {AppwriteException} * @returns {Promise} */ delete: async (): Promise<{}> => { let path = '/account'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('delete', uri, { 'content-type': 'application/json', }, payload); }, /** * Update Account Email * * Update currently logged in user account email address. After changing user * address, the user confirmation status will get reset. A new confirmation * email is not sent automatically however you can use the send confirmation * email endpoint again to send the confirmation email. For security measures, * user password is required to complete this request. * This endpoint can also be used to convert an anonymous account to a normal * one, by passing an email address and a new password. * * * @param {string} email * @param {string} password * @throws {AppwriteException} * @returns {Promise} */ updateEmail: async <Preferences extends Models.Preferences>(email: string, password: string): Promise<Models.User<Preferences>> => { if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } let path = '/account/email'; let payload: Payload = {}; if (typeof email !== 'undefined') { payload['email'] = email; } if (typeof password !== 'undefined') { payload['password'] = password; } const uri = new URL(this.config.endpoint + path); return await this.call('patch', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Account JWT * * Use this endpoint to create a JSON Web Token. You can use the resulting JWT * to authenticate on behalf of the current user when working with the * Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes * from its creation and will be invalid if the user will logout in that time * frame. * * @throws {AppwriteException} * @returns {Promise} */ createJWT: async (): Promise<Models.Jwt> => { let path = '/account/jwt'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Get Account Logs * * Get currently logged in user list of latest security activity logs. Each * log returns user IP address, location and date and time of log. * * @param {number} limit * @param {number} offset * @throws {AppwriteException} * @returns {Promise} */ getLogs: async (limit?: number, offset?: number): Promise<Models.LogList> => { let path = '/account/logs'; let payload: Payload = {}; if (typeof limit !== 'undefined') { payload['limit'] = limit; } if (typeof offset !== 'undefined') { payload['offset'] = offset; } const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Update Account Name * * Update currently logged in user account name. * * @param {string} name * @throws {AppwriteException} * @returns {Promise} */ updateName: async <Preferences extends Models.Preferences>(name: string): Promise<Models.User<Preferences>> => { if (typeof name === 'undefined') { throw new AppwriteException('Missing required parameter: "name"'); } let path = '/account/name'; let payload: Payload = {}; if (typeof name !== 'undefined') { payload['name'] = name; } const uri = new URL(this.config.endpoint + path); return await this.call('patch', uri, { 'content-type': 'application/json', }, payload); }, /** * Update Account Password * * Update currently logged in user password. For validation, user is required * to pass in the new password, and the old password. For users created with * OAuth and Team Invites, oldPassword is optional. * * @param {string} password * @param {string} oldPassword * @throws {AppwriteException} * @returns {Promise} */ updatePassword: async <Preferences extends Models.Preferences>(password: string, oldPassword?: string): Promise<Models.User<Preferences>> => { if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } let path = '/account/password'; let payload: Payload = {}; if (typeof password !== 'undefined') { payload['password'] = password; } if (typeof oldPassword !== 'undefined') { payload['oldPassword'] = oldPassword; } const uri = new URL(this.config.endpoint + path); return await this.call('patch', uri, { 'content-type': 'application/json', }, payload); }, /** * Get Account Preferences * * Get currently logged in user preferences as a key-value object. * * @throws {AppwriteException} * @returns {Promise} */ getPrefs: async <Preferences extends Models.Preferences>(): Promise<Preferences> => { let path = '/account/prefs'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Update Account Preferences * * Update currently logged in user account preferences. You can pass only the * specific settings you wish to update. * * @param {object} prefs * @throws {AppwriteException} * @returns {Promise} */ updatePrefs: async <Preferences extends Models.Preferences>(prefs: object): Promise<Models.User<Preferences>> => { if (typeof prefs === 'undefined') { throw new AppwriteException('Missing required parameter: "prefs"'); } let path = '/account/prefs'; let payload: Payload = {}; if (typeof prefs !== 'undefined') { payload['prefs'] = prefs; } const uri = new URL(this.config.endpoint + path); return await this.call('patch', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Password Recovery * * Sends the user an email with a temporary secret key for password reset. * When the user clicks the confirmation link he is redirected back to your * app password reset URL with the secret key and email address values * attached to the URL query string. Use the query string params to submit a * request to the [PUT * /account/recovery](/docs/client/account#accountUpdateRecovery) endpoint to * complete the process. The verification link sent to the user's email * address is valid for 1 hour. * * @param {string} email * @param {string} url * @throws {AppwriteException} * @returns {Promise} */ createRecovery: async (email: string, url: string): Promise<Models.Token> => { if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } let path = '/account/recovery'; let payload: Payload = {}; if (typeof email !== 'undefined') { payload['email'] = email; } if (typeof url !== 'undefined') { payload['url'] = url; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Password Recovery (confirmation) * * Use this endpoint to complete the user account password reset. Both the * **userId** and **secret** arguments will be passed as query parameters to * the redirect URL you have provided when sending your request to the [POST * /account/recovery](/docs/client/account#accountCreateRecovery) endpoint. * * Please note that in order to avoid a [Redirect * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) * the only valid redirect URLs are the ones from domains you have set when * adding your platforms in the console interface. * * @param {string} userId * @param {string} secret * @param {string} password * @param {string} passwordAgain * @throws {AppwriteException} * @returns {Promise} */ updateRecovery: async (userId: string, secret: string, password: string, passwordAgain: string): Promise<Models.Token> => { if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } if (typeof passwordAgain === 'undefined') { throw new AppwriteException('Missing required parameter: "passwordAgain"'); } let path = '/account/recovery'; let payload: Payload = {}; if (typeof userId !== 'undefined') { payload['userId'] = userId; } if (typeof secret !== 'undefined') { payload['secret'] = secret; } if (typeof password !== 'undefined') { payload['password'] = password; } if (typeof passwordAgain !== 'undefined') { payload['passwordAgain'] = passwordAgain; } const uri = new URL(this.config.endpoint + path); return await this.call('put', uri, { 'content-type': 'application/json', }, payload); }, /** * Get Account Sessions * * Get currently logged in user list of active sessions across different * devices. * * @throws {AppwriteException} * @returns {Promise} */ getSessions: async (): Promise<Models.SessionList> => { let path = '/account/sessions'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Account Session * * Allow the user to login into their account by providing a valid email and * password combination. This route will create a new session for the user. * * @param {string} email * @param {string} password * @throws {AppwriteException} * @returns {Promise} */ createSession: async (email: string, password: string): Promise<Models.Session> => { if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } let path = '/account/sessions'; let payload: Payload = {}; if (typeof email !== 'undefined') { payload['email'] = email; } if (typeof password !== 'undefined') { payload['password'] = password; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Delete All Account Sessions * * Delete all sessions from the user account and remove any sessions cookies * from the end client. * * @throws {AppwriteException} * @returns {Promise} */ deleteSessions: async (): Promise<{}> => { let path = '/account/sessions'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('delete', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Anonymous Session * * Use this endpoint to allow a new user to register an anonymous account in * your project. This route will also create a new session for the user. To * allow the new user to convert an anonymous account to a normal account, you * need to update its [email and * password](/docs/client/account#accountUpdateEmail) or create an [OAuth2 * session](/docs/client/account#accountCreateOAuth2Session). * * @throws {AppwriteException} * @returns {Promise} */ createAnonymousSession: async (): Promise<Models.Session> => { let path = '/account/sessions/anonymous'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Magic URL session * * Sends the user an email with a secret key for creating a session. When the * user clicks the link in the email, the user is redirected back to the URL * you provided with the secret key and userId values attached to the URL * query string. Use the query string parameters to submit a request to the * [PUT * /account/sessions/magic-url](/docs/client/account#accountUpdateMagicURLSession) * endpoint to complete the login process. The link sent to the user's email * address is valid for 1 hour. If you are on a mobile device you can leave * the URL parameter empty, so that the login completion will be handled by * your Appwrite instance by default. * * @param {string} userId * @param {string} email * @param {string} url * @throws {AppwriteException} * @returns {Promise} */ createMagicURLSession: async (userId: string, email: string, url?: string): Promise<Models.Token> => { if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } let path = '/account/sessions/magic-url'; let payload: Payload = {}; if (typeof userId !== 'undefined') { payload['userId'] = userId; } if (typeof email !== 'undefined') { payload['email'] = email; } if (typeof url !== 'undefined') { payload['url'] = url; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Magic URL session (confirmation) * * Use this endpoint to complete creating the session with the Magic URL. Both * the **userId** and **secret** arguments will be passed as query parameters * to the redirect URL you have provided when sending your request to the * [POST * /account/sessions/magic-url](/docs/client/account#accountCreateMagicURLSession) * endpoint. * * Please note that in order to avoid a [Redirect * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) * the only valid redirect URLs are the ones from domains you have set when * adding your platforms in the console interface. * * @param {string} userId * @param {string} secret * @throws {AppwriteException} * @returns {Promise} */ updateMagicURLSession: async (userId: string, secret: string): Promise<Models.Session> => { if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } let path = '/account/sessions/magic-url'; let payload: Payload = {}; if (typeof userId !== 'undefined') { payload['userId'] = userId; } if (typeof secret !== 'undefined') { payload['secret'] = secret; } const uri = new URL(this.config.endpoint + path); return await this.call('put', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Account Session with OAuth2 * * Allow the user to login to their account using the OAuth2 provider of their * choice. Each OAuth2 provider should be enabled from the Appwrite console * first. Use the success and failure arguments to provide a redirect URL's * back to your app when login is completed. * * If there is already an active session, the new session will be attached to * the logged-in account. If there are no active sessions, the server will * attempt to look for a user with the same email address as the email * received from the OAuth2 provider and attach the new session to the * existing user. If no matching user is found - the server will create a new * user.. * * * @param {string} provider * @param {string} success * @param {string} failure * @param {string[]} scopes * @throws {AppwriteException} * @returns {void|string} */ createOAuth2Session: (provider: string, success?: string, failure?: string, scopes?: string[]): void | URL => { if (typeof provider === 'undefined') { throw new AppwriteException('Missing required parameter: "provider"'); } let path = '/account/sessions/oauth2/{provider}'.replace('{provider}', provider); let payload: Payload = {}; if (typeof success !== 'undefined') { payload['success'] = success; } if (typeof failure !== 'undefined') { payload['failure'] = failure; } if (typeof scopes !== 'undefined') { payload['scopes'] = scopes; } const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } if (typeof window !== 'undefined' && window?.location) { window.location.href = uri.toString(); } else { return uri; } }, /** * Get Session By ID * * Use this endpoint to get a logged in user's session using a Session ID. * Inputting 'current' will return the current session being used. * * @param {string} sessionId * @throws {AppwriteException} * @returns {Promise} */ getSession: async (sessionId: string): Promise<Models.Session> => { if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } let path = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Delete Account Session * * Use this endpoint to log out the currently logged in user from all their * account sessions across all of their different devices. When using the * option id argument, only the session unique ID provider will be deleted. * * @param {string} sessionId * @throws {AppwriteException} * @returns {Promise} */ deleteSession: async (sessionId: string): Promise<{}> => { if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } let path = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('delete', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Email Verification * * Use this endpoint to send a verification message to your user email address * to confirm they are the valid owners of that address. Both the **userId** * and **secret** arguments will be passed as query parameters to the URL you * have provided to be attached to the verification email. The provided URL * should redirect the user back to your app and allow you to complete the * verification process by verifying both the **userId** and **secret** * parameters. Learn more about how to [complete the verification * process](/docs/client/account#accountUpdateVerification). The verification * link sent to the user's email address is valid for 7 days. * * Please note that in order to avoid a [Redirect * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), * the only valid redirect URLs are the ones from domains you have set when * adding your platforms in the console interface. * * * @param {string} url * @throws {AppwriteException} * @returns {Promise} */ createVerification: async (url: string): Promise<Models.Token> => { if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } let path = '/account/verification'; let payload: Payload = {}; if (typeof url !== 'undefined') { payload['url'] = url; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Email Verification (confirmation) * * Use this endpoint to complete the user email verification process. Use both * the **userId** and **secret** parameters that were attached to your app URL * to verify the user email ownership. If confirmed this route will return a * 200 status code. * * @param {string} userId * @param {string} secret * @throws {AppwriteException} * @returns {Promise} */ updateVerification: async (userId: string, secret: string): Promise<Models.Token> => { if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } let path = '/account/verification'; let payload: Payload = {}; if (typeof userId !== 'undefined') { payload['userId'] = userId; } if (typeof secret !== 'undefined') { payload['secret'] = secret; } const uri = new URL(this.config.endpoint + path); return await this.call('put', uri, { 'content-type': 'application/json', }, payload); } }; avatars = { /** * Get Browser Icon * * You can use this endpoint to show different browser icons to your users. * The code argument receives the browser code as it appears in your user * /account/sessions endpoint. Use width, height and quality arguments to * change the output settings. * * @param {string} code * @param {number} width * @param {number} height * @param {number} quality * @throws {AppwriteException} * @returns {URL} */ getBrowser: (code: string, width?: number, height?: number, quality?: number): URL => { if (typeof code === 'undefined') { throw new AppwriteException('Missing required parameter: "code"'); } let path = '/avatars/browsers/{code}'.replace('{code}', code); let payload: Payload = {}; if (typeof width !== 'undefined') { payload['width'] = width; } if (typeof height !== 'undefined') { payload['height'] = height; } if (typeof quality !== 'undefined') { payload['quality'] = quality; } const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; }, /** * Get Credit Card Icon * * The credit card endpoint will return you the icon of the credit card * provider you need. Use width, height and quality arguments to change the * output settings. * * @param {string} code * @param {number} width * @param {number} height * @param {number} quality * @throws {AppwriteException} * @returns {URL} */ getCreditCard: (code: string, width?: number, height?: number, quality?: number): URL => { if (typeof code === 'undefined') { throw new AppwriteException('Missing required parameter: "code"'); } let path = '/avatars/credit-cards/{code}'.replace('{code}', code); let payload: Payload = {}; if (typeof width !== 'undefined') { payload['width'] = width; } if (typeof height !== 'undefined') { payload['height'] = height; } if (typeof quality !== 'undefined') { payload['quality'] = quality; } const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; }, /** * Get Favicon * * Use this endpoint to fetch the favorite icon (AKA favicon) of any remote * website URL. * * * @param {string} url * @throws {AppwriteException} * @returns {URL} */ getFavicon: (url: string): URL => { if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } let path = '/avatars/favicon'; let payload: Payload = {}; if (typeof url !== 'undefined') { payload['url'] = url; } const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; }, /** * Get Country Flag * * You can use this endpoint to show different country flags icons to your * users. The code argument receives the 2 letter country code. Use width, * height and quality arguments to change the output settings. * * @param {string} code * @param {number} width * @param {number} height * @param {number} quality * @throws {AppwriteException} * @returns {URL} */ getFlag: (code: string, width?: number, height?: number, quality?: number): URL => { if (typeof code === 'undefined') { throw new AppwriteException('Missing required parameter: "code"'); } let path = '/avatars/flags/{code}'.replace('{code}', code); let payload: Payload = {}; if (typeof width !== 'undefined') { payload['width'] = width; } if (typeof height !== 'undefined') { payload['height'] = height; } if (typeof quality !== 'undefined') { payload['quality'] = quality; } const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; }, /** * Get Image from URL * * Use this endpoint to fetch a remote image URL and crop it to any image size * you want. This endpoint is very useful if you need to crop and display * remote images in your app or in case you want to make sure a 3rd party * image is properly served using a TLS protocol. * * @param {string} url * @param {number} width * @param {number} height * @throws {AppwriteException} * @returns {URL} */ getImage: (url: string, width?: number, height?: number): URL => { if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } let path = '/avatars/image'; let payload: Payload = {}; if (typeof url !== 'undefined') { payload['url'] = url; } if (typeof width !== 'undefined') { payload['width'] = width; } if (typeof height !== 'undefined') { payload['height'] = height; } const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; }, /** * Get User Initials * * Use this endpoint to show your user initials avatar icon on your website or * app. By default, this route will try to print your logged-in user name or * email initials. You can also overwrite the user name if you pass the 'name' * parameter. If no name is given and no user is logged, an empty avatar will * be returned. * * You can use the color and background params to change the avatar colors. By * default, a random theme will be selected. The random theme will persist for * the user's initials when reloading the same theme will always return for * the same initials. * * @param {string} name * @param {number} width * @param {number} height * @param {string} color * @param {string} background * @throws {AppwriteException} * @returns {URL} */ getInitials: (name?: string, width?: number, height?: number, color?: string, background?: string): URL => { let path = '/avatars/initials'; let payload: Payload = {}; if (typeof name !== 'undefined') { payload['name'] = name; } if (typeof width !== 'undefined') { payload['width'] = width; } if (typeof height !== 'undefined') { payload['height'] = height; } if (typeof color !== 'undefined') { payload['color'] = color; } if (typeof background !== 'undefined') { payload['background'] = background; } const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; }, /** * Get QR Code * * Converts a given plain text to a QR code image. You can use the query * parameters to change the size and style of the resulting image. * * @param {string} text * @param {number} size * @param {number} margin * @param {boolean} download * @throws {AppwriteException} * @returns {URL} */ getQR: (text: string, size?: number, margin?: number, download?: boolean): URL => { if (typeof text === 'undefined') { throw new AppwriteException('Missing required parameter: "text"'); } let path = '/avatars/qr'; let payload: Payload = {}; if (typeof text !== 'undefined') { payload['text'] = text; } if (typeof size !== 'undefined') { payload['size'] = size; } if (typeof margin !== 'undefined') { payload['margin'] = margin; } if (typeof download !== 'undefined') { payload['download'] = download; } const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; } }; database = { /** * List Documents * * Get a list of all the user documents. You can use the query params to * filter your results. On admin mode, this endpoint will return a list of all * of the project's documents. [Learn more about different API * modes](/docs/admin). * * @param {string} collectionId * @param {string[]} queries * @param {number} limit * @param {number} offset * @param {string} cursor * @param {string} cursorDirection * @param {string[]} orderAttributes * @param {string[]} orderTypes * @throws {AppwriteException} * @returns {Promise} */ listDocuments: async <Document extends Models.Document>(collectionId: string, queries?: string[], limit?: number, offset?: number, cursor?: string, cursorDirection?: string, orderAttributes?: string[], orderTypes?: string[]): Promise<Models.DocumentList<Document>> => { if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } let path = '/database/collections/{collectionId}/documents'.replace('{collectionId}', collectionId); let payload: Payload = {}; if (typeof queries !== 'undefined') { payload['queries'] = queries; } if (typeof limit !== 'undefined') { payload['limit'] = limit; } if (typeof offset !== 'undefined') { payload['offset'] = offset; } if (typeof cursor !== 'undefined') { payload['cursor'] = cursor; } if (typeof cursorDirection !== 'undefined') { payload['cursorDirection'] = cursorDirection; } if (typeof orderAttributes !== 'undefined') { payload['orderAttributes'] = orderAttributes; } if (typeof orderTypes !== 'undefined') { payload['orderTypes'] = orderTypes; } const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Document * * Create a new Document. Before using this route, you should create a new * collection resource using either a [server * integration](/docs/server/database#databaseCreateCollection) API or * directly from your database console. * * @param {string} collectionId * @param {string} documentId * @param {object} data * @param {string[]} read * @param {string[]} write * @throws {AppwriteException} * @returns {Promise} */ createDocument: async <Document extends Models.Document>(collectionId: string, documentId: string, data: object, read?: string[], write?: string[]): Promise<Document> => { if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } if (typeof documentId === 'undefined') { throw new AppwriteException('Missing required parameter: "documentId"'); } if (typeof data === 'undefined') { throw new AppwriteException('Missing required parameter: "data"'); } let path = '/database/collections/{collectionId}/documents'.replace('{collectionId}', collectionId); let payload: Payload = {}; if (typeof documentId !== 'undefined') { payload['documentId'] = documentId; } if (typeof data !== 'undefined') { payload['data'] = data; } if (typeof read !== 'undefined') { payload['read'] = read; } if (typeof write !== 'undefined') { payload['write'] = write; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Get Document * * Get a document by its unique ID. This endpoint response returns a JSON * object with the document data. * * @param {string} collectionId * @param {string} documentId * @throws {AppwriteException} * @returns {Promise} */ getDocument: async <Document extends Models.Document>(collectionId: string, documentId: string): Promise<Document> => { if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } if (typeof documentId === 'undefined') { throw new AppwriteException('Missing required parameter: "documentId"'); } let path = '/database/collections/{collectionId}/documents/{documentId}'.replace('{collectionId}', collectionId).replace('{documentId}', documentId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Update Document * * Update a document by its unique ID. Using the patch method you can pass * only specific fields that will get updated. * * @param {string} collectionId * @param {string} documentId * @param {object} data * @param {string[]} read * @param {string[]} write * @throws {AppwriteException} * @returns {Promise} */ updateDocument: async <Document extends Models.Document>(collectionId: string, documentId: string, data: object, read?: string[], write?: string[]): Promise<Document> => { if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } if (typeof documentId === 'undefined') { throw new AppwriteException('Missing required parameter: "documentId"'); } if (typeof data === 'undefined') { throw new AppwriteException('Missing required parameter: "data"'); } let path = '/database/collections/{collectionId}/documents/{documentId}'.replace('{collectionId}', collectionId).replace('{documentId}', documentId); let payload: Payload = {}; if (typeof data !== 'undefined') { payload['data'] = data; } if (typeof read !== 'undefined') { payload['read'] = read; } if (typeof write !== 'undefined') { payload['write'] = write; } const uri = new URL(this.config.endpoint + path); return await this.call('patch', uri, { 'content-type': 'application/json', }, payload); }, /** * Delete Document * * Delete a document by its unique ID. This endpoint deletes only the parent * documents, its attributes and relations to other documents. Child documents * **will not** be deleted. * * @param {string} collectionId * @param {string} documentId * @throws {AppwriteException} * @returns {Promise} */ deleteDocument: async (collectionId: string, documentId: string): Promise<{}> => { if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } if (typeof documentId === 'undefined') { throw new AppwriteException('Missing required parameter: "documentId"'); } let path = '/database/collections/{collectionId}/documents/{documentId}'.replace('{collectionId}', collectionId).replace('{documentId}', documentId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('delete', uri, { 'content-type': 'application/json', }, payload); } }; functions = { /** * List Executions * * Get a list of all the current user function execution logs. You can use the * query params to filter your results. On admin mode, this endpoint will * return a list of all of the project's executions. [Learn more about * different API modes](/docs/admin). * * @param {string} functionId * @param {number} limit * @param {number} offset * @param {string} search * @param {string} cursor * @param {string} cursorDirection * @throws {AppwriteException} * @returns {Promise} */ listExecutions: async (functionId: string, limit?: number, offset?: number, search?: string, cursor?: string, cursorDirection?: string): Promise<Models.ExecutionList> => { if (typeof functionId === 'undefined') { throw new AppwriteException('Missing required parameter: "functionId"'); } let path = '/functions/{functionId}/executions'.replace('{functionId}', functionId); let payload: Payload = {}; if (typeof limit !== 'undefined') { payload['limit'] = limit; } if (typeof offset !== 'undefined') { payload['offset'] = offset; } if (typeof search !== 'undefined') { payload['search'] = search; } if (typeof cursor !== 'undefined') { payload['cursor'] = cursor; } if (typeof cursorDirection !== 'undefined') { payload['cursorDirection'] = cursorDirection; } const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Execution * * Trigger a function execution. The returned object will return you the * current execution status. You can ping the `Get Execution` endpoint to get * updates on the current execution status. Once this endpoint is called, your * function execution process will start asynchronously. * * @param {string} functionId * @param {string} data * @throws {AppwriteException} * @returns {Promise} */ createExecution: async (functionId: string, data?: string): Promise<Models.Execution> => { if (typeof functionId === 'undefined') { throw new AppwriteException('Missing required parameter: "functionId"'); } let path = '/functions/{functionId}/executions'.replace('{functionId}', functionId); let payload: Payload = {}; if (typeof data !== 'undefined') { payload['data'] = data; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Get Execution * * Get a function execution log by its unique ID. * * @param {string} functionId * @param {string} executionId * @throws {AppwriteException} * @returns {Promise} */ getExecution: async (functionId: string, executionId: string): Promise<Models.Execution> => { if (typeof functionId === 'undefined') { throw new AppwriteException('Missing required parameter: "functionId"'); } if (typeof executionId === 'undefined') { throw new AppwriteException('Missing required parameter: "executionId"'); } let path = '/functions/{functionId}/executions/{executionId}'.replace('{functionId}', functionId).replace('{executionId}', executionId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); } }; locale = { /** * Get User Locale * * Get the current user location based on IP. Returns an object with user * country code, country name, continent name, continent code, ip address and * suggested currency. You can use the locale header to get the data in a * supported language. * * ([IP Geolocation by DB-IP](https://db-ip.com)) * * @throws {AppwriteException} * @returns {Promise} */ get: async (): Promise<Models.Locale> => { let path = '/locale'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * List Continents * * List of all continents. You can use the locale header to get the data in a * supported language. * * @throws {AppwriteException} * @returns {Promise} */ getContinents: async (): Promise<Models.ContinentList> => { let path = '/locale/continents'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * List Countries * * List of all countries. You can use the locale header to get the data in a * supported language. * * @throws {AppwriteException} * @returns {Promise} */ getCountries: async (): Promise<Models.CountryList> => { let path = '/locale/countries'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * List EU Countries * * List of all countries that are currently members of the EU. You can use the * locale header to get the data in a supported language. * * @throws {AppwriteException} * @returns {Promise} */ getCountriesEU: async (): Promise<Models.CountryList> => { let path = '/locale/countries/eu'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * List Countries Phone Codes * * List of all countries phone codes. You can use the locale header to get the * data in a supported language. * * @throws {AppwriteException} * @returns {Promise} */ getCountriesPhones: async (): Promise<Models.PhoneList> => { let path = '/locale/countries/phones'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * List Currencies * * List of all currencies, including currency symbol, name, plural, and * decimal digits for all major and minor currencies. You can use the locale * header to get the data in a supported language. * * @throws {AppwriteException} * @returns {Promise} */ getCurrencies: async (): Promise<Models.CurrencyList> => { let path = '/locale/currencies'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * List Languages * * List of all languages classified by ISO 639-1 including 2-letter code, name * in English, and name in the respective language. * * @throws {AppwriteException} * @returns {Promise} */ getLanguages: async (): Promise<Models.LanguageList> => { let path = '/locale/languages'; let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); } }; storage = { /** * List Files * * Get a list of all the user files. You can use the query params to filter * your results. On admin mode, this endpoint will return a list of all of the * project's files. [Learn more about different API modes](/docs/admin). * * @param {string} search * @param {number} limit * @param {number} offset * @param {string} cursor * @param {string} cursorDirection * @param {string} orderType * @throws {AppwriteException} * @returns {Promise} */ listFiles: async (search?: string, limit?: number, offset?: number, cursor?: string, cursorDirection?: string, orderType?: string): Promise<Models.FileList> => { let path = '/storage/files'; let payload: Payload = {}; if (typeof search !== 'undefined') { payload['search'] = search; } if (typeof limit !== 'undefined') { payload['limit'] = limit; } if (typeof offset !== 'undefined') { payload['offset'] = offset; } if (typeof cursor !== 'undefined') { payload['cursor'] = cursor; } if (typeof cursorDirection !== 'undefined') { payload['cursorDirection'] = cursorDirection; } if (typeof orderType !== 'undefined') { payload['orderType'] = orderType; } const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Create File * * Create a new file. The user who creates the file will automatically be * assigned to read and write access unless he has passed custom values for * read and write arguments. * * @param {string} fileId * @param {File} file * @param {string[]} read * @param {string[]} write * @throws {AppwriteException} * @returns {Promise} */ createFile: async (fileId: string, file: File, read?: string[], write?: string[]): Promise<Models.File> => { if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } if (typeof file === 'undefined') { throw new AppwriteException('Missing required parameter: "file"'); } let path = '/storage/files'; let payload: Payload = {}; if (typeof fileId !== 'undefined') { payload['fileId'] = fileId; } if (typeof file !== 'undefined') { payload['file'] = file; } if (typeof read !== 'undefined') { payload['read'] = read; } if (typeof write !== 'undefined') { payload['write'] = write; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'multipart/form-data', }, payload); }, /** * Get File * * Get a file by its unique ID. This endpoint response returns a JSON object * with the file metadata. * * @param {string} fileId * @throws {AppwriteException} * @returns {Promise} */ getFile: async (fileId: string): Promise<Models.File> => { if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } let path = '/storage/files/{fileId}'.replace('{fileId}', fileId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Update File * * Update a file by its unique ID. Only users with write permissions have * access to update this resource. * * @param {string} fileId * @param {string[]} read * @param {string[]} write * @throws {AppwriteException} * @returns {Promise} */ updateFile: async (fileId: string, read: string[], write: string[]): Promise<Models.File> => { if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } if (typeof read === 'undefined') { throw new AppwriteException('Missing required parameter: "read"'); } if (typeof write === 'undefined') { throw new AppwriteException('Missing required parameter: "write"'); } let path = '/storage/files/{fileId}'.replace('{fileId}', fileId); let payload: Payload = {}; if (typeof read !== 'undefined') { payload['read'] = read; } if (typeof write !== 'undefined') { payload['write'] = write; } const uri = new URL(this.config.endpoint + path); return await this.call('put', uri, { 'content-type': 'application/json', }, payload); }, /** * Delete File * * Delete a file by its unique ID. Only users with write permissions have * access to delete this resource. * * @param {string} fileId * @throws {AppwriteException} * @returns {Promise} */ deleteFile: async (fileId: string): Promise<{}> => { if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } let path = '/storage/files/{fileId}'.replace('{fileId}', fileId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('delete', uri, { 'content-type': 'application/json', }, payload); }, /** * Get File for Download * * Get a file content by its unique ID. The endpoint response return with a * 'Content-Disposition: attachment' header that tells the browser to start * downloading the file to user downloads directory. * * @param {string} fileId * @throws {AppwriteException} * @returns {URL} */ getFileDownload: (fileId: string): URL => { if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } let path = '/storage/files/{fileId}/download'.replace('{fileId}', fileId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; }, /** * Get File Preview * * Get a file preview image. Currently, this method supports preview for image * files (jpg, png, and gif), other supported formats, like pdf, docs, slides, * and spreadsheets, will return the file icon image. You can also pass query * string arguments for cutting and resizing your preview image. * * @param {string} fileId * @param {number} width * @param {number} height * @param {string} gravity * @param {number} quality * @param {number} borderWidth * @param {string} borderColor * @param {number} borderRadius * @param {number} opacity * @param {number} rotation * @param {string} background * @param {string} output * @throws {AppwriteException} * @returns {URL} */ getFilePreview: (fileId: string, width?: number, height?: number, gravity?: string, quality?: number, borderWidth?: number, borderColor?: string, borderRadius?: number, opacity?: number, rotation?: number, background?: string, output?: string): URL => { if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } let path = '/storage/files/{fileId}/preview'.replace('{fileId}', fileId); let payload: Payload = {}; if (typeof width !== 'undefined') { payload['width'] = width; } if (typeof height !== 'undefined') { payload['height'] = height; } if (typeof gravity !== 'undefined') { payload['gravity'] = gravity; } if (typeof quality !== 'undefined') { payload['quality'] = quality; } if (typeof borderWidth !== 'undefined') { payload['borderWidth'] = borderWidth; } if (typeof borderColor !== 'undefined') { payload['borderColor'] = borderColor; } if (typeof borderRadius !== 'undefined') { payload['borderRadius'] = borderRadius; } if (typeof opacity !== 'undefined') { payload['opacity'] = opacity; } if (typeof rotation !== 'undefined') { payload['rotation'] = rotation; } if (typeof background !== 'undefined') { payload['background'] = background; } if (typeof output !== 'undefined') { payload['output'] = output; } const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; }, /** * Get File for View * * Get a file content by its unique ID. This endpoint is similar to the * download method but returns with no 'Content-Disposition: attachment' * header. * * @param {string} fileId * @throws {AppwriteException} * @returns {URL} */ getFileView: (fileId: string): URL => { if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } let path = '/storage/files/{fileId}/view'.replace('{fileId}', fileId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); payload['project'] = this.config.project; for (const [key, value] of Object.entries(this.flatten(payload))) { uri.searchParams.append(key, value); } return uri; } }; teams = { /** * List Teams * * Get a list of all the teams in which the current user is a member. You can * use the parameters to filter your results. * * In admin mode, this endpoint returns a list of all the teams in the current * project. [Learn more about different API modes](/docs/admin). * * @param {string} search * @param {number} limit * @param {number} offset * @param {string} cursor * @param {string} cursorDirection * @param {string} orderType * @throws {AppwriteException} * @returns {Promise} */ list: async (search?: string, limit?: number, offset?: number, cursor?: string, cursorDirection?: string, orderType?: string): Promise<Models.TeamList> => { let path = '/teams'; let payload: Payload = {}; if (typeof search !== 'undefined') { payload['search'] = search; } if (typeof limit !== 'undefined') { payload['limit'] = limit; } if (typeof offset !== 'undefined') { payload['offset'] = offset; } if (typeof cursor !== 'undefined') { payload['cursor'] = cursor; } if (typeof cursorDirection !== 'undefined') { payload['cursorDirection'] = cursorDirection; } if (typeof orderType !== 'undefined') { payload['orderType'] = orderType; } const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Team * * Create a new team. The user who creates the team will automatically be * assigned as the owner of the team. Only the users with the owner role can * invite new members, add new owners and delete or update the team. * * @param {string} teamId * @param {string} name * @param {string[]} roles * @throws {AppwriteException} * @returns {Promise} */ create: async (teamId: string, name: string, roles?: string[]): Promise<Models.Team> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } if (typeof name === 'undefined') { throw new AppwriteException('Missing required parameter: "name"'); } let path = '/teams'; let payload: Payload = {}; if (typeof teamId !== 'undefined') { payload['teamId'] = teamId; } if (typeof name !== 'undefined') { payload['name'] = name; } if (typeof roles !== 'undefined') { payload['roles'] = roles; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Get Team * * Get a team by its ID. All team members have read access for this resource. * * @param {string} teamId * @throws {AppwriteException} * @returns {Promise} */ get: async (teamId: string): Promise<Models.Team> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } let path = '/teams/{teamId}'.replace('{teamId}', teamId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Update Team * * Update a team using its ID. Only members with the owner role can update the * team. * * @param {string} teamId * @param {string} name * @throws {AppwriteException} * @returns {Promise} */ update: async (teamId: string, name: string): Promise<Models.Team> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } if (typeof name === 'undefined') { throw new AppwriteException('Missing required parameter: "name"'); } let path = '/teams/{teamId}'.replace('{teamId}', teamId); let payload: Payload = {}; if (typeof name !== 'undefined') { payload['name'] = name; } const uri = new URL(this.config.endpoint + path); return await this.call('put', uri, { 'content-type': 'application/json', }, payload); }, /** * Delete Team * * Delete a team using its ID. Only team members with the owner role can * delete the team. * * @param {string} teamId * @throws {AppwriteException} * @returns {Promise} */ delete: async (teamId: string): Promise<{}> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } let path = '/teams/{teamId}'.replace('{teamId}', teamId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('delete', uri, { 'content-type': 'application/json', }, payload); }, /** * Get Team Memberships * * Use this endpoint to list a team's members using the team's ID. All team * members have read access to this endpoint. * * @param {string} teamId * @param {string} search * @param {number} limit * @param {number} offset * @param {string} cursor * @param {string} cursorDirection * @param {string} orderType * @throws {AppwriteException} * @returns {Promise} */ getMemberships: async (teamId: string, search?: string, limit?: number, offset?: number, cursor?: string, cursorDirection?: string, orderType?: string): Promise<Models.MembershipList> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } let path = '/teams/{teamId}/memberships'.replace('{teamId}', teamId); let payload: Payload = {}; if (typeof search !== 'undefined') { payload['search'] = search; } if (typeof limit !== 'undefined') { payload['limit'] = limit; } if (typeof offset !== 'undefined') { payload['offset'] = offset; } if (typeof cursor !== 'undefined') { payload['cursor'] = cursor; } if (typeof cursorDirection !== 'undefined') { payload['cursorDirection'] = cursorDirection; } if (typeof orderType !== 'undefined') { payload['orderType'] = orderType; } const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Create Team Membership * * Invite a new member to join your team. If initiated from the client SDK, an * email with a link to join the team will be sent to the member's email * address and an account will be created for them should they not be signed * up already. If initiated from server-side SDKs, the new member will * automatically be added to the team. * * Use the 'url' parameter to redirect the user from the invitation email back * to your app. When the user is redirected, use the [Update Team Membership * Status](/docs/client/teams#teamsUpdateMembershipStatus) endpoint to allow * the user to accept the invitation to the team. * * Please note that to avoid a [Redirect * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) * the only valid redirect URL's are the once from domains you have set when * adding your platforms in the console interface. * * @param {string} teamId * @param {string} email * @param {string[]} roles * @param {string} url * @param {string} name * @throws {AppwriteException} * @returns {Promise} */ createMembership: async (teamId: string, email: string, roles: string[], url: string, name?: string): Promise<Models.Membership> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } if (typeof roles === 'undefined') { throw new AppwriteException('Missing required parameter: "roles"'); } if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } let path = '/teams/{teamId}/memberships'.replace('{teamId}', teamId); let payload: Payload = {}; if (typeof email !== 'undefined') { payload['email'] = email; } if (typeof roles !== 'undefined') { payload['roles'] = roles; } if (typeof url !== 'undefined') { payload['url'] = url; } if (typeof name !== 'undefined') { payload['name'] = name; } const uri = new URL(this.config.endpoint + path); return await this.call('post', uri, { 'content-type': 'application/json', }, payload); }, /** * Get Team Membership * * Get a team member by the membership unique id. All team members have read * access for this resource. * * @param {string} teamId * @param {string} membershipId * @throws {AppwriteException} * @returns {Promise} */ getMembership: async (teamId: string, membershipId: string): Promise<Models.MembershipList> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } if (typeof membershipId === 'undefined') { throw new AppwriteException('Missing required parameter: "membershipId"'); } let path = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('get', uri, { 'content-type': 'application/json', }, payload); }, /** * Update Membership Roles * * Modify the roles of a team member. Only team members with the owner role * have access to this endpoint. Learn more about [roles and * permissions](/docs/permissions). * * @param {string} teamId * @param {string} membershipId * @param {string[]} roles * @throws {AppwriteException} * @returns {Promise} */ updateMembershipRoles: async (teamId: string, membershipId: string, roles: string[]): Promise<Models.Membership> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } if (typeof membershipId === 'undefined') { throw new AppwriteException('Missing required parameter: "membershipId"'); } if (typeof roles === 'undefined') { throw new AppwriteException('Missing required parameter: "roles"'); } let path = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); let payload: Payload = {}; if (typeof roles !== 'undefined') { payload['roles'] = roles; } const uri = new URL(this.config.endpoint + path); return await this.call('patch', uri, { 'content-type': 'application/json', }, payload); }, /** * Delete Team Membership * * This endpoint allows a user to leave a team or for a team owner to delete * the membership of any other team member. You can also use this endpoint to * delete a user membership even if it is not accepted. * * @param {string} teamId * @param {string} membershipId * @throws {AppwriteException} * @returns {Promise} */ deleteMembership: async (teamId: string, membershipId: string): Promise<{}> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } if (typeof membershipId === 'undefined') { throw new AppwriteException('Missing required parameter: "membershipId"'); } let path = '/teams/{teamId}/memberships/{membershipId}'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); let payload: Payload = {}; const uri = new URL(this.config.endpoint + path); return await this.call('delete', uri, { 'content-type': 'application/json', }, payload); }, /** * Update Team Membership Status * * Use this endpoint to allow a user to accept an invitation to join a team * after being redirected back to your app from the invitation email received * by the user. * * @param {string} teamId * @param {string} membershipId * @param {string} userId * @param {string} secret * @throws {AppwriteException} * @returns {Promise} */ updateMembershipStatus: async (teamId: string, membershipId: string, userId: string, secret: string): Promise<Models.Membership> => { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } if (typeof membershipId === 'undefined') { throw new AppwriteException('Missing required parameter: "membershipId"'); } if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } let path = '/teams/{teamId}/memberships/{membershipId}/status'.replace('{teamId}', teamId).replace('{membershipId}', membershipId); let payload: Payload = {}; if (typeof userId !== 'undefined') { payload['userId'] = userId; } if (typeof secret !== 'undefined') { payload['secret'] = secret; } const uri = new URL(this.config.endpoint + path); return await this.call('patch', uri, { 'content-type': 'application/json', }, payload); } }; }; type QueryTypesSingle = string | number | boolean; type QueryTypesList = string[] | number[] | boolean[]; type QueryTypes = QueryTypesSingle | QueryTypesList; class Query { static equal = (attribute: string, value: QueryTypes): string => Query.addQuery(attribute, "equal", value); static notEqual = (attribute: string, value: QueryTypes): string => Query.addQuery(attribute, "notEqual", value); static lesser = (attribute: string, value: QueryTypes): string => Query.addQuery(attribute, "lesser", value); static lesserEqual = (attribute: string, value: QueryTypes): string => Query.addQuery(attribute, "lesserEqual", value); static greater = (attribute: string, value: QueryTypes): string => Query.addQuery(attribute, "greater", value); static greaterEqual = (attribute: string, value: QueryTypes): string => Query.addQuery(attribute, "greaterEqual", value); static search = (attribute: string, value: string): string => Query.addQuery(attribute, "search", value); private static addQuery = (attribute: string, oper: string, value: QueryTypes): string => value instanceof Array ? `${attribute}.${oper}(${value .map((v: QueryTypesSingle) => Query.parseValues(v)) .join(",")})` : `${attribute}.${oper}(${Query.parseValues(value)})`; private static parseValues = (value: QueryTypes): string => typeof value === "string" || value instanceof String ? `"${value}"` : `${value}`; } export { Appwrite, Query } export type { AppwriteException, Models, QueryTypes, QueryTypesList }
the_stack
import React from 'react'; import classnames from 'classnames'; import { MDCTextFieldAdapter, MDCTextFieldRootAdapter, MDCTextFieldLabelAdapter, MDCTextFieldInputAdapter, MDCTextFieldOutlineAdapter, MDCTextFieldLineRippleAdapter, } from '@material/textfield/adapter'; import {MDCTextFieldFoundation} from '@material/textfield/foundation'; import Input, {InputProps} from './Input'; import Icon, {IconProps} from './icon'; import HelperText, {HelperTextProps} from './helper-text'; import CharacterCounter, {CharacterCounterProps} from './character-counter'; import FloatingLabel from '@material/react-floating-label'; import LineRipple from '@material/react-line-ripple'; import NotchedOutline from '@material/react-notched-outline'; const cssClasses = MDCTextFieldFoundation.cssClasses; export interface Props<T extends HTMLElement = HTMLInputElement> { // InputProps<T> includes the prop `id`, which we use below in the constructor 'children.props'?: InputProps<T>; children: React.ReactElement<Input<T>>; className?: string; dense?: boolean; floatingLabelClassName?: string; fullWidth?: boolean; helperText?: React.ReactElement<HelperTextProps>; characterCounter?: React.ReactElement<CharacterCounterProps>; label?: React.ReactNode; leadingIcon?: React.ReactElement<React.HTMLProps<HTMLOrSVGElement>>; lineRippleClassName?: string; notchedOutlineClassName?: string; outlined?: boolean; onLeadingIconSelect?: () => void; onTrailingIconSelect?: () => void; textarea?: boolean; trailingIcon?: React.ReactElement<React.HTMLProps<HTMLOrSVGElement>>; noLabel?: boolean; } type TextFieldProps<T extends HTMLElement = HTMLInputElement> = Props<T> & React.HTMLProps<HTMLDivElement>; interface TextFieldState { foundation?: MDCTextFieldFoundation; classList: Set<string>; inputId: string; isFocused: boolean; dir: string; disabled: boolean; labelIsFloated: boolean; initialLabelWidth: number; notchedLabelWidth: number; activeLineRipple: boolean; lineRippleCenter: number; outlineIsNotched: boolean; isValid: boolean; } class TextField< T extends HTMLElement = HTMLInputElement > extends React.Component<TextFieldProps<T>, TextFieldState> { textFieldElement: React.RefObject<HTMLDivElement> = React.createRef(); floatingLabelElement: React.RefObject<FloatingLabel> = React.createRef(); inputComponent_: null | Input<T> = null; static defaultProps = { className: '', dense: false, floatingLabelClassName: '', fullWidth: false, lineRippleClassName: '', notchedOutlineClassName: '', outlined: false, textarea: false, noLabel: false, }; constructor(props: TextFieldProps<T>) { super(props); let inputId; if (props.children && React.Children.only(props.children)) { inputId = props.children.props.id; } this.state = { // root state classList: new Set(), inputId, isFocused: false, dir: 'ltr', disabled: false, // floating label state labelIsFloated: false, initialLabelWidth: 0, notchedLabelWidth: 0, // line ripple state activeLineRipple: false, lineRippleCenter: 0, // notched outline state outlineIsNotched: false, // helper text state isValid: true, // foundation is on state, // so that the Input renders after this component foundation: undefined, }; } componentDidMount() { const foundation = new MDCTextFieldFoundation(this.adapter); this.setState({foundation}); foundation.init(); } componentWillUnmount() { this.state.foundation && this.state.foundation.destroy(); } /** * getters */ get classes() { const {classList, disabled, isFocused, isValid} = this.state; const { className, dense, fullWidth, textarea, trailingIcon, leadingIcon, noLabel, } = this.props; return classnames(cssClasses.ROOT, Array.from(classList), className, { [cssClasses.DENSE]: dense, [cssClasses.DISABLED]: disabled, [cssClasses.FOCUSED]: isFocused, [cssClasses.INVALID]: !isValid, [cssClasses.OUTLINED]: this.notchedOutlineAdapter.hasOutline() && !fullWidth, [cssClasses.TEXTAREA]: textarea, [cssClasses.WITH_LEADING_ICON]: leadingIcon, // TODO change literal to constant 'mdc-text-field--fullwidth': fullWidth, 'mdc-text-field--with-trailing-icon': trailingIcon, 'mdc-text-field--no-label': !this.labelAdapter.hasLabel() || noLabel, }); } get otherProps() { const { /* eslint-disable @typescript-eslint/no-unused-vars */ children, className, dense, floatingLabelClassName, fullWidth, helperText, characterCounter, label, leadingIcon, lineRippleClassName, notchedOutlineClassName, onLeadingIconSelect, onTrailingIconSelect, outlined, textarea, trailingIcon, noLabel, /* eslint-enable @typescript-eslint/no-unused-vars */ ...otherProps } = this.props; return otherProps; } get adapter(): MDCTextFieldAdapter { const rootAdapterMethods: MDCTextFieldRootAdapter = { addClass: (className: string) => this.setState({classList: this.state.classList.add(className)}), removeClass: (className: string) => { const {classList} = this.state; classList.delete(className); this.setState({classList}); }, hasClass: (className: string) => this.classes.split(' ').includes(className), // Please manage handler though JSX registerTextFieldInteractionHandler: () => undefined, deregisterTextFieldInteractionHandler: () => undefined, registerValidationAttributeChangeHandler: (): any => undefined, deregisterValidationAttributeChangeHandler: () => undefined, }; return Object.assign( {}, rootAdapterMethods, this.inputAdapter, this.labelAdapter, this.lineRippleAdapter, this.notchedOutlineAdapter ); } get inputAdapter(): MDCTextFieldInputAdapter { return { isFocused: () => this.state.isFocused, getNativeInput: () => { const component = this.inputComponent_; if (!component) { throw Error('MDCReactTextField: The input did not render properly'); } else { return { disabled: component.isDisabled(), value: component.getValue(), maxLength: component.getMaxLength(), type: component.getInputType(), validity: { badInput: !!component.isBadInput(), valid: !!component.isValid(), }, }; } }, // Please manage handler though JSX registerInputInteractionHandler: () => undefined, deregisterInputInteractionHandler: () => undefined, }; } get labelAdapter(): MDCTextFieldLabelAdapter { return { shakeLabel: (shakeLabel: boolean) => { const {floatingLabelElement: floatingLabel} = this; if (!shakeLabel) return; if (floatingLabel && floatingLabel.current) { floatingLabel.current.shake(); } }, floatLabel: (labelIsFloated: boolean) => this.setState({labelIsFloated}), hasLabel: () => !!this.props.label && !this.props.fullWidth, getLabelWidth: () => this.state.initialLabelWidth, }; } get lineRippleAdapter(): MDCTextFieldLineRippleAdapter { return { activateLineRipple: () => this.setState({activeLineRipple: true}), deactivateLineRipple: () => this.setState({activeLineRipple: false}), setLineRippleTransformOrigin: (lineRippleCenter: number) => this.setState({lineRippleCenter}), }; } get notchedOutlineAdapter(): MDCTextFieldOutlineAdapter { return { notchOutline: (notchedLabelWidth: number) => this.setState({outlineIsNotched: true, notchedLabelWidth}), closeOutline: () => this.setState({outlineIsNotched: false}), hasOutline: () => !!this.props.outlined || !!this.props.textarea, }; } get inputProps() { // ref does exist on React.ReactElement<InputProps<T>> // @ts-ignore const {props} = React.Children.only(this.props.children); return Object.assign({}, props, { foundation: this.state.foundation, handleFocusChange: (isFocused: boolean) => { this.setState({isFocused}); if (!this.state.foundation) return; if (isFocused) { this.state.foundation.activateFocus(); } else { this.state.foundation.deactivateFocus(); } }, setDisabled: (disabled: boolean) => this.setState({disabled}), setInputId: (id: string) => this.setState({inputId: id}), syncInput: (input: Input<T>) => (this.inputComponent_ = input), inputType: this.props.textarea ? 'textarea' : 'input', placeholder: this.props.noLabel ? this.props.label : null, }); } get characterCounterProps() { const {value, maxLength} = this.inputProps; return { count: value ? value.length : 0, maxLength: maxLength ? parseInt(maxLength) : 0, }; } /** * render methods */ render() { const { fullWidth, helperText, characterCounter, onLeadingIconSelect, onTrailingIconSelect, leadingIcon, trailingIcon, textarea, noLabel, } = this.props; const {foundation} = this.state; return ( <React.Fragment> <div {...this.otherProps} className={this.classes} onClick={() => foundation!.handleTextFieldInteraction()} onKeyDown={() => foundation!.handleTextFieldInteraction()} ref={this.textFieldElement} key='text-field-container' > {leadingIcon ? this.renderIcon(leadingIcon, onLeadingIconSelect) : null} {textarea && characterCounter && this.renderCharacterCounter(characterCounter)} {this.renderInput()} {this.notchedOutlineAdapter.hasOutline() ? ( this.renderNotchedOutline() ) : ( <React.Fragment> {this.labelAdapter.hasLabel() && !noLabel ? this.renderLabel() : null} {!textarea && !fullWidth ? this.renderLineRipple() : null} </React.Fragment> )} {trailingIcon ? this.renderIcon(trailingIcon, onTrailingIconSelect) : null} </div> {helperText || characterCounter ? this.renderHelperLine(helperText, characterCounter) : null} </React.Fragment> ); } renderInput() { const child = React.Children.only( this.props.children ) as React.ReactElement<InputProps<T>>; return React.cloneElement(child, this.inputProps); } renderLabel() { const {label, floatingLabelClassName} = this.props; const {inputId} = this.state; return ( <FloatingLabel className={floatingLabelClassName} float={this.state.labelIsFloated} handleWidthChange={(initialLabelWidth) => this.setState({initialLabelWidth}) } ref={this.floatingLabelElement} htmlFor={inputId} > {label} </FloatingLabel> ); } renderLineRipple() { const {lineRippleClassName} = this.props; const {activeLineRipple, lineRippleCenter} = this.state; return ( <LineRipple rippleCenter={lineRippleCenter} className={lineRippleClassName} active={activeLineRipple} /> ); } renderNotchedOutline() { const {notchedOutlineClassName} = this.props; const {notchedLabelWidth, outlineIsNotched} = this.state; return ( <NotchedOutline className={notchedOutlineClassName} notchWidth={notchedLabelWidth} notch={outlineIsNotched} > {this.labelAdapter.hasLabel() ? this.renderLabel() : null} </NotchedOutline> ); } renderHelperLine( helperText?: React.ReactElement<HelperTextProps>, characterCounter?: React.ReactElement<CharacterCounterProps> ) { return ( <div className={cssClasses.HELPER_LINE}> {helperText && this.renderHelperText(helperText)} {characterCounter && !this.props.textarea && this.renderCharacterCounter(characterCounter)} </div> ); } renderHelperText(helperText: React.ReactElement<HelperTextProps>) { const {isValid} = this.state; const props = Object.assign( { isValid, key: 'text-field-helper-text', }, helperText.props ); return React.cloneElement(helperText, props); } renderIcon( icon: React.ReactElement<React.HTMLProps<HTMLOrSVGElement>>, onSelect?: () => void ) { const {disabled} = this.state; // Toggling disabled will trigger icon.foundation.setDisabled() return ( <Icon disabled={disabled} onSelect={onSelect}> {icon} </Icon> ); } renderCharacterCounter( characterCounter: React.ReactElement<CharacterCounterProps> ) { return React.cloneElement( characterCounter, Object.assign(this.characterCounterProps, characterCounter.props) ); } } export { Icon, HelperText, CharacterCounter, Input, IconProps, HelperTextProps, CharacterCounterProps, InputProps, }; export default TextField;
the_stack
import expressions = require('../src/expression'); import Json = require('source-processor'); function translationTestCase(from:string, to:string, functions: expressions.Functions, test:nodeunit.Test){ var expr = expressions.Expression.parse(from); var symbols:expressions.Symbols = new expressions.Symbols(); symbols.functions = functions; var translation = expr.generate(symbols); test.equal(translation, to); } export function testArrayLookup1(test:nodeunit.Test):void{ translationTestCase( "next['c1'].val()", "newData.child('c1').val()", new expressions.Functions(), test ); test.done(); } export function testArrayLookup2(test:nodeunit.Test):void{ translationTestCase( "next.c1.val()", "newData.child('c1').val()", new expressions.Functions(), test ); test.done(); } export function testArrayLookup3(test:nodeunit.Test):void{ translationTestCase( "next[prev.val()].val()", "newData.child(data.val()).val()", new expressions.Functions(), test ); test.done(); } export function testArrayLookup4(test:nodeunit.Test):void{ translationTestCase( "next[prev].val()", "newData.child(data.val()).val()", new expressions.Functions(), test ); test.done(); } export function testArrayLookup5(test:nodeunit.Test):void{ translationTestCase( "next[prev.child].val()", "newData.child(data.child('child').val()).val()", new expressions.Functions(), test ); test.done(); } export function testArrayLookup6(test:nodeunit.Test):void{ translationTestCase( "next[prev[child]].val()", "newData.child(data.child('child').val()).val()", new expressions.Functions(), test ); test.done(); } export function testArrayLookup7(test:nodeunit.Test):void{ translationTestCase( "next[prev[child]]['fred'].val()", "newData.child(data.child('child').val()).child('fred').val()", new expressions.Functions(), test ); test.done(); } export function testParent1(test:nodeunit.Test):void{ translationTestCase( "next.parent()", "newData.parent()", new expressions.Functions(), test ); test.done(); } export function testParent2(test:nodeunit.Test):void{ translationTestCase( "next[prev.parent().val()]['blah'].c1.val()", "newData.child(data.parent().val()).child('blah').child('c1').val()", new expressions.Functions(), test ); test.done(); } export function testHasChildren(test:nodeunit.Test):void{ translationTestCase( "next.c1.hasChildren(['eric'])", "newData.child('c1').hasChildren(['eric'])", new expressions.Functions(), test ); test.done(); } export function testContains1(test:nodeunit.Test):void{ translationTestCase( "next.c1.val().contains('yo')", "newData.child('c1').val().contains('yo')", new expressions.Functions(), test ); test.done(); } export function testContains2(test:nodeunit.Test):void{ translationTestCase( "'yo'.contains('yo')", "'yo'.contains('yo')", new expressions.Functions(), test ); test.done(); } export function testContains3(test:nodeunit.Test):void{ translationTestCase( "'yo'.contains(prev.val())", "'yo'.contains(data.val())", new expressions.Functions(), test ); test.done(); } export function testAuth1(test:nodeunit.Test):void{ translationTestCase( "auth.id", "auth.id", new expressions.Functions(), test ); test.done(); } export function testAuth2(test:nodeunit.Test):void{ translationTestCase( "root.users[auth.id]", "root.child('users').child(auth.id)", new expressions.Functions(), test ); test.done(); } export function testCoercion1(test:nodeunit.Test):void{ translationTestCase( "root.superuser == auth.id", "root.child('superuser').val()==auth.id", new expressions.Functions(), test ); test.done(); } export function testCoercion2(test:nodeunit.Test):void{ translationTestCase( "auth.id == root[next]", "auth.id==root.child(newData.val()).val()", new expressions.Functions(), test ); test.done(); } export function test$var1(test:nodeunit.Test):void{ translationTestCase( "auth.id == $userid", "auth.id==$userid", new expressions.Functions(), test ); test.done(); } export function test$var3(test:nodeunit.Test):void{ translationTestCase( "prev[$userid].val()", "data.child($userid).val()", new expressions.Functions(), test ); test.done(); } export function test$var4(test:nodeunit.Test):void{ translationTestCase( "prev.$userid.val()", "data.child($userid).val()", new expressions.Functions(), test ); test.done(); } export function testNow(test:nodeunit.Test):void{ translationTestCase( "next < now", "newData.val()<now", new expressions.Functions(), test ); test.done(); } export function testRoot(test:nodeunit.Test):void{ translationTestCase( "root.users[auth.id].active == true", "root.child('users').child(auth.id).child('active').val()==true", new expressions.Functions(), test ); test.done(); } export function testHasChild(test:nodeunit.Test):void{ translationTestCase( "next.hasChild('name')", "newData.hasChild('name')", new expressions.Functions(), test ); test.done(); } export function testHasChildren1(test:nodeunit.Test):void{ translationTestCase( "next.hasChildren()", "newData.hasChildren()", new expressions.Functions(), test ); test.done(); } export function testHasChildren2(test:nodeunit.Test):void{ translationTestCase( "next.hasChildren(['name', 'age'])", "newData.hasChildren(['name', 'age'])", new expressions.Functions(), test ); test.done(); } export function testGetPriority(test:nodeunit.Test):void{ translationTestCase( "next.getPriority() != null", "newData.getPriority()!=null", new expressions.Functions(), test ); test.done(); } export function testLength(test:nodeunit.Test):void{ translationTestCase( "next.isString()&&next.val().length>=10", "newData.isString()&&newData.val().length>=10", new expressions.Functions(), test ); test.done(); } export function testBeginsWith(test:nodeunit.Test):void{ translationTestCase( "auth.identifier.beginsWith('internal-')", "auth.identifier.beginsWith('internal-')", new expressions.Functions(), test ); test.done(); } export function testEndsWith(test:nodeunit.Test):void{ translationTestCase( "next.val().endsWith('internal-')", "newData.val().endsWith('internal-')", new expressions.Functions(), test ); test.done(); } export function testReplace(test:nodeunit.Test):void{ translationTestCase( "root.users[auth.email.replace('.', ',')].exists()", "root.child('users').child(auth.email.replace('.', ',')).exists()", new expressions.Functions(), test ); test.done(); } export function testToLowerCase(test:nodeunit.Test):void{ translationTestCase( "root.users[auth.identifier.toLowerCase()].exists()", "root.child('users').child(auth.identifier.toLowerCase()).exists()", new expressions.Functions(), test ); test.done(); } export function testToUpperCase(test:nodeunit.Test):void{ translationTestCase( "root.users[auth.identifier.toUpperCase()].exists()", "root.child('users').child(auth.identifier.toUpperCase()).exists()", new expressions.Functions(), test ); test.done(); } export function testRegex1(test:nodeunit.Test):void{ translationTestCase( "/regex/", "/regex/", new expressions.Functions(), test ); test.done(); } export function testRegex2(test:nodeunit.Test):void{ translationTestCase( "/\\d/", "/\\d/", new expressions.Functions(), test ); test.done(); } export function testRegex3(test:nodeunit.Test):void{ translationTestCase( "/\\\\d/", "/\\\\d/", new expressions.Functions(), test ); test.done(); } export function testRegex4(test:nodeunit.Test):void{ translationTestCase( "root.val().matches(/regex/)", "root.val().matches(/regex/)", //this second version needs to be safe inside a "" new expressions.Functions(), test ); test.done(); } function Function(dec: string, expr: string): expressions.Function { return new expressions.Function(dec, new Json.JString(expr, 0, 0)) } export function testFunctionParsing1(test){ var predicate = Function("f(x)", "true"); test.ok(predicate.signature == "f(1)"); test.done(); } export function testFunctionParsing2(test){ var predicate = Function("f()", "true"); test.ok(predicate.signature == "f(0)"); test.done(); } export function testFunctionParsing3(test){ var predicate = Function("f(x, y)", "true"); test.equals(predicate.signature, "f(2)"); test.deepEqual(predicate.parameter_map, ['x', 'y']); test.done(); } export function testFunction1(test:nodeunit.Test):void { translationTestCase( "isLoggedIn()", "(auth.id==null)", expressions.Functions.parse( Json.parse('[{"isLoggedIn()":"auth.id == null"}]') ), test ); test.done(); } export function testFunction2(test:nodeunit.Test):void { translationTestCase( "isEqual(prev, next.name)", "(data.val()==newData.child('name').val())", expressions.Functions.parse( Json.parse('[{"isEqual(a, b)":"a == b"}]') ), test ); test.done(); } export function testFunction3(test:nodeunit.Test):void { translationTestCase( "isLoggedIn(auth)", "(auth.id=='yo')", expressions.Functions.parse( Json.parse('[{"isLoggedIn(q)":"q.id == \'yo\'"}]') ), test ); test.done(); } export function testUnary(test:nodeunit.Test):void { translationTestCase( "!isLoggedIn(auth)", "!(auth.id=='yo')", expressions.Functions.parse( Json.parse('[{"isLoggedIn(q)":"q.id == \'yo\'"}]') ), test ); test.done(); } export function testSanitizeQuotes1(test:nodeunit.Test):void { translationTestCase( "\"string\"=='string'", "\"string\"=='string'", new expressions.Functions(), test ); test.done(); } export function testSanitizeQuotes2(test:nodeunit.Test):void { translationTestCase( "next['string'] == prev[\"string\"]", 'newData.child(\'string\').val()==data.child("string").val()', new expressions.Functions(), test ); test.done(); } export function testRewriteForChild(test:nodeunit.Test):void { var expr = expressions.Expression.parse("true"); var rewrite = expr.rewriteForChild().toString(); test.equals(rewrite, "true"); var expr2 = expressions.Expression.parse(rewrite); var rewrite2 = expr2.rewriteForChild(); test.equals(rewrite2, "true"); test.done(); } //testRewriteForChild(<nodeunit.Test>{equals: function(){}});
the_stack
import BigNumber from 'bignumber.js'; import { isAddress } from '@parity/abi/lib/util/address'; import { isInstanceOf } from '@parity/abi/lib/util/types'; import { Block, Receipt } from '../types'; import { outBlock, outAccountInfo, outAddress, outChainStatus, outDate, outHistogram, outHwAccountInfo, outNodeKind, outNumber, outPeer, outPeers, outReceipt, outSyncing, outTransaction, outTrace, outVaultMeta } from './output'; import { SerializedBlock, SerializedReceipt, SerializedTransaction } from './types.serialized'; describe('format/output', () => { const address = '0x63cf90d3f0410092fc0fca41846f596223979195'; const checksum = '0x63Cf90D3f0410092FC0fca41846f596223979195'; describe('outAccountInfo', () => { it('returns meta objects parsed', () => { expect( outAccountInfo({ '0x63cf90d3f0410092fc0fca41846f596223979195': { name: 'name', uuid: 'uuid', meta: '{"name":"456"}' } }) ).toEqual({ '0x63Cf90D3f0410092FC0fca41846f596223979195': { name: 'name', uuid: 'uuid', meta: { name: '456' } } }); }); it('returns objects without meta & uuid as required', () => { expect( outAccountInfo({ '0x63cf90d3f0410092fc0fca41846f596223979195': { name: 'name' } }) ).toEqual({ '0x63Cf90D3f0410092FC0fca41846f596223979195': { name: 'name' } }); }); }); describe('outAddress', () => { it('retuns the address as checksummed', () => { expect(outAddress(address)).toEqual(checksum); }); it('retuns the checksum as checksummed', () => { expect(outAddress(checksum)).toEqual(checksum); }); }); describe('outBlock', () => { ['author', 'miner'].forEach(input => { it(`formats ${input} address as address`, () => { const block: SerializedBlock = {}; block[input as keyof SerializedBlock] = address; const formatted = outBlock(block)[input as keyof Block]; expect(isAddress(formatted as string)).toBe(true); expect(formatted).toEqual(checksum); }); }); [ 'difficulty', 'gasLimit', 'gasUsed', 'number', 'nonce', 'totalDifficulty' ].forEach(input => { it(`formats ${input} number as hexnumber`, () => { const block: SerializedBlock = {}; // @ts-ignore block[input as keyof SerializedBlock] = 0x123; const formatted = outBlock(block)[input as keyof Block]; expect(isInstanceOf(formatted, BigNumber)).toBe(true); // @ts-ignore expect(formatted.toString(16)).toEqual('123'); }); }); ['timestamp'].forEach(input => { it(`formats ${input} number as Date`, () => { const block: SerializedBlock = {}; // @ts-ignore block[input as keyof SerializedBlock] = 0x57513668; const formatted = outBlock(block)[input as keyof Block]; expect(isInstanceOf(formatted, Date)).toBe(true); expect((formatted as Date).getTime()).toEqual(1464940136000); }); }); it('ignores and passes through unknown keys', () => { expect(outBlock({ someRandom: 'someRandom' } as any)).toEqual({ someRandom: 'someRandom' }); }); it('formats a block with all the info converted', () => { expect( outBlock({ author: address, miner: address, difficulty: '0x100', gasLimit: '0x101', gasUsed: '0x102', number: '0x103', nonce: '0x104', totalDifficulty: '0x105', timestamp: '0x57513668', extraData: 'someExtraStuffInHere' }) ).toEqual({ author: checksum, miner: checksum, difficulty: new BigNumber('0x100'), gasLimit: new BigNumber('0x101'), gasUsed: new BigNumber('0x102'), number: new BigNumber('0x103'), nonce: new BigNumber('0x104'), totalDifficulty: new BigNumber('0x105'), timestamp: new Date('2016-06-03T07:48:56.000Z'), extraData: 'someExtraStuffInHere' }); }); }); describe('outChainStatus', () => { it('formats blockGap values', () => { const status = { blockGap: [0x1234, '0x5678'] }; expect(outChainStatus(status)).toEqual({ blockGap: [new BigNumber(0x1234), new BigNumber(0x5678)] }); }); it('handles null blockGap values', () => { const status = { blockGap: undefined }; expect(outChainStatus(status)).toEqual(status); }); }); describe('outDate', () => { it('converts a second date in unix timestamp', () => { expect(outDate(0x57513668)).toEqual(new Date('2016-06-03T07:48:56.000Z')); }); }); describe('outHistogram', () => { ['bucketBounds', 'counts'].forEach(type => { it(`formats ${type} as number arrays`, () => { expect(outHistogram({ [type]: [0x123, 0x456, 0x789] })).toEqual({ [type]: [ new BigNumber(0x123), new BigNumber(0x456), new BigNumber(0x789) ] }); }); }); }); describe('outHwAccountInfo', () => { it('returns objects with formatted addresses', () => { expect( outHwAccountInfo({ '0x63cf90d3f0410092fc0fca41846f596223979195': { manufacturer: 'mfg', name: 'type' } }) ).toEqual({ '0x63Cf90D3f0410092FC0fca41846f596223979195': { manufacturer: 'mfg', name: 'type' } }); }); }); describe('outNodeKind', () => { it('formats the input as received', () => { const kind = { availability: 'personal', capability: 'full' }; expect(outNodeKind(kind)).toEqual(kind); }); }); describe('outNumber', () => { it('returns a BigNumber equalling the value', () => { const bn = outNumber('0x123456'); expect(isInstanceOf(bn, BigNumber)).toBe(true); expect(bn.eq(0x123456)).toBe(true); }); it('assumes 0 when ivalid input', () => { expect(outNumber().eq(0)).toBe(true); }); }); describe('outPeer', () => { it('converts all internal numbers to BigNumbers', () => { expect( outPeer({ caps: ['par/1'], id: '0x01', name: 'Parity', network: { localAddress: '10.0.0.1', remoteAddress: '10.0.0.1' }, protocols: { par: { difficulty: '0x0f', head: '0x02', version: 63 } } }) ).toEqual({ caps: ['par/1'], id: '0x01', name: 'Parity', network: { localAddress: '10.0.0.1', remoteAddress: '10.0.0.1' }, protocols: { par: { difficulty: new BigNumber(15), head: '0x02', version: 63 } } }); }); it('does not output null protocols', () => { expect( outPeer({ caps: ['par/1'], id: '0x01', name: 'Parity', network: { localAddress: '10.0.0.1', remoteAddress: '10.0.0.1' }, protocols: { les: null } }) ).toEqual({ caps: ['par/1'], id: '0x01', name: 'Parity', network: { localAddress: '10.0.0.1', remoteAddress: '10.0.0.1' }, protocols: {} }); }); }); describe('outPeers', () => { it('converts all internal numbers to BigNumbers', () => { expect( outPeers({ active: 789, connected: '456', max: 0x7b, peers: [ { caps: ['par/1'], id: '0x01', name: 'Parity', network: { localAddress: '10.0.0.1', remoteAddress: '10.0.0.1' }, protocols: { par: { difficulty: '0x0f', head: '0x02', version: 63 }, les: null } } ] }) ).toEqual({ active: new BigNumber(789), connected: new BigNumber(456), max: new BigNumber(123), peers: [ { caps: ['par/1'], id: '0x01', name: 'Parity', network: { localAddress: '10.0.0.1', remoteAddress: '10.0.0.1' }, protocols: { par: { difficulty: new BigNumber(15), head: '0x02', version: 63 } } } ] }); }); }); describe('outReceipt', () => { ['contractAddress'].forEach(input => { it(`formats ${input} address as address`, () => { const block: SerializedReceipt = {}; block[input as keyof SerializedReceipt] = address; const formatted = outReceipt(block)[input as keyof Receipt]; expect(isAddress(formatted as string)).toBe(true); expect(formatted).toEqual(checksum); }); }); [ 'blockNumber', 'cumulativeGasUsed', 'cumulativeGasUsed', 'gasUsed', 'transactionIndex' ].forEach(input => { it(`formats ${input} number as hexnumber`, () => { const block: SerializedReceipt = {}; // @ts-ignore block[input as keyof SerializedReceipt] = 0x123; const formatted = outReceipt(block)[input as keyof Receipt]; expect(isInstanceOf(formatted, BigNumber)).toBe(true); // @ts-ignore expect(formatted.toString(16)).toEqual('123'); }); }); it('ignores and passes through unknown keys', () => { // @ts-ignore expect(outReceipt({ someRandom: 'someRandom' })).toEqual({ someRandom: 'someRandom' }); }); it('formats a receipt with all the info converted', () => { expect( outReceipt({ contractAddress: address, blockNumber: '0x100', cumulativeGasUsed: '0x101', gasUsed: '0x102', transactionIndex: '0x103', extraData: 'someExtraStuffInHere' }) ).toEqual({ contractAddress: checksum, blockNumber: new BigNumber('0x100'), cumulativeGasUsed: new BigNumber('0x101'), gasUsed: new BigNumber('0x102'), transactionIndex: new BigNumber('0x103'), extraData: 'someExtraStuffInHere' }); }); }); describe('outSyncing', () => { [ 'currentBlock', 'highestBlock', 'startingBlock', 'warpChunksAmount', 'warpChunksProcessed' ].forEach(input => { it(`formats ${input} numbers as a number`, () => { expect(outSyncing({ [input]: '0x123' })).toEqual({ [input]: new BigNumber('0x123') }); }); }); it('formats blockGap properly', () => { expect(outSyncing({ blockGap: [0x123, 0x456] })).toEqual({ blockGap: [new BigNumber(0x123), new BigNumber(0x456)] }); }); }); describe('outTransaction', () => { ['from', 'to'].forEach(input => { it(`formats ${input} address as address`, () => { const block: SerializedTransaction = {}; block[input as keyof SerializedTransaction] = address; const formatted = outTransaction(block)[ input as keyof SerializedTransaction ]; expect(isAddress(formatted as string)).toBe(true); expect(formatted).toEqual(checksum); }); }); [ 'blockNumber', 'gasPrice', 'gas', 'nonce', 'transactionIndex', 'value' ].forEach(input => { it(`formats ${input} number as hexnumber`, () => { const block: SerializedTransaction = {}; // @ts-ignore block[input as keyof SerializedTransaction] = 0x123; const formatted = outTransaction(block)[ input as keyof SerializedTransaction ]; expect(isInstanceOf(formatted, BigNumber)).toBe(true); // @ts-ignore expect(formatted.toString(16)).toEqual('123'); }); }); it('passes condition as null when null', () => { expect(outTransaction({ condition: null })).toEqual({ condition: null }); }); it('ignores and passes through unknown keys', () => { // @ts-ignore expect(outTransaction({ someRandom: 'someRandom' })).toEqual({ someRandom: 'someRandom' }); }); it('formats a transaction with all the info converted', () => { expect( outTransaction({ from: address, to: address, blockNumber: '0x100', gasPrice: '0x101', gas: '0x102', nonce: '0x103', transactionIndex: '0x104', value: '0x105', extraData: 'someExtraStuffInHere' }) ).toEqual({ from: checksum, to: checksum, blockNumber: new BigNumber('0x100'), gasPrice: new BigNumber('0x101'), gas: new BigNumber('0x102'), nonce: new BigNumber('0x103'), transactionIndex: new BigNumber('0x104'), value: new BigNumber('0x105'), extraData: 'someExtraStuffInHere' }); }); }); describe('outTrace', () => { it('ignores and passes through unknown keys', () => { // @ts-ignore expect(outTrace({ someRandom: 'someRandom' })).toEqual({ someRandom: 'someRandom' }); }); it('formats a trace with all the info converted', () => { const formatted = outTrace({ type: 'call', action: { from: address, to: address, value: '0x06', gas: '0x07', input: '0x1234', callType: 'call' }, result: { gasUsed: '0x08', output: '0x5678' }, traceAddress: ['0x2'], subtraces: 3, transactionPosition: '0xb', transactionHash: '0x000000000000000000000000000000000000000000000000000000000000000c', blockNumber: '0x0d', blockHash: '0x000000000000000000000000000000000000000000000000000000000000000e' }); // @ts-ignore expect(isInstanceOf(formatted.action.gas, BigNumber)).toBe(true); // @ts-ignore expect(formatted.action.gas.toNumber()).toEqual(7); // @ts-ignore expect(isInstanceOf(formatted.action.value, BigNumber)).toBe(true); // @ts-ignore expect(formatted.action.value.toNumber()).toEqual(6); // @ts-ignore expect(formatted.action.from).toEqual(checksum); // @ts-ignore expect(formatted.action.to).toEqual(checksum); // @ts-ignore expect(isInstanceOf(formatted.blockNumber, BigNumber)).toBe(true); // @ts-ignore expect(formatted.blockNumber.toNumber()).toEqual(13); // @ts-ignore expect(isInstanceOf(formatted.transactionPosition, BigNumber)).toBe(true); // @ts-ignore expect(formatted.transactionPosition.toNumber()).toEqual(11); }); }); describe('outVaultMeta', () => { it('returns an exmpt object on null', () => { expect(outVaultMeta(null)).toEqual({}); }); it('returns the original value if not string', () => { expect(outVaultMeta({ test: 123 })).toEqual({ test: 123 }); }); it('returns an object from JSON string', () => { expect(outVaultMeta('{"test":123}')).toEqual({ test: 123 }); }); it('returns an empty object on invalid JSON', () => { expect(outVaultMeta('{"test"}')).toEqual({}); }); }); });
the_stack
import { BN } from 'ethereumjs-util'; import { mocked } from 'ts-jest/utils'; import { when } from 'jest-when'; import { query, fromHex, toHex } from '../util'; import fetchBlockFeeHistory from './fetchBlockFeeHistory'; jest.mock('../util', () => { return { ...jest.requireActual('../util'), __esModule: true, query: jest.fn(), }; }); const mockedQuery = mocked(query, true); /** * Calls the given function the given number of times, collecting the results from each call. * * @param n - The number of times you want to call the function. * @param fn - The function to call. * @returns An array of values gleaned from the results of each call to the function. */ function times<T>(n: number, fn: (n: number) => T): T[] { const values = []; for (let i = 0; i < n; i++) { values.push(fn(i)); } return values; } describe('fetchBlockFeeHistory', () => { const ethQuery = { eth: 'query' }; describe('with a minimal set of arguments', () => { const latestBlockNumber = 3; const numberOfRequestedBlocks = 3; beforeEach(() => { when(mockedQuery) .calledWith(ethQuery, 'blockNumber') .mockResolvedValue(new BN(latestBlockNumber)); }); it('should return a representation of fee history from the Ethereum network, organized by block rather than type of data', async () => { when(mockedQuery) .calledWith(ethQuery, 'eth_feeHistory', [ toHex(numberOfRequestedBlocks), toHex(latestBlockNumber), [], ]) .mockResolvedValue({ oldestBlock: toHex(1), // Note that this array contains 4 items when the request was made for 3. Per // <https://github.com/ethereum/go-ethereum/blob/57a3fab8a75eeb9c2f4fab770b73b51b9fe672c5/eth/gasprice/feehistory.go#L191-L192>, // baseFeePerGas will always include an extra item which is the calculated base fee for the // next (future) block. baseFeePerGas: [ toHex(10_000_000_000), toHex(20_000_000_000), toHex(30_000_000_000), toHex(40_000_000_000), ], gasUsedRatio: [0.1, 0.2, 0.3], }); const feeHistory = await fetchBlockFeeHistory({ ethQuery, numberOfBlocks: numberOfRequestedBlocks, }); expect(feeHistory).toStrictEqual([ { number: new BN(1), baseFeePerGas: new BN(10_000_000_000), gasUsedRatio: 0.1, priorityFeesByPercentile: {}, }, { number: new BN(2), baseFeePerGas: new BN(20_000_000_000), gasUsedRatio: 0.2, priorityFeesByPercentile: {}, }, { number: new BN(3), baseFeePerGas: new BN(30_000_000_000), gasUsedRatio: 0.3, priorityFeesByPercentile: {}, }, ]); }); it('should be able to handle an "empty" response from eth_feeHistory', async () => { when(mockedQuery) .calledWith(ethQuery, 'eth_feeHistory', [ toHex(numberOfRequestedBlocks), toHex(latestBlockNumber), [], ]) .mockResolvedValue({ oldestBlock: toHex(0), baseFeePerGas: [], gasUsedRatio: [], }); const feeHistory = await fetchBlockFeeHistory({ ethQuery, numberOfBlocks: numberOfRequestedBlocks, }); expect(feeHistory).toStrictEqual([]); }); }); describe('given a numberOfBlocks that exceeds the max limit that the EVM returns', () => { it('divides the number into chunks and calls eth_feeHistory for each chunk', async () => { const latestBlockNumber = 2348; const numberOfRequestedBlocks = 2348; const expectedChunks = [ { startBlockNumber: 1, endBlockNumber: 1024 }, { startBlockNumber: 1025, endBlockNumber: 2048 }, { startBlockNumber: 2049, endBlockNumber: 2348 }, ]; const expectedBlocks = times(numberOfRequestedBlocks, (i) => { return { number: i + 1, baseFeePerGas: toHex(1_000_000_000 * (i + 1)), gasUsedRatio: (i + 1) / numberOfRequestedBlocks, }; }); when(mockedQuery) .calledWith(ethQuery, 'blockNumber') .mockResolvedValue(new BN(latestBlockNumber)); expectedChunks.forEach(({ startBlockNumber, endBlockNumber }) => { const baseFeePerGas = expectedBlocks .slice(startBlockNumber - 1, endBlockNumber + 1) .map((block) => block.baseFeePerGas); const gasUsedRatio = expectedBlocks .slice(startBlockNumber - 1, endBlockNumber) .map((block) => block.gasUsedRatio); when(mockedQuery) .calledWith(ethQuery, 'eth_feeHistory', [ toHex(endBlockNumber - startBlockNumber + 1), toHex(endBlockNumber), [], ]) .mockResolvedValue({ oldestBlock: toHex(startBlockNumber), baseFeePerGas, gasUsedRatio, }); }); const feeHistory = await fetchBlockFeeHistory({ ethQuery, numberOfBlocks: numberOfRequestedBlocks, }); expect(feeHistory).toStrictEqual( expectedBlocks.map((block) => { return { number: new BN(block.number), baseFeePerGas: fromHex(block.baseFeePerGas), gasUsedRatio: block.gasUsedRatio, priorityFeesByPercentile: {}, }; }), ); }); }); describe('given an endBlock of a BN', () => { it('should pass it to the eth_feeHistory call', async () => { const latestBlockNumber = 3; const numberOfRequestedBlocks = 3; const endBlock = new BN(latestBlockNumber); when(mockedQuery) .calledWith(ethQuery, 'eth_feeHistory', [ toHex(numberOfRequestedBlocks), toHex(endBlock), [], ]) .mockResolvedValue({ oldestBlock: toHex(0), baseFeePerGas: [], gasUsedRatio: [], }); const feeHistory = await fetchBlockFeeHistory({ ethQuery, numberOfBlocks: numberOfRequestedBlocks, endBlock, }); expect(feeHistory).toStrictEqual([]); }); }); describe('given percentiles', () => { const latestBlockNumber = 3; const numberOfRequestedBlocks = 3; beforeEach(() => { when(mockedQuery) .calledWith(ethQuery, 'blockNumber') .mockResolvedValue(new BN(latestBlockNumber)); }); it('should match each item in the "reward" key from the response to its percentile', async () => { when(mockedQuery) .calledWith(ethQuery, 'eth_feeHistory', [ toHex(numberOfRequestedBlocks), toHex(latestBlockNumber), [10, 20, 30], ]) .mockResolvedValue({ oldestBlock: toHex(1), // Note that this array contains 4 items when the request was made for 3. Per // <https://github.com/ethereum/go-ethereum/blob/57a3fab8a75eeb9c2f4fab770b73b51b9fe672c5/eth/gasprice/feehistory.go#L191-L192>, // baseFeePerGas will always include an extra item which is the calculated base fee for the // next (future) block. baseFeePerGas: [ toHex(100_000_000_000), toHex(200_000_000_000), toHex(300_000_000_000), toHex(400_000_000_000), ], gasUsedRatio: [0.1, 0.2, 0.3], reward: [ [ toHex(10_000_000_000), toHex(15_000_000_000), toHex(20_000_000_000), ], [toHex(0), toHex(10_000_000_000), toHex(15_000_000_000)], [ toHex(20_000_000_000), toHex(20_000_000_000), toHex(30_000_000_000), ], ], }); const feeHistory = await fetchBlockFeeHistory({ ethQuery, numberOfBlocks: numberOfRequestedBlocks, percentiles: [10, 20, 30], }); expect(feeHistory).toStrictEqual([ { number: new BN(1), baseFeePerGas: new BN(100_000_000_000), gasUsedRatio: 0.1, priorityFeesByPercentile: { 10: new BN(10_000_000_000), 20: new BN(15_000_000_000), 30: new BN(20_000_000_000), }, }, { number: new BN(2), baseFeePerGas: new BN(200_000_000_000), gasUsedRatio: 0.2, priorityFeesByPercentile: { 10: new BN(0), 20: new BN(10_000_000_000), 30: new BN(15_000_000_000), }, }, { number: new BN(3), baseFeePerGas: new BN(300_000_000_000), gasUsedRatio: 0.3, priorityFeesByPercentile: { 10: new BN(20_000_000_000), 20: new BN(20_000_000_000), 30: new BN(30_000_000_000), }, }, ]); }); it('should be able to handle an "empty" response from eth_feeHistory including an empty "reward" array', async () => { when(mockedQuery) .calledWith(ethQuery, 'eth_feeHistory', [ toHex(numberOfRequestedBlocks), toHex(latestBlockNumber), [10, 20, 30], ]) .mockResolvedValue({ oldestBlock: toHex(0), baseFeePerGas: [], gasUsedRatio: [], reward: [], }); const feeHistory = await fetchBlockFeeHistory({ ethQuery, numberOfBlocks: numberOfRequestedBlocks, percentiles: [10, 20, 30], }); expect(feeHistory).toStrictEqual([]); }); }); describe('given includeNextBlock = true', () => { const latestBlockNumber = 3; const numberOfRequestedBlocks = 3; it('includes an extra block with an estimated baseFeePerGas', async () => { when(mockedQuery) .calledWith(ethQuery, 'eth_feeHistory', [ toHex(numberOfRequestedBlocks), toHex(latestBlockNumber), [], ]) .mockResolvedValue({ oldestBlock: toHex(1), // Note that this array contains 6 items when we requested 5. Per // <https://github.com/ethereum/go-ethereum/blob/57a3fab8a75eeb9c2f4fab770b73b51b9fe672c5/eth/gasprice/feehistory.go#L191-L192>, // baseFeePerGas will always include an extra item which is the calculated base fee for the // next (future) block. baseFeePerGas: [ toHex(10_000_000_000), toHex(20_000_000_000), toHex(30_000_000_000), toHex(40_000_000_000), ], gasUsedRatio: [0.1, 0.2, 0.3], }); const feeHistory = await fetchBlockFeeHistory({ ethQuery, numberOfBlocks: numberOfRequestedBlocks, includeNextBlock: true, }); expect(feeHistory).toStrictEqual([ { number: new BN(1), baseFeePerGas: new BN(10_000_000_000), gasUsedRatio: 0.1, priorityFeesByPercentile: {}, }, { number: new BN(2), baseFeePerGas: new BN(20_000_000_000), gasUsedRatio: 0.2, priorityFeesByPercentile: {}, }, { number: new BN(3), baseFeePerGas: new BN(30_000_000_000), gasUsedRatio: 0.3, priorityFeesByPercentile: {}, }, { number: new BN(4), baseFeePerGas: new BN(40_000_000_000), gasUsedRatio: null, priorityFeesByPercentile: null, }, ]); }); }); });
the_stack
import { default as Resolver, ComponentResolution, ComponentLocator } from './resolver'; import type { ASTv1 } from '@glimmer/syntax'; // This is the AST transform that resolves components and helpers at build time // and puts them into `dependencies`. export function makeResolverTransform(resolver: Resolver) { function resolverTransform({ filename }: { filename: string }) { resolver.enter(filename); let scopeStack = new ScopeStack(); return { name: 'embroider-build-time-resolver', visitor: { Program: { enter(node: ASTv1.Program) { scopeStack.push(node.blockParams); }, exit() { scopeStack.pop(); }, }, BlockStatement(node: ASTv1.BlockStatement) { if (node.path.type !== 'PathExpression') { return; } if (scopeStack.inScope(node.path.parts[0])) { return; } if (node.path.parts.length > 1) { // paths with a dot in them (which therefore split into more than // one "part") are classically understood by ember to be contextual // components, which means there's nothing to resolve at this // location. return; } if (node.path.original === 'component' && node.params.length > 0) { handleComponentHelper(node.params[0], resolver, filename, scopeStack); return; } // a block counts as args from our perpsective (it's enough to prove // this thing must be a component, not content) let hasArgs = true; const resolution = resolver.resolveMustache(node.path.original, hasArgs, filename, node.path.loc); if (resolution && resolution.type === 'component') { scopeStack.enteringComponentBlock(resolution, ({ argumentsAreComponents }) => { for (let name of argumentsAreComponents) { let pair = node.hash.pairs.find((pair: ASTv1.HashPair) => pair.key === name); if (pair) { handleComponentHelper(pair.value, resolver, filename, scopeStack, { componentName: (node.path as ASTv1.PathExpression).original, argumentName: name, }); } } }); } }, SubExpression(node: ASTv1.SubExpression) { if (node.path.type !== 'PathExpression') { return; } if (node.path.this === true) { return; } if (scopeStack.inScope(node.path.parts[0])) { return; } if (node.path.original === 'component' && node.params.length > 0) { handleComponentHelper(node.params[0], resolver, filename, scopeStack); return; } resolver.resolveSubExpression(node.path.original, filename, node.path.loc); }, MustacheStatement(node: ASTv1.MustacheStatement) { if (node.path.type !== 'PathExpression') { return; } if (scopeStack.inScope(node.path.parts[0])) { return; } if (node.path.parts.length > 1) { // paths with a dot in them (which therefore split into more than // one "part") are classically understood by ember to be contextual // components, which means there's nothing to resolve at this // location. return; } if (node.path.original === 'component' && node.params.length > 0) { handleComponentHelper(node.params[0], resolver, filename, scopeStack); return; } let hasArgs = node.params.length > 0 || node.hash.pairs.length > 0; let resolution = resolver.resolveMustache(node.path.original, hasArgs, filename, node.path.loc); if (resolution && resolution.type === 'component') { for (let name of resolution.argumentsAreComponents) { let pair = node.hash.pairs.find((pair: ASTv1.HashPair) => pair.key === name); if (pair) { handleComponentHelper(pair.value, resolver, filename, scopeStack, { componentName: node.path.original, argumentName: name, }); } } } }, ElementNode: { enter(node: ASTv1.ElementNode) { if (!scopeStack.inScope(node.tag.split('.')[0])) { const resolution = resolver.resolveElement(node.tag, filename, node.loc); if (resolution && resolution.type === 'component') { scopeStack.enteringComponentBlock(resolution, ({ argumentsAreComponents }) => { for (let name of argumentsAreComponents) { let attr = node.attributes.find((attr: ASTv1.AttrNode) => attr.name === '@' + name); if (attr) { handleComponentHelper(attr.value, resolver, filename, scopeStack, { componentName: node.tag, argumentName: name, }); } } }); } } scopeStack.push(node.blockParams); }, exit() { scopeStack.pop(); }, }, }, }; } resolverTransform.parallelBabel = { requireFile: __filename, buildUsing: 'makeResolverTransform', params: Resolver, }; return resolverTransform; } interface ComponentBlockMarker { type: 'componentBlockMarker'; resolution: ComponentResolution; argumentsAreComponents: string[]; exit: (marker: ComponentBlockMarker) => void; } type ScopeEntry = { type: 'blockParams'; blockParams: string[] } | ComponentBlockMarker; class ScopeStack { private stack: ScopeEntry[] = []; // as we enter a block, we push the block params onto here to mark them as // being in scope push(blockParams: string[]) { this.stack.unshift({ type: 'blockParams', blockParams }); } // and when we leave the block they go out of scope. If this block was tagged // by a safe component marker, we also clear that. pop() { this.stack.shift(); let next = this.stack[0]; if (next && next.type === 'componentBlockMarker') { next.exit(next); this.stack.shift(); } } // right before we enter a block, we might determine that some of the values // that will be yielded as marked (by a rule) as safe to be used with the // {{component}} helper. enteringComponentBlock(resolution: ComponentResolution, exit: ComponentBlockMarker['exit']) { this.stack.unshift({ type: 'componentBlockMarker', resolution, argumentsAreComponents: resolution.argumentsAreComponents.slice(), exit, }); } inScope(name: string) { for (let scope of this.stack) { if (scope.type === 'blockParams' && scope.blockParams.includes(name)) { return true; } } return false; } safeComponentInScope(name: string): boolean { let parts = name.split('.'); if (parts.length > 2) { // we let component rules specify that they yield components or objects // containing components. But not deeper than that. So the max path length // that can refer to a marked-safe component is two segments. return false; } for (let i = 0; i < this.stack.length - 1; i++) { let here = this.stack[i]; let next = this.stack[i + 1]; if (here.type === 'blockParams' && next.type === 'componentBlockMarker') { let positionalIndex = here.blockParams.indexOf(parts[0]); if (positionalIndex === -1) { continue; } if (parts.length === 1) { if (next.resolution.yieldsComponents[positionalIndex] === true) { return true; } let sourceArg = next.resolution.yieldsArguments[positionalIndex]; if (typeof sourceArg === 'string') { next.argumentsAreComponents.push(sourceArg); return true; } } else { let entry = next.resolution.yieldsComponents[positionalIndex]; if (entry && typeof entry === 'object') { return entry[parts[1]] === true; } let argsEntry = next.resolution.yieldsArguments[positionalIndex]; if (argsEntry && typeof argsEntry === 'object') { let sourceArg = argsEntry[parts[1]]; if (typeof sourceArg === 'string') { next.argumentsAreComponents.push(sourceArg); return true; } } } // we found the source of the name, but there were no rules to cover it. // Don't keep searching higher, those are different names. return false; } } return false; } } function handleComponentHelper( param: ASTv1.Node, resolver: Resolver, moduleName: string, scopeStack: ScopeStack, impliedBecause?: { componentName: string; argumentName: string } ): void { let locator: ComponentLocator; switch (param.type) { case 'StringLiteral': locator = { type: 'literal', path: param.value }; break; case 'PathExpression': locator = { type: 'path', path: param.original }; break; case 'MustacheStatement': if (param.hash.pairs.length === 0 && param.params.length === 0) { handleComponentHelper(param.path, resolver, moduleName, scopeStack, impliedBecause); return; } else if (param.path.type === 'PathExpression' && param.path.original === 'component') { // safe because we will handle this inner `{{component ...}}` mustache on its own return; } else { locator = { type: 'other' }; } break; case 'TextNode': locator = { type: 'literal', path: param.chars }; break; case 'SubExpression': if (param.path.type === 'PathExpression' && param.path.original === 'component') { // safe because we will handle this inner `(component ...)` subexpression on its own return; } if (param.path.type === 'PathExpression' && param.path.original === 'ensure-safe-component') { // safe because we trust ensure-safe-component return; } locator = { type: 'other' }; break; default: locator = { type: 'other' }; } if (locator.type === 'path' && scopeStack.safeComponentInScope(locator.path)) { return; } resolver.resolveComponentHelper(locator, moduleName, param.loc, impliedBecause); // if ( // param.type === 'MustacheStatement' && // param.hash.pairs.length === 0 && // param.params.length === 0 && // handleComponentHelper(param.path, resolver, moduleName, scopeStack) // ) { // return; // } // if ( // param.type === 'MustacheStatement' && // param.path.type === 'PathExpression' && // param.path.original === 'component' // ) { // // safe because we will handle this inner `{{component ...}}` mustache on its own // return; // } // if (param.type === 'TextNode') { // resolver.resolveComponentHelper({ type: 'literal', path: param.chars }, moduleName, param.loc); // return; // } // if (param.type === 'SubExpression' && param.path.type === 'PathExpression' && param.path.original === 'component') { // // safe because we will handle this inner `(component ...)` subexpression on its own // return; // } // resolver.unresolvableComponentArgument(componentName, argumentName, moduleName, param.loc); }
the_stack
import React, { FC, useState } from 'react'; import styles from './table.module.css'; export interface TableHeaderCell { label: string; key: string; sortable?: boolean; width?: string; // This is just a render prop allowing the consumer to put custom markup for the row cell // https://reactjs.org/docs/render-props.html#using-props-other-than-render renderFn?: (rowKey: string, rowValue: string) => React.ReactElement; /** * Custom sorting `compareFunction` which will take the values from the * two respective row cells being compared. * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description */ sortFn?: (cellLeft: any, cellRight: any) => -1 | 0 | 1; } /** * Header Cell Components * A th cell that only has a label like <th scope="col">foo</th> */ export interface HeaderCellProps { headerCell: TableHeaderCell; } export const HeaderCell: FC<HeaderCellProps> = ({ headerCell }) => ( <th scope="col" key={headerCell.key} style={headerCell.width ? { width: headerCell.width } : {}}> {headerCell.label} </th> ); /** * Sortable Header Cell Components * A th cell that has sorting enabled and thus a table sort button to sort * the rows by this column's key. */ export type Direction = 'ascending' | 'descending' | 'none'; export interface SortableHeaderCellProps extends HeaderCellProps { sortHandler: (key: string) => void; iconSortClasses: string; direction: Direction; } export const SortableHeaderCell: FC<SortableHeaderCellProps> = ({ headerCell, sortHandler, direction, iconSortClasses, }) => ( <th aria-sort={direction} scope="col" key={headerCell.key} style={headerCell.width ? { width: headerCell.width } : {}} > <div className={styles.tableHeaderContainer}> <span className={styles.tableSortLabel}>{headerCell.label}</span> <button type="button" className={styles.tableSort} onClick={() => sortHandler(headerCell.key)} > <span className="screenreader-only">{headerCell.label}</span> <span className={iconSortClasses} /> </button> </div> </th> ); /** * Main Table Component */ export interface TableProps { headers: TableHeaderCell[]; rows: any[]; tableSize?: '' | 'small' | 'large' | 'xlarge'; responsiveSize?: '' | 'small' | 'medium' | 'large' | 'xlarge'; captionPosition?: 'top' | 'bottom' | 'end' | 'hidden'; caption: string; isUppercasedHeaders?: boolean; isBordered?: boolean; isBorderless?: boolean; isStriped?: boolean; isHoverable?: boolean; isStacked?: boolean; } export const Table: FC<TableProps> = ({ headers, rows, caption, captionPosition = 'hidden', responsiveSize = '', tableSize = '', isUppercasedHeaders = false, isBordered = false, isBorderless = false, isStriped = false, isHoverable = false, isStacked = false, }) => { const [direction, setDirection] = useState<Direction>('none'); const [sortingKey, setSortingKey] = useState(''); /** * Plucks the columns from rows by key of the current sortingKey; sortingKey * reflects the currently being sorted column due to user interaction e.g. they * have clicked on that columns table header cell. * * Since we want to sort rows but by column comparisons, we need to "pluck out" * these columns from the two rows. If we cannot find the columns in rows by the * `sortingKey`, then we set these to `-Infinity` which places them at the bottom. * * @param rowLeft left row to compare * @param rowRight right row to compare * @returns Normalized columns from both rows in form of { a:a, b:b } */ const pluckColumnToSort = (rowLeft: any, rowRight: any) => { const colLeft = rowLeft[sortingKey] === null || rowLeft[sortingKey] === undefined ? -Infinity : rowLeft[sortingKey]; const colRight = rowRight[sortingKey] === null || rowRight[sortingKey] === undefined ? -Infinity : rowRight[sortingKey]; return { colLeft, colRight, }; }; /** * This function first checks if there is a corresponding custom sort function * that was supplied in a header cell with key" of `sortingKey` named `.sortFn` * per the API. If it finds, it will delegate to that for actual sort comparison. * Otherwise, the function supplies its own fallback default (naive) sorting logic. * @param rowLeft left row to compare * @param rowRight right row to compare * @returns Standard `Array.sort`'s `compareFunction` return of 0, -1, or 1 */ const internalSort = (rowLeft: any, rowRight: any) => { let { colLeft, colRight } = pluckColumnToSort(rowLeft, rowRight); /** * First check if the corresponding header cell has a custom sort * method. If so, we use that, else we proceed with our default one. */ const headerWithCustomSortFunction = headers.find( (h: TableHeaderCell) => h.key === sortingKey && !!h.sortFn, ); if (headerWithCustomSortFunction && headerWithCustomSortFunction.sortFn) { return headerWithCustomSortFunction.sortFn(colLeft, colRight); } // No custom sort method for the header cell, so we continue with our own. // Strings converted to lowercase; dollar currency etc. stripped (not yet i18n safe!) colLeft = typeof colLeft === 'string' ? colLeft.toLowerCase().replace(/(^\$|,)/g, '') : colLeft; colRight = typeof colRight === 'string' ? colRight.toLowerCase().replace(/(^\$|,)/g, '') : colRight; // If raw value represents a number explicitly set to Number colLeft = !Number.isNaN(Number(colLeft)) ? Number(colLeft) : colLeft; colRight = !Number.isNaN(Number(colRight)) ? Number(colRight) : colRight; if (colLeft > colRight) { return 1; } if (colLeft < colRight) { return -1; } return 0; }; // Simply flips the sign of results of the ascending sort const descendingSort = (r: any, r2: any) => internalSort(r, r2) * -1; /** * This memoized function is what actually sorts the array of items. It relies * on state updates, but just delegates to the other sorting routines. */ const sortedRows = React.useMemo(() => { const sortableItems = [...rows]; if (direction === 'ascending') { sortableItems.sort(internalSort); } else if (direction === 'descending') { sortableItems.sort(descendingSort); } // If direction was 'none' this will be the original unadultrated rows return sortableItems; }, [rows, sortingKey, direction]); /** * Updates sorting states: `direction` and `sortingKey` when a `SortableHeaderCell` clicked * @param headerKey the key of this header cell */ const handleSortClicked = (headerKey: string): void => { // Our last direction state starts as the "latest direction". But, we have to account // for when the user clicks an entirely different sort header from the last one. In // this case, we always want to start anew with direction set as 'none'. let latestDirection = direction; if (sortingKey !== headerKey) { latestDirection = 'none'; setSortingKey(headerKey); } switch (latestDirection) { case 'ascending': setDirection('descending'); break; case 'descending': setDirection('none'); break; case 'none': setDirection('ascending'); break; default: /* eslint-disable-next-line no-console */ console.warn('Table sorting only supports directions: ascending | descending | none'); } }; /** * Generates th header cell classes on `SortableHeaderCell`'s which are used to * display the appropriate sorting icons. * @param headerKey the key of this header cell * @returns CSS classes appropriate for the `SortableHeaderCell`'s current sorting state */ const getSortingClassesFor = (headerKey: string) => { // If it's the header currently being sorting on, add direction-based classes if (sortingKey === headerKey) { const directionCapitalized = direction ? `${direction.slice(0, 1).toUpperCase()}${direction.slice(1)}` : ''; return [ styles.iconSort, direction && direction !== 'none' ? styles[`iconSort${directionCapitalized}`] : '', ] .filter((c) => c.length) .join(' '); } // If not currently being sorted apply base class only return styles.iconSort; }; /** * CSS class generation routines */ const captionPositionCapitalized = captionPosition ? `${captionPosition.slice(0, 1).toUpperCase()}${captionPosition.slice(1)}` : ''; let captionClasses; if (captionPosition === 'hidden') { captionClasses = 'screenreader-only'; } else { captionClasses = styles[`caption${captionPositionCapitalized}`]; } const tableResponsiveSizeCapitalized = responsiveSize ? `${responsiveSize.slice(0, 1).toUpperCase()}${responsiveSize.slice(1)}` : ''; const tableResponsiveClasses = responsiveSize ? styles[`tableResponsive${tableResponsiveSizeCapitalized}`] : styles.tableResponsive; const tableSizeCapitalized = tableSize ? `${tableSize.slice(0, 1).toUpperCase()}${tableSize.slice(1)}` : ''; const tableClasses = [ styles.table, tableSize ? styles[`table${tableSizeCapitalized}`] : '', isUppercasedHeaders ? styles.tableCaps : '', isBordered ? styles.tableBordered : '', isBorderless ? styles.tableBorderless : '', isStriped ? styles.tableStriped : '', isHoverable ? styles.tableHoverable : '', isStacked ? styles.tableStacked : '', ] .filter((cl) => cl) .join(' '); return ( <div className={tableResponsiveClasses}> <table className={tableClasses}> <caption className={captionClasses}>{caption}</caption> <thead> <tr> {headers.map((headerCell: TableHeaderCell) => (headerCell.sortable ? ( <SortableHeaderCell key={headerCell.key} headerCell={headerCell} sortHandler={handleSortClicked} direction={direction} iconSortClasses={getSortingClassesFor(headerCell.key)} /> ) : ( <HeaderCell headerCell={headerCell} /> )))} </tr> </thead> <tbody> {sortedRows.map((row, i) => ( // eslint-disable-next-line react/no-array-index-key <tr key={i}> {Object.keys(row).map((key, cIndex) => (headers[cIndex].renderFn ? ( headers[cIndex].renderFn!(key, row[key]) ) : ( // eslint-disable-next-line react/no-array-index-key <td key={cIndex}>{row[key]}</td> )))} </tr> ))} </tbody> </table> </div> ); };
the_stack
* @file User interface for display and editing annotations. */ import './annotations.css'; import {Annotation, AnnotationId, AnnotationPropertySerializer, AnnotationReference, AnnotationSource, annotationToJson, AnnotationType, annotationTypeHandlers, AxisAlignedBoundingBox, Ellipsoid, formatNumericProperty, Line} from 'neuroglancer/annotation'; import {AnnotationDisplayState, AnnotationLayerState} from 'neuroglancer/annotation/annotation_layer_state'; import {MultiscaleAnnotationSource} from 'neuroglancer/annotation/frontend_source'; import {AnnotationLayer, PerspectiveViewAnnotationLayer, SliceViewAnnotationLayer, SpatiallyIndexedPerspectiveViewAnnotationLayer, SpatiallyIndexedSliceViewAnnotationLayer} from 'neuroglancer/annotation/renderlayer'; import {CoordinateSpace} from 'neuroglancer/coordinate_transform'; import {MouseSelectionState, UserLayer} from 'neuroglancer/layer'; import {LoadedDataSubsource} from 'neuroglancer/layer_data_source'; import {ChunkTransformParameters, getChunkPositionFromCombinedGlobalLocalPositions} from 'neuroglancer/render_coordinate_transform'; import {RenderScaleHistogram, trackableRenderScaleTarget} from 'neuroglancer/render_scale_statistics'; import {RenderLayerRole} from 'neuroglancer/renderlayer'; import {bindSegmentListWidth, registerCallbackWhenSegmentationDisplayStateChanged, SegmentationDisplayState, SegmentWidgetFactory} from 'neuroglancer/segmentation_display_state/frontend'; import {ElementVisibilityFromTrackableBoolean} from 'neuroglancer/trackable_boolean'; import {AggregateWatchableValue, makeCachedLazyDerivedWatchableValue, registerNested, WatchableValueInterface} from 'neuroglancer/trackable_value'; import {getDefaultAnnotationListBindings} from 'neuroglancer/ui/default_input_event_bindings'; import {LegacyTool, registerLegacyTool} from 'neuroglancer/ui/tool'; import {animationFrameDebounce} from 'neuroglancer/util/animation_frame_debounce'; import {arraysEqual, ArraySpliceOp} from 'neuroglancer/util/array'; import {setClipboard} from 'neuroglancer/util/clipboard'; import {serializeColor, unpackRGB, unpackRGBA, useWhiteBackground} from 'neuroglancer/util/color'; import {Borrowed, disposableOnce, RefCounted} from 'neuroglancer/util/disposable'; import {removeChildren} from 'neuroglancer/util/dom'; import {Endianness, ENDIANNESS} from 'neuroglancer/util/endian'; import {ValueOrError} from 'neuroglancer/util/error'; import {vec3} from 'neuroglancer/util/geom'; import {EventActionMap, KeyboardEventBinder, registerActionListener} from 'neuroglancer/util/keyboard_bindings'; import * as matrix from 'neuroglancer/util/matrix'; import {MouseEventBinder} from 'neuroglancer/util/mouse_bindings'; import {formatScaleWithUnitAsString} from 'neuroglancer/util/si_units'; import {NullarySignal, Signal} from 'neuroglancer/util/signal'; import {Uint64} from 'neuroglancer/util/uint64'; import * as vector from 'neuroglancer/util/vector'; import {makeAddButton} from 'neuroglancer/widget/add_button'; import {ColorWidget} from 'neuroglancer/widget/color'; import {makeCopyButton} from 'neuroglancer/widget/copy_button'; import {makeDeleteButton} from 'neuroglancer/widget/delete_button'; import {DependentViewContext, DependentViewWidget} from 'neuroglancer/widget/dependent_view_widget'; import {makeIcon} from 'neuroglancer/widget/icon'; import {makeMoveToButton} from 'neuroglancer/widget/move_to_button'; import {Tab} from 'neuroglancer/widget/tab_view'; import {VirtualList, VirtualListSource} from 'neuroglancer/widget/virtual_list'; export class MergedAnnotationStates extends RefCounted implements WatchableValueInterface<readonly AnnotationLayerState[]> { changed = new NullarySignal(); isLoadingChanged = new NullarySignal(); states: Borrowed<AnnotationLayerState>[] = []; relationships: string[] = []; private loadingCount = 0; get value() { return this.states; } get isLoading() { return this.loadingCount !== 0; } markLoading() { this.loadingCount++; return () => { if (--this.loadingCount === 0) { this.isLoadingChanged.dispatch(); } }; } private sort() { this.states.sort((a, b) => { let d = a.sourceIndex - b.sourceIndex; if (d !== 0) return d; return a.subsourceIndex - b.subsourceIndex; }); } private updateRelationships() { const newRelationships = new Set<string>(); for (const state of this.states) { for (const relationship of state.source.relationships) { newRelationships.add(relationship); } } this.relationships = Array.from(newRelationships); } add(state: Borrowed<AnnotationLayerState>) { this.states.push(state); this.sort(); this.updateRelationships(); this.changed.dispatch(); return () => { const index = this.states.indexOf(state); this.states.splice(index, 1); this.updateRelationships(); this.changed.dispatch(); }; } } function getCenterPosition(center: Float32Array, annotation: Annotation) { switch (annotation.type) { case AnnotationType.AXIS_ALIGNED_BOUNDING_BOX: case AnnotationType.LINE: vector.add(center, annotation.pointA, annotation.pointB); vector.scale(center, center, 0.5); break; case AnnotationType.POINT: center.set(annotation.point); break; case AnnotationType.ELLIPSOID: center.set(annotation.center); break; } } function setLayerPosition( layer: UserLayer, chunkTransform: ValueOrError<ChunkTransformParameters>, layerPosition: Float32Array) { if (chunkTransform.error !== undefined) return; layer.setLayerPosition(chunkTransform.modelTransform, layerPosition); } function visitTransformedAnnotationGeometry( annotation: Annotation, chunkTransform: ChunkTransformParameters, callback: (layerPosition: Float32Array, isVector: boolean) => void) { const {layerRank} = chunkTransform; const paddedChunkPosition = new Float32Array(layerRank); annotationTypeHandlers[annotation.type].visitGeometry(annotation, (chunkPosition, isVector) => { // Rank of "chunk" coordinate space may be less than rank of layer space if the annotations are // embedded in a higher-dimensional space. The extra embedding dimensions always are last and // have a coordinate of 0. paddedChunkPosition.set(chunkPosition); const layerPosition = new Float32Array(layerRank); (isVector ? matrix.transformVector : matrix.transformPoint)( layerPosition, chunkTransform.chunkToLayerTransform, layerRank + 1, paddedChunkPosition, layerRank); callback(layerPosition, isVector); }); } interface AnnotationLayerViewAttachedState { refCounted: RefCounted; annotations: Annotation[]; idToIndex: Map<AnnotationId, number>; listOffset: number; } export class AnnotationLayerView extends Tab { private previousSelectedState: {annotationId: string, annotationLayerState: AnnotationLayerState, pin: boolean}|undefined = undefined; private previousHoverId: string|undefined = undefined; private previousHoverAnnotationLayerState: AnnotationLayerState|undefined = undefined; private virtualListSource: VirtualListSource = { length: 0, render: (index: number) => this.render(index), changed: new Signal<(splices: ArraySpliceOp[]) => void>(), }; private virtualList = new VirtualList({source: this.virtualListSource}); private listElements: {state: AnnotationLayerState, annotation: Annotation}[] = []; private updated = false; private mutableControls = document.createElement('div'); private headerRow = document.createElement('div'); get annotationStates() { return this.layer.annotationStates; } private attachedAnnotationStates = new Map<AnnotationLayerState, AnnotationLayerViewAttachedState>(); private updateAttachedAnnotationLayerStates() { const states = this.annotationStates.states; const {attachedAnnotationStates} = this; const newAttachedAnnotationStates = new Map<AnnotationLayerState, AnnotationLayerViewAttachedState>(); for (const [state, info] of attachedAnnotationStates) { if (!states.includes(state)) { attachedAnnotationStates.delete(state); info.refCounted.dispose(); } } for (const state of states) { const info = attachedAnnotationStates.get(state); if (info !== undefined) { newAttachedAnnotationStates.set(state, info); continue; } const source = state.source; const refCounted = new RefCounted(); if (source instanceof AnnotationSource) { refCounted.registerDisposer( source.childAdded.add((annotation) => this.addAnnotationElement(annotation, state))); refCounted.registerDisposer(source.childUpdated.add( (annotation) => this.updateAnnotationElement(annotation, state))); refCounted.registerDisposer(source.childDeleted.add( (annotationId) => this.deleteAnnotationElement(annotationId, state))); } refCounted.registerDisposer(state.transform.changed.add(this.forceUpdateView)); newAttachedAnnotationStates.set( state, {refCounted, annotations: [], idToIndex: new Map(), listOffset: 0}); } this.attachedAnnotationStates = newAttachedAnnotationStates; attachedAnnotationStates.clear(); this.updateCoordinateSpace(); this.forceUpdateView(); } private forceUpdateView = () => { this.updated = false; this.updateView(); }; private globalDimensionIndices: number[] = []; private localDimensionIndices: number[] = []; private curCoordinateSpaceGeneration = -1; private prevCoordinateSpaceGeneration = -1; private columnWidths: number[] = []; private gridTemplate: string = ''; private updateCoordinateSpace() { const localCoordinateSpace = this.layer.localCoordinateSpace.value; const globalCoordinateSpace = this.layer.manager.root.coordinateSpace.value; const globalDimensionIndices: number[] = []; const localDimensionIndices: number[] = []; for (let globalDim = 0, globalRank = globalCoordinateSpace.rank; globalDim < globalRank; ++globalDim) { if (this.annotationStates.states.some(state => { const transform = state.transform.value; if (transform.error !== undefined) return false; return transform.globalToRenderLayerDimensions[globalDim] !== -1; })) { globalDimensionIndices.push(globalDim); } } for (let localDim = 0, localRank = localCoordinateSpace.rank; localDim < localRank; ++localDim) { if (this.annotationStates.states.some(state => { const transform = state.transform.value; if (transform.error !== undefined) return false; return transform.localToRenderLayerDimensions[localDim] !== -1; })) { localDimensionIndices.push(localDim); } } if (!arraysEqual(globalDimensionIndices, this.globalDimensionIndices) || !arraysEqual(localDimensionIndices, this.localDimensionIndices)) { this.localDimensionIndices = localDimensionIndices; this.globalDimensionIndices = globalDimensionIndices; ++this.curCoordinateSpaceGeneration; } } constructor( public layer: Borrowed<UserLayerWithAnnotations>, public displayState: AnnotationDisplayState) { super(); this.element.classList.add('neuroglancer-annotation-layer-view'); this.registerDisposer(this.visibility.changed.add(() => this.updateView())); this.registerDisposer( layer.annotationStates.changed.add(() => this.updateAttachedAnnotationLayerStates())); this.headerRow.classList.add('neuroglancer-annotation-list-header'); const toolbox = document.createElement('div'); toolbox.className = 'neuroglancer-annotation-toolbox'; layer.initializeAnnotationLayerViewTab(this); const colorPicker = this.registerDisposer(new ColorWidget(this.displayState.color)); colorPicker.element.title = 'Change annotation display color'; this.registerDisposer(new ElementVisibilityFromTrackableBoolean( makeCachedLazyDerivedWatchableValue( shader => shader.match(/\bdefaultColor\b/) !== null, displayState.shaderControls.processedFragmentMain), colorPicker.element)); toolbox.appendChild(colorPicker.element); const {mutableControls} = this; const pointButton = makeIcon({ text: annotationTypeHandlers[AnnotationType.POINT].icon, title: 'Annotate point', onClick: () => { this.layer.tool.value = new PlacePointTool(this.layer, {}); }, }); mutableControls.appendChild(pointButton); const boundingBoxButton = makeIcon({ text: annotationTypeHandlers[AnnotationType.AXIS_ALIGNED_BOUNDING_BOX].icon, title: 'Annotate bounding box', onClick: () => { this.layer.tool.value = new PlaceBoundingBoxTool(this.layer, {}); }, }); mutableControls.appendChild(boundingBoxButton); const lineButton = makeIcon({ text: annotationTypeHandlers[AnnotationType.LINE].icon, title: 'Annotate line', onClick: () => { this.layer.tool.value = new PlaceLineTool(this.layer, {}); }, }); mutableControls.appendChild(lineButton); const ellipsoidButton = makeIcon({ text: annotationTypeHandlers[AnnotationType.ELLIPSOID].icon, title: 'Annotate ellipsoid', onClick: () => { this.layer.tool.value = new PlaceEllipsoidTool(this.layer, {}); }, }); mutableControls.appendChild(ellipsoidButton); toolbox.appendChild(mutableControls); this.element.appendChild(toolbox); this.element.appendChild(this.headerRow); const {virtualList} = this; virtualList.element.classList.add('neuroglancer-annotation-list'); this.element.appendChild(virtualList.element); this.virtualList.element.addEventListener('mouseleave', () => { this.displayState.hoverState.value = undefined; }); const bindings = getDefaultAnnotationListBindings(); this.registerDisposer(new MouseEventBinder(this.virtualList.element, bindings)); this.virtualList.element.title = bindings.describe(); this.registerDisposer(this.displayState.hoverState.changed.add(() => this.updateHoverView())); this.registerDisposer( this.selectedAnnotationState.changed.add(() => this.updateSelectionView())); this.registerDisposer(this.layer.localCoordinateSpace.changed.add(() => { this.updateCoordinateSpace(); this.updateView(); })); this.registerDisposer(this.layer.manager.root.coordinateSpace.changed.add(() => { this.updateCoordinateSpace(); this.updateView(); })); this.updateCoordinateSpace(); this.updateAttachedAnnotationLayerStates(); this.updateSelectionView(); } private getRenderedAnnotationListElement( state: AnnotationLayerState, id: AnnotationId, scrollIntoView: boolean = false): HTMLElement |undefined { const attached = this.attachedAnnotationStates.get(state); if (attached == undefined) return undefined; const index = attached.idToIndex.get(id); if (index === undefined) return undefined; const listIndex = attached.listOffset + index; if (scrollIntoView) { this.virtualList.scrollItemIntoView(index) } return this.virtualList.getItemElement(listIndex); } private clearSelectionClass() { const {previousSelectedState: state} = this; if (state === undefined) return; this.previousSelectedState = undefined; const element = this.getRenderedAnnotationListElement(state.annotationLayerState, state.annotationId); if (element !== undefined) { element.classList.remove('neuroglancer-annotation-selected'); } } private clearHoverClass() { const {previousHoverId, previousHoverAnnotationLayerState} = this; if (previousHoverAnnotationLayerState !== undefined) { this.previousHoverAnnotationLayerState = undefined; this.previousHoverId = undefined; const element = this.getRenderedAnnotationListElement( previousHoverAnnotationLayerState, previousHoverId!!); if (element !== undefined) { element.classList.remove('neuroglancer-annotation-hover'); } } } private selectedAnnotationState = makeCachedLazyDerivedWatchableValue((selectionState, pin) => { if (selectionState === undefined) return undefined; const {layer} = this; const layerSelectionState = selectionState.layers.find(s => s.layer === layer)?.state; if (layerSelectionState === undefined) return undefined; const {annotationId} = layerSelectionState; if (annotationId === undefined) return undefined; const annotationLayerState = this.annotationStates.states.find( x => x.sourceIndex === layerSelectionState.annotationSourceIndex && (layerSelectionState.annotationSubsource === undefined || x.subsourceId === layerSelectionState.annotationSubsource)); if (annotationLayerState === undefined) return undefined; return {annotationId, annotationLayerState, pin}; }, this.layer.manager.root.selectionState, this.layer.manager.root.selectionState.pin); private updateSelectionView() { const selectionState = this.selectedAnnotationState.value; const {previousSelectedState} = this; if (previousSelectedState === selectionState || (previousSelectedState !== undefined && selectionState !== undefined && previousSelectedState.annotationId === selectionState.annotationId && previousSelectedState.annotationLayerState === selectionState.annotationLayerState && previousSelectedState.pin === selectionState.pin)) { return; } this.clearSelectionClass(); this.previousSelectedState = selectionState; if (selectionState === undefined) return; const element = this.getRenderedAnnotationListElement( selectionState.annotationLayerState, selectionState.annotationId, /*scrollIntoView=*/selectionState.pin); if (element !== undefined) { element.classList.add('neuroglancer-annotation-selected'); } } private updateHoverView() { const selectedValue = this.displayState.hoverState.value; let newHoverId: string|undefined; let newAnnotationLayerState: AnnotationLayerState|undefined; if (selectedValue !== undefined) { newHoverId = selectedValue.id; newAnnotationLayerState = selectedValue.annotationLayerState; } const {previousHoverId, previousHoverAnnotationLayerState} = this; if (newHoverId === previousHoverId && newAnnotationLayerState === previousHoverAnnotationLayerState) { return; } this.clearHoverClass(); this.previousHoverId = newHoverId; this.previousHoverAnnotationLayerState = newAnnotationLayerState; if (newHoverId === undefined) return; const element = this.getRenderedAnnotationListElement(newAnnotationLayerState!, newHoverId); if (element === undefined) return; element.classList.add('neuroglancer-annotation-hover'); } private render(index: number) { const {annotation, state} = this.listElements[index]; return this.makeAnnotationListElement(annotation, state); } private setColumnWidth(column: number, width: number) { // Padding width += 2; const {columnWidths} = this; if (columnWidths[column] > width) { // False if `columnWidths[column] === undefined`. return; } columnWidths[column] = width; this.element.style.setProperty(`--neuroglancer-column-${column}-width`, `${width}ch`); } private updateView() { if (!this.visible) { return; } if (this.curCoordinateSpaceGeneration !== this.prevCoordinateSpaceGeneration) { this.updated = false; const {columnWidths} = this; columnWidths.length = 0; const {headerRow} = this; const symbolPlaceholder = document.createElement('div'); symbolPlaceholder.style.gridColumn = `symbol`; const deletePlaceholder = document.createElement('div'); deletePlaceholder.style.gridColumn = `delete`; removeChildren(headerRow); headerRow.appendChild(symbolPlaceholder); let i = 0; let gridTemplate = '[symbol] 2ch'; const addDimension = (coordinateSpace: CoordinateSpace, dimIndex: number) => { const dimWidget = document.createElement('div'); dimWidget.classList.add('neuroglancer-annotations-view-dimension'); const name = document.createElement('span'); name.classList.add('neuroglancer-annotations-view-dimension-name'); name.textContent = coordinateSpace.names[dimIndex]; const scale = document.createElement('scale'); scale.classList.add('neuroglancer-annotations-view-dimension-scale'); scale.textContent = formatScaleWithUnitAsString( coordinateSpace.scales[dimIndex], coordinateSpace.units[dimIndex], {precision: 2}); dimWidget.appendChild(name); dimWidget.appendChild(scale); dimWidget.style.gridColumn = `dim ${i + 1}`; this.setColumnWidth(i, scale.textContent.length + name.textContent.length + 3); gridTemplate += ` [dim] var(--neuroglancer-column-${i}-width)`; ++i; headerRow.appendChild(dimWidget); }; const globalCoordinateSpace = this.layer.manager.root.coordinateSpace.value; for (const globalDim of this.globalDimensionIndices) { addDimension(globalCoordinateSpace, globalDim); } const localCoordinateSpace = this.layer.localCoordinateSpace.value; for (const localDim of this.localDimensionIndices) { addDimension(localCoordinateSpace, localDim); } headerRow.appendChild(deletePlaceholder); gridTemplate += ` [delete] 2ch`; this.gridTemplate = gridTemplate; headerRow.style.gridTemplateColumns = gridTemplate; this.prevCoordinateSpaceGeneration = this.curCoordinateSpaceGeneration; } if (this.updated) { return; } let isMutable = false; const {listElements} = this; listElements.length = 0; for (const [state, info] of this.attachedAnnotationStates) { if (!state.source.readonly) isMutable = true; if (state.chunkTransform.value.error !== undefined) continue; const {source} = state; const annotations = Array.from(source); info.annotations = annotations; const {idToIndex} = info; idToIndex.clear(); for (let i = 0, length = annotations.length; i < length; ++i) { idToIndex.set(annotations[i].id, i); } for (const annotation of annotations) { listElements.push({state, annotation}); } } const oldLength = this.virtualListSource.length; this.updateListLength(); this.virtualListSource.changed!.dispatch( [{retainCount: 0, deleteCount: oldLength, insertCount: listElements.length}]); this.mutableControls.style.display = isMutable ? 'contents' : 'none'; this.resetOnUpdate(); } private updateListLength() { let length = 0; for (const info of this.attachedAnnotationStates.values()) { info.listOffset = length; length += info.annotations.length; } this.virtualListSource.length = length; } private addAnnotationElement(annotation: Annotation, state: AnnotationLayerState) { if (!this.visible) { this.updated = false; return; } if (!this.updated) { this.updateView(); return; } const info = this.attachedAnnotationStates.get(state); if (info !== undefined) { const index = info.annotations.length; info.annotations.push(annotation); info.idToIndex.set(annotation.id, index); const spliceStart = info.listOffset + index; this.listElements.splice(spliceStart, 0, {state, annotation}); this.updateListLength(); this.virtualListSource.changed!.dispatch( [{retainCount: spliceStart, deleteCount: 0, insertCount: 1}]); } this.resetOnUpdate(); } private updateAnnotationElement(annotation: Annotation, state: AnnotationLayerState) { if (!this.visible) { this.updated = false; return; } if (!this.updated) { this.updateView(); return; } const info = this.attachedAnnotationStates.get(state); if (info !== undefined) { const index = info.idToIndex.get(annotation.id); if (index !== undefined) { const updateStart = info.listOffset + index; info.annotations[index] = annotation; this.listElements[updateStart].annotation = annotation; this.virtualListSource.changed!.dispatch( [{retainCount: updateStart, deleteCount: 1, insertCount: 1}]); } } this.resetOnUpdate(); } private deleteAnnotationElement(annotationId: string, state: AnnotationLayerState) { if (!this.visible) { this.updated = false; return; } if (!this.updated) { this.updateView(); return; } const info = this.attachedAnnotationStates.get(state); if (info !== undefined) { const {idToIndex} = info; const index = idToIndex.get(annotationId); if (index !== undefined) { const spliceStart = info.listOffset + index; const {annotations} = info; annotations.splice(index, 1); idToIndex.delete(annotationId); for (let i = index, length = annotations.length; i < length; ++i) { idToIndex.set(annotations[i].id, i); } this.listElements.splice(spliceStart, 1); this.updateListLength(); this.virtualListSource.changed!.dispatch( [{retainCount: spliceStart, deleteCount: 1, insertCount: 0}]); } } this.resetOnUpdate(); } private resetOnUpdate() { this.clearHoverClass(); this.clearSelectionClass(); this.updated = true; this.updateHoverView(); this.updateSelectionView(); } private makeAnnotationListElement(annotation: Annotation, state: AnnotationLayerState) { const chunkTransform = state.chunkTransform.value as ChunkTransformParameters; const element = document.createElement('div'); element.classList.add('neuroglancer-annotation-list-entry'); element.style.gridTemplateColumns = this.gridTemplate; const icon = document.createElement('div'); icon.className = 'neuroglancer-annotation-icon'; icon.textContent = annotationTypeHandlers[annotation.type].icon; element.appendChild(icon); let deleteButton: HTMLElement|undefined; const maybeAddDeleteButton = () => { if (state.source.readonly) return; if (deleteButton !== undefined) return; deleteButton = makeDeleteButton({ title: 'Delete annotation', onClick: event => { event.stopPropagation(); event.preventDefault(); const ref = state.source.getReference(annotation.id); try { state.source.delete(ref); } finally { ref.dispose(); } }, }); deleteButton.classList.add('neuroglancer-annotation-list-entry-delete'); element.appendChild(deleteButton); }; let numRows = 0; visitTransformedAnnotationGeometry(annotation, chunkTransform, (layerPosition, isVector) => { isVector; ++numRows; const position = document.createElement('div'); position.className = 'neuroglancer-annotation-position'; element.appendChild(position); let i = 0; const addDims = (viewDimensionIndices: readonly number[], layerDimensionIndices: readonly number[]) => { for (const viewDim of viewDimensionIndices) { const layerDim = layerDimensionIndices[viewDim]; if (layerDim !== -1) { const coord = Math.floor(layerPosition[layerDim]); const coordElement = document.createElement('div'); const text = coord.toString() coordElement.textContent = text; coordElement.classList.add('neuroglancer-annotation-coordinate'); coordElement.style.gridColumn = `dim ${i + 1}`; this.setColumnWidth(i, text.length); position.appendChild(coordElement); } ++i; } }; addDims( this.globalDimensionIndices, chunkTransform.modelTransform.globalToRenderLayerDimensions); addDims( this.localDimensionIndices, chunkTransform.modelTransform.localToRenderLayerDimensions); maybeAddDeleteButton(); }); if (annotation.description) { ++numRows; const description = document.createElement('div'); description.classList.add('neuroglancer-annotation-description'); description.textContent = annotation.description; element.appendChild(description); } icon.style.gridRow = `span ${numRows}`; if (deleteButton !== undefined) { deleteButton.style.gridRow = `span ${numRows}`; } element.addEventListener('mouseenter', () => { this.displayState.hoverState.value = { id: annotation.id, partIndex: 0, annotationLayerState: state, }; this.layer.selectAnnotation(state, annotation.id, false); }); element.addEventListener('action:select-position', event => { event.stopPropagation(); this.layer.selectAnnotation(state, annotation.id, 'toggle'); }); element.addEventListener('action:pin-annotation', event => { event.stopPropagation(); this.layer.selectAnnotation(state, annotation.id, true); }); element.addEventListener('action:move-to-annotation', event => { event.stopPropagation(); event.preventDefault(); const {layerRank} = chunkTransform; const chunkPosition = new Float32Array(layerRank); const layerPosition = new Float32Array(layerRank); getCenterPosition(chunkPosition, annotation); matrix.transformPoint( layerPosition, chunkTransform.chunkToLayerTransform, layerRank + 1, chunkPosition, layerRank); setLayerPosition(this.layer, chunkTransform, layerPosition); }); const selectionState = this.selectedAnnotationState.value; if (selectionState !== undefined && selectionState.annotationLayerState === state && selectionState.annotationId === annotation.id) { element.classList.add('neuroglancer-annotation-selected'); } return element; } } export class AnnotationTab extends Tab { private layerView = this.registerDisposer(new AnnotationLayerView(this.layer, this.layer.annotationDisplayState)); constructor(public layer: Borrowed<UserLayerWithAnnotations>) { super(); const {element} = this; element.classList.add('neuroglancer-annotations-tab'); element.appendChild(this.layerView.element); } } function getSelectedAssociatedSegments(annotationLayer: AnnotationLayerState) { let segments: Uint64[][] = []; const {relationships} = annotationLayer.source; const {relationshipStates} = annotationLayer.displayState; for (let i = 0, count = relationships.length; i < count; ++i) { const segmentationState = relationshipStates.get(relationships[i]).segmentationState.value; if (segmentationState != null) { if (segmentationState.segmentSelectionState.hasSelectedSegment) { segments[i] = [segmentationState.segmentSelectionState.selectedSegment.clone()]; continue; } } segments[i] = []; } return segments; } abstract class PlaceAnnotationTool extends LegacyTool { layer: UserLayerWithAnnotations; constructor(layer: UserLayerWithAnnotations, options: any) { super(layer); options; } get annotationLayer(): AnnotationLayerState|undefined { for (const state of this.layer.annotationStates.states) { if (!state.source.readonly) return state; } return undefined; } } const ANNOTATE_POINT_TOOL_ID = 'annotatePoint'; const ANNOTATE_LINE_TOOL_ID = 'annotateLine'; const ANNOTATE_BOUNDING_BOX_TOOL_ID = 'annotateBoundingBox'; const ANNOTATE_ELLIPSOID_TOOL_ID = 'annotateSphere'; export class PlacePointTool extends PlaceAnnotationTool { trigger(mouseState: MouseSelectionState) { const {annotationLayer} = this; if (annotationLayer === undefined) { // Not yet ready. return; } if (mouseState.updateUnconditionally()) { const point = getMousePositionInAnnotationCoordinates(mouseState, annotationLayer); if (point === undefined) return; const annotation: Annotation = { id: '', description: '', relatedSegments: getSelectedAssociatedSegments(annotationLayer), point, type: AnnotationType.POINT, properties: annotationLayer.source.properties.map(x => x.default), }; const reference = annotationLayer.source.add(annotation, /*commit=*/true); this.layer.selectAnnotation(annotationLayer, reference.id, true); reference.dispose(); } } get description() { return `annotate point`; } toJSON() { return ANNOTATE_POINT_TOOL_ID; } } function getMousePositionInAnnotationCoordinates( mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState): Float32Array| undefined { const chunkTransform = annotationLayer.chunkTransform.value; if (chunkTransform.error !== undefined) return undefined; const chunkPosition = new Float32Array(chunkTransform.modelTransform.unpaddedRank); if (!getChunkPositionFromCombinedGlobalLocalPositions( chunkPosition, mouseState.unsnappedPosition, annotationLayer.localPosition.value, chunkTransform.layerRank, chunkTransform.combinedGlobalLocalToChunkTransform)) { return undefined; } return chunkPosition; } abstract class TwoStepAnnotationTool extends PlaceAnnotationTool { inProgressAnnotation: {annotationLayer: AnnotationLayerState, reference: AnnotationReference, disposer: () => void}| undefined; abstract getInitialAnnotation( mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState): Annotation; abstract getUpdatedAnnotation( oldAnnotation: Annotation, mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState): Annotation; trigger(mouseState: MouseSelectionState) { const {annotationLayer} = this; if (annotationLayer === undefined) { // Not yet ready. return; } if (mouseState.updateUnconditionally()) { const updatePointB = () => { const state = this.inProgressAnnotation!; const reference = state.reference; const newAnnotation = this.getUpdatedAnnotation(reference.value!, mouseState, annotationLayer); if (JSON.stringify(annotationToJson(newAnnotation, annotationLayer.source)) === JSON.stringify(annotationToJson(reference.value!, annotationLayer.source))) { return; } state.annotationLayer.source.update(reference, newAnnotation); this.layer.selectAnnotation(annotationLayer, reference.id, true); }; if (this.inProgressAnnotation === undefined) { const reference = annotationLayer.source.add( this.getInitialAnnotation(mouseState, annotationLayer), /*commit=*/false); this.layer.selectAnnotation(annotationLayer, reference.id, true); const mouseDisposer = mouseState.changed.add(updatePointB); const disposer = () => { mouseDisposer(); reference.dispose(); }; this.inProgressAnnotation = { annotationLayer, reference, disposer, }; } else { updatePointB(); this.inProgressAnnotation.annotationLayer.source.commit( this.inProgressAnnotation.reference); this.inProgressAnnotation.disposer(); this.inProgressAnnotation = undefined; } } } disposed() { this.deactivate(); super.disposed(); } deactivate() { if (this.inProgressAnnotation !== undefined) { this.inProgressAnnotation.annotationLayer.source.delete(this.inProgressAnnotation.reference); this.inProgressAnnotation.disposer(); this.inProgressAnnotation = undefined; } } } abstract class PlaceTwoCornerAnnotationTool extends TwoStepAnnotationTool { annotationType: AnnotationType.LINE|AnnotationType.AXIS_ALIGNED_BOUNDING_BOX; getInitialAnnotation(mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState): Annotation { const point = getMousePositionInAnnotationCoordinates(mouseState, annotationLayer); return <AxisAlignedBoundingBox|Line>{ id: '', type: this.annotationType, description: '', pointA: point, pointB: point, properties: annotationLayer.source.properties.map(x => x.default), }; } getUpdatedAnnotation( oldAnnotation: AxisAlignedBoundingBox|Line, mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState): Annotation { const point = getMousePositionInAnnotationCoordinates(mouseState, annotationLayer); if (point === undefined) return oldAnnotation; return {...oldAnnotation, pointB: point}; } } export class PlaceBoundingBoxTool extends PlaceTwoCornerAnnotationTool { get description() { return `annotate bounding box`; } getUpdatedAnnotation( oldAnnotation: AxisAlignedBoundingBox, mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState) { const result = super.getUpdatedAnnotation(oldAnnotation, mouseState, annotationLayer) as AxisAlignedBoundingBox; const {pointA, pointB} = result; const rank = pointA.length; for (let i = 0; i < rank; ++i) { if (pointA[i] === pointB[i]) { pointB[i] += 1; } } return result; } toJSON() { return ANNOTATE_BOUNDING_BOX_TOOL_ID; } } PlaceBoundingBoxTool.prototype.annotationType = AnnotationType.AXIS_ALIGNED_BOUNDING_BOX; export class PlaceLineTool extends PlaceTwoCornerAnnotationTool { get description() { return `annotate line`; } private initialRelationships: Uint64[][]|undefined; getInitialAnnotation(mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState): Annotation { const result = super.getInitialAnnotation(mouseState, annotationLayer); this.initialRelationships = result.relatedSegments = getSelectedAssociatedSegments(annotationLayer); return result; } getUpdatedAnnotation( oldAnnotation: Line|AxisAlignedBoundingBox, mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState) { const result = super.getUpdatedAnnotation(oldAnnotation, mouseState, annotationLayer); const initialRelationships = this.initialRelationships; const newRelationships = getSelectedAssociatedSegments(annotationLayer); if (initialRelationships === undefined) { result.relatedSegments = newRelationships; } else { result.relatedSegments = Array.from(newRelationships, (newSegments, i) => { const initialSegments = initialRelationships[i]; newSegments = newSegments.filter(x => initialSegments.findIndex(y => Uint64.equal(x, y)) === -1); return [...initialSegments, ...newSegments]; }); } return result; } toJSON() { return ANNOTATE_LINE_TOOL_ID; } } PlaceLineTool.prototype.annotationType = AnnotationType.LINE; class PlaceEllipsoidTool extends TwoStepAnnotationTool { getInitialAnnotation(mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState): Annotation { const point = getMousePositionInAnnotationCoordinates(mouseState, annotationLayer); return <Ellipsoid>{ type: AnnotationType.ELLIPSOID, id: '', description: '', segments: getSelectedAssociatedSegments(annotationLayer), center: point, radii: vec3.fromValues(0, 0, 0), properties: annotationLayer.source.properties.map(x => x.default), }; } getUpdatedAnnotation( oldAnnotation: Ellipsoid, mouseState: MouseSelectionState, annotationLayer: AnnotationLayerState) { const radii = getMousePositionInAnnotationCoordinates(mouseState, annotationLayer); if (radii === undefined) return oldAnnotation; const center = oldAnnotation.center; const rank = center.length; for (let i = 0; i < rank; ++i) { radii[i] = Math.abs(center[i] - radii[i]); } return <Ellipsoid>{ ...oldAnnotation, radii, }; } get description() { return `annotate ellipsoid`; } toJSON() { return ANNOTATE_ELLIPSOID_TOOL_ID; } } registerLegacyTool( ANNOTATE_POINT_TOOL_ID, (layer, options) => new PlacePointTool(<UserLayerWithAnnotations>layer, options)); registerLegacyTool( ANNOTATE_BOUNDING_BOX_TOOL_ID, (layer, options) => new PlaceBoundingBoxTool(<UserLayerWithAnnotations>layer, options)); registerLegacyTool( ANNOTATE_LINE_TOOL_ID, (layer, options) => new PlaceLineTool(<UserLayerWithAnnotations>layer, options)); registerLegacyTool( ANNOTATE_ELLIPSOID_TOOL_ID, (layer, options) => new PlaceEllipsoidTool(<UserLayerWithAnnotations>layer, options)); const newRelatedSegmentKeyMap = EventActionMap.fromObject({ 'enter': {action: 'commit'}, 'escape': {action: 'cancel'}, }); function makeRelatedSegmentList( listName: string, segments: Uint64[], segmentationDisplayState: WatchableValueInterface<SegmentationDisplayState|null|undefined>, mutate?: ((newSegments: Uint64[]) => void)|undefined) { return new DependentViewWidget( segmentationDisplayState, (segmentationDisplayState, parent, context) => { const listElement = document.createElement('div'); listElement.classList.add('neuroglancer-related-segment-list'); if (segmentationDisplayState != null) { context.registerDisposer(bindSegmentListWidth(segmentationDisplayState, listElement)); } const headerRow = document.createElement('div'); headerRow.classList.add('neuroglancer-related-segment-list-header'); const copyButton = makeCopyButton({ title: `Copy segment IDs`, onClick: () => { setClipboard(segments.map(x => x.toString()).join(', ')); }, }); headerRow.appendChild(copyButton); let headerCheckbox: HTMLInputElement|undefined; if (segmentationDisplayState != null) { headerCheckbox = document.createElement('input'); headerCheckbox.type = 'checkbox'; headerCheckbox.addEventListener('change', () => { const {visibleSegments} = segmentationDisplayState.segmentationGroupState.value; const add = segments.some(id => !visibleSegments.has(id)); for (const id of segments) { visibleSegments.set(id, add); } }); headerRow.appendChild(headerCheckbox); } if (mutate !== undefined) { const deleteButton = makeDeleteButton({ title: 'Remove all IDs', onClick: () => { mutate([]); }, }); headerRow.appendChild(deleteButton); } const titleElement = document.createElement('span'); titleElement.classList.add('neuroglancer-related-segment-list-title'); titleElement.textContent = listName; headerRow.appendChild(titleElement); if (mutate !== undefined) { const addButton = makeAddButton({ title: 'Add related segment ID', onClick: () => { const addContext = new RefCounted(); const addContextDisposer = context.registerDisposer(disposableOnce(addContext)); const newRow = document.createElement('div'); newRow.classList.add('neuroglancer-segment-list-entry'); newRow.classList.add('neuroglancer-segment-list-entry-new'); const copyButton = makeCopyButton({}); copyButton.classList.add('neuroglancer-segment-list-entry-copy'); newRow.appendChild(copyButton); if (segmentationDisplayState != null) { const checkbox = document.createElement('input'); checkbox.classList.add('neuroglancer-segment-list-entry-visible-checkbox'); checkbox.type = 'checkbox'; newRow.appendChild(checkbox); } const deleteButton = makeDeleteButton({ title: 'Cancel adding new segment ID', onClick: () => { addContextDisposer(); }, }); deleteButton.classList.add('neuroglancer-segment-list-entry-delete'); newRow.appendChild(deleteButton); const idElement = document.createElement('input'); idElement.autocomplete = 'off'; idElement.spellcheck = false; idElement.classList.add('neuroglancer-segment-list-entry-id'); const keyboardEventBinder = addContext.registerDisposer( new KeyboardEventBinder(idElement, newRelatedSegmentKeyMap)); keyboardEventBinder.allShortcutsAreGlobal = true; const validateInput = () => { const id = new Uint64(); if (id.tryParseString(idElement.value)) { idElement.dataset.valid = 'true'; return id; } else { idElement.dataset.valid = 'false'; return undefined; } }; validateInput(); idElement.addEventListener('input', () => { validateInput(); }); idElement.addEventListener('blur', () => { const id = validateInput(); if (id !== undefined) { mutate([...segments, id]); } addContextDisposer(); }); registerActionListener(idElement, 'cancel', addContextDisposer); registerActionListener(idElement, 'commit', () => { const id = validateInput(); if (id !== undefined) { mutate([...segments, id]); } addContextDisposer(); }); newRow.appendChild(idElement); listElement.appendChild(newRow); idElement.focus(); addContext.registerDisposer(() => { idElement.value = ''; newRow.remove(); }); }, }); headerRow.appendChild(addButton); } listElement.appendChild(headerRow); const rows: HTMLElement[] = []; const segmentWidgetFactory = SegmentWidgetFactory.make( segmentationDisplayState ?? undefined, /*includeMapped=*/ false); for (const id of segments) { const row = segmentWidgetFactory.get(id); rows.push(row); if (mutate !== undefined) { const deleteButton = makeDeleteButton({ title: 'Remove ID', onClick: event => { mutate(segments.filter(x => !Uint64.equal(x, id))); event.stopPropagation(); }, }); deleteButton.classList.add('neuroglancer-segment-list-entry-delete'); row.children[0].appendChild(deleteButton); } listElement.appendChild(row); } if (segmentationDisplayState != null) { const updateSegments = context.registerCancellable(animationFrameDebounce(() => { const {visibleSegments} = segmentationDisplayState.segmentationGroupState.value; let numVisible = 0; for (const id of segments) { if (visibleSegments.has(id)) { ++numVisible; } } for (const row of rows) { segmentWidgetFactory.update(row); } headerCheckbox!.checked = numVisible === segments.length && numVisible > 0; headerCheckbox!.indeterminate = (numVisible > 0) && (numVisible < segments.length); })); updateSegments(); updateSegments.flush(); registerCallbackWhenSegmentationDisplayStateChanged( segmentationDisplayState, context, updateSegments); context.registerDisposer( segmentationDisplayState.segmentationGroupState.changed.add(updateSegments)); } parent.appendChild(listElement); }); } const ANNOTATION_COLOR_JSON_KEY = 'annotationColor'; export function UserLayerWithAnnotationsMixin<TBase extends {new (...args: any[]): UserLayer}>( Base: TBase) { abstract class C extends Base implements UserLayerWithAnnotations { annotationStates = this.registerDisposer(new MergedAnnotationStates()); annotationDisplayState = new AnnotationDisplayState(); annotationCrossSectionRenderScaleHistogram = new RenderScaleHistogram(); annotationCrossSectionRenderScaleTarget = trackableRenderScaleTarget(8); annotationProjectionRenderScaleHistogram = new RenderScaleHistogram(); annotationProjectionRenderScaleTarget = trackableRenderScaleTarget(8); constructor(...args: any[]) { super(...args); this.annotationDisplayState.color.changed.add(this.specificationChanged.dispatch); this.annotationDisplayState.shader.changed.add(this.specificationChanged.dispatch); this.annotationDisplayState.shaderControls.changed.add(this.specificationChanged.dispatch); this.tabs.add( 'annotations', {label: 'Annotations', order: 10, getter: () => new AnnotationTab(this)}); let annotationStateReadyBinding: (() => void)|undefined; const updateReadyBinding = () => { const isReady = this.isReady; if (isReady && annotationStateReadyBinding !== undefined) { annotationStateReadyBinding(); annotationStateReadyBinding = undefined; } else if (!isReady && annotationStateReadyBinding === undefined) { annotationStateReadyBinding = this.annotationStates.markLoading(); } }; this.readyStateChanged.add(updateReadyBinding); updateReadyBinding(); const {mouseState} = this.manager.layerSelectedValues; this.registerDisposer(mouseState.changed.add(() => { if (mouseState.active) { const {pickedAnnotationLayer} = mouseState; if (pickedAnnotationLayer !== undefined && this.annotationStates.states.includes(pickedAnnotationLayer)) { const existingValue = this.annotationDisplayState.hoverState.value; if (existingValue === undefined || existingValue.id !== mouseState.pickedAnnotationId! || existingValue.partIndex !== mouseState.pickedOffset || existingValue.annotationLayerState !== pickedAnnotationLayer) { this.annotationDisplayState.hoverState.value = { id: mouseState.pickedAnnotationId!, partIndex: mouseState.pickedOffset, annotationLayerState: pickedAnnotationLayer, }; } return; } } this.annotationDisplayState.hoverState.value = undefined; })); } initializeAnnotationLayerViewTab(tab: AnnotationLayerView) { tab; } restoreState(specification: any) { super.restoreState(specification); this.annotationDisplayState.color.restoreState(specification[ANNOTATION_COLOR_JSON_KEY]); } captureSelectionState(state: this['selectionState'], mouseState: MouseSelectionState) { super.captureSelectionState(state, mouseState); const annotationLayer = mouseState.pickedAnnotationLayer; if (annotationLayer === undefined || !this.annotationStates.states.includes(annotationLayer)) { return; } state.annotationId = mouseState.pickedAnnotationId; state.annotationType = mouseState.pickedAnnotationType; state.annotationSerialized = new Uint8Array( mouseState.pickedAnnotationBuffer!, mouseState.pickedAnnotationBufferOffset!); state.annotationPartIndex = mouseState.pickedOffset; state.annotationSourceIndex = annotationLayer.sourceIndex; state.annotationSubsource = annotationLayer.subsourceId; } displayAnnotationState(state: this['selectionState'], parent: HTMLElement, context: RefCounted): boolean { if (state.annotationId === undefined) return false; const annotationLayer = this.annotationStates.states.find( x => x.sourceIndex === state.annotationSourceIndex && (state.annotationSubsource === undefined || x.subsourceId === state.annotationSubsource)); if (annotationLayer === undefined) return false; const reference = context.registerDisposer(annotationLayer.source.getReference(state.annotationId)); parent.appendChild( context .registerDisposer(new DependentViewWidget( context.registerDisposer( new AggregateWatchableValue(() => ({ annotation: reference, chunkTransform: annotationLayer.chunkTransform }))), ({annotation, chunkTransform}, parent, context) => { let statusText: string|undefined; if (annotation == null) { if (state.annotationType !== undefined && state.annotationSerialized !== undefined) { const handler = annotationTypeHandlers[state.annotationType]; const rank = annotationLayer.source.rank; const baseNumBytes = handler.serializedBytes(rank); const geometryOffset = state.annotationSerialized.byteOffset; const propertiesOffset = geometryOffset + baseNumBytes; const dataView = new DataView(state.annotationSerialized.buffer); const isLittleEndian = Endianness.LITTLE === ENDIANNESS; const {properties} = annotationLayer.source; const annotationPropertySerializer = new AnnotationPropertySerializer(rank, properties); annotation = handler.deserialize( dataView, geometryOffset, isLittleEndian, rank, state.annotationId!); annotationPropertySerializer.deserialize( dataView, propertiesOffset, isLittleEndian, annotation.properties = new Array(properties.length)); if (annotationLayer.source.hasNonSerializedProperties()) { statusText = 'Loading...'; } } else { statusText = (annotation === null) ? 'Annotation not found' : 'Loading...'; } } if (annotation != null) { const layerRank = chunkTransform.error === undefined ? chunkTransform.layerRank : 0; const positionGrid = document.createElement('div'); positionGrid.classList.add( 'neuroglancer-selected-annotation-details-position-grid'); positionGrid.style.gridTemplateColumns = `[icon] 0fr [copy] 0fr repeat(${ layerRank}, [dim] 0fr [coord] 0fr) [move] 0fr [delete] 0fr`; parent.appendChild(positionGrid); const handler = annotationTypeHandlers[annotation.type]; const icon = document.createElement('div'); icon.className = 'neuroglancer-selected-annotation-details-icon'; icon.textContent = handler.icon; positionGrid.appendChild(icon); if (layerRank !== 0) { const {layerDimensionNames} = (chunkTransform as ChunkTransformParameters).modelTransform; for (let i = 0; i < layerRank; ++i) { const dimElement = document.createElement('div'); dimElement.classList.add( 'neuroglancer-selected-annotation-details-position-dim'); dimElement.textContent = layerDimensionNames[i]; dimElement.style.gridColumn = `dim ${i + 1}`; positionGrid.appendChild(dimElement); } visitTransformedAnnotationGeometry( annotation, chunkTransform as ChunkTransformParameters, (layerPosition, isVector) => { const copyButton = makeCopyButton({ title: 'Copy position', onClick: () => { setClipboard(layerPosition.map(x => Math.floor(x)).join(', ')); }, }); copyButton.style.gridColumn = 'copy'; positionGrid.appendChild(copyButton); for (let layerDim = 0; layerDim < layerRank; ++layerDim) { const coordElement = document.createElement('div'); coordElement.classList.add( 'neuroglancer-selected-annotation-details-position-coord'); coordElement.style.gridColumn = `coord ${layerDim + 1}`; coordElement.textContent = Math.floor(layerPosition[layerDim]).toString(); positionGrid.appendChild(coordElement); } if (!isVector) { const moveButton = makeMoveToButton({ title: 'Move to position', onClick: () => { setLayerPosition(this, chunkTransform, layerPosition); }, }); moveButton.style.gridColumn = 'move'; positionGrid.appendChild(moveButton); } }); } if (!annotationLayer.source.readonly) { const button = makeDeleteButton({ title: 'Delete annotation', onClick: () => { annotationLayer.source.delete(reference); } }); button.classList.add('neuroglancer-selected-annotation-details-delete'); positionGrid.appendChild(button); } const {relationships, properties} = annotationLayer.source; const sourceReadonly = annotationLayer.source.readonly; for (let i = 0, count = properties.length; i < count; ++i) { const property = properties[i]; const label = document.createElement('label'); label.classList.add('neuroglancer-annotation-property'); const idElement = document.createElement('span'); idElement.classList.add('neuroglancer-annotation-property-label'); idElement.textContent = property.identifier; label.appendChild(idElement); const {description} = property; if (description !== undefined) { label.title = description; } const value = annotation.properties[i]; const valueElement = document.createElement('span'); valueElement.classList.add('neuroglancer-annotation-property-value'); switch (property.type) { case 'rgb': { const colorVec = unpackRGB(value); const hex = serializeColor(colorVec); valueElement.textContent = hex; valueElement.style.backgroundColor = hex; valueElement.style.color = useWhiteBackground(colorVec) ? 'white' : 'black'; break; } case 'rgba': { const colorVec = unpackRGB(value); valueElement.textContent = serializeColor(unpackRGBA(value)); valueElement.style.backgroundColor = serializeColor(unpackRGB(value)); valueElement.style.color = useWhiteBackground(colorVec) ? 'white' : 'black'; break; } default: valueElement.textContent = formatNumericProperty(property, value); break; } label.appendChild(valueElement); parent.appendChild(label); } const {relatedSegments} = annotation; for (let i = 0, count = relationships.length; i < count; ++i) { const related = relatedSegments === undefined ? [] : relatedSegments[i]; if (related.length === 0 && sourceReadonly) continue; const relationshipIndex = i; const relationship = relationships[i]; parent.appendChild( context .registerDisposer(makeRelatedSegmentList( relationship, related, annotationLayer.displayState.relationshipStates .get(relationship) .segmentationState, sourceReadonly ? undefined : newIds => { const annotation = reference.value; if (annotation == null) { return; } let {relatedSegments} = annotation; if (relatedSegments === undefined) { relatedSegments = annotationLayer.source.relationships.map(() => []); } else { relatedSegments = relatedSegments.slice(); } relatedSegments[relationshipIndex] = newIds; const newAnnotation = {...annotation, relatedSegments}; annotationLayer.source.update(reference, newAnnotation); annotationLayer.source.commit(reference); })) .element); } if (!annotationLayer.source.readonly || annotation.description) { if (annotationLayer.source.readonly) { const description = document.createElement('div'); description.className = 'neuroglancer-annotation-details-description'; description.textContent = annotation.description || ''; parent.appendChild(description); } else { const description = document.createElement('textarea'); description.value = annotation.description || ''; description.rows = 3; description.className = 'neuroglancer-annotation-details-description'; description.placeholder = 'Description'; description.addEventListener('change', () => { const x = description.value; annotationLayer.source.update( reference, {...annotation!, description: x ? x : undefined}); annotationLayer.source.commit(reference); }); parent.appendChild(description); } } } if (statusText !== undefined) { const statusMessage = document.createElement('div'); statusMessage.classList.add('neuroglancer-selection-annotation-status'); statusMessage.textContent = statusText; parent.appendChild(statusMessage); } })) .element); return true; } displaySelectionState( state: this['selectionState'], parent: HTMLElement, context: DependentViewContext): boolean { let displayed = this.displayAnnotationState(state, parent, context); if (super.displaySelectionState(state, parent, context)) displayed = true; return displayed; } addLocalAnnotations( loadedSubsource: LoadedDataSubsource, source: AnnotationSource, role: RenderLayerRole) { const {subsourceEntry} = loadedSubsource; const state = new AnnotationLayerState({ localPosition: this.localPosition, transform: loadedSubsource.getRenderLayerTransform(), source, displayState: this.annotationDisplayState, dataSource: loadedSubsource.loadedDataSource.layerDataSource, subsourceIndex: loadedSubsource.subsourceIndex, subsourceId: subsourceEntry.id, role, }); this.addAnnotationLayerState(state, loadedSubsource); } addStaticAnnotations(loadedSubsource: LoadedDataSubsource) { const {subsourceEntry} = loadedSubsource; const {staticAnnotations} = subsourceEntry.subsource; if (staticAnnotations === undefined) return false; loadedSubsource.activate(() => { this.addLocalAnnotations( loadedSubsource, staticAnnotations, RenderLayerRole.DEFAULT_ANNOTATION); }); return true; } addAnnotationLayerState(state: AnnotationLayerState, loadedSubsource: LoadedDataSubsource) { const refCounted = loadedSubsource.activated!; refCounted.registerDisposer(this.annotationStates.add(state)); const annotationLayer = new AnnotationLayer(this.manager.chunkManager, state.addRef()); if (annotationLayer.source instanceof MultiscaleAnnotationSource) { const crossSectionRenderLayer = new SpatiallyIndexedSliceViewAnnotationLayer({ annotationLayer: annotationLayer.addRef(), renderScaleTarget: this.annotationCrossSectionRenderScaleTarget, renderScaleHistogram: this.annotationCrossSectionRenderScaleHistogram }); refCounted.registerDisposer( loadedSubsource.messages.addChild(crossSectionRenderLayer.messages)); const projectionRenderLayer = new SpatiallyIndexedPerspectiveViewAnnotationLayer({ annotationLayer: annotationLayer.addRef(), renderScaleTarget: this.annotationProjectionRenderScaleTarget, renderScaleHistogram: this.annotationProjectionRenderScaleHistogram }); refCounted.registerDisposer( loadedSubsource.messages.addChild(projectionRenderLayer.messages)); refCounted.registerDisposer(registerNested((context, value) => { if (value) { context.registerDisposer(this.addRenderLayer(crossSectionRenderLayer.addRef())); context.registerDisposer(this.addRenderLayer(projectionRenderLayer.addRef())); } }, this.annotationDisplayState.displayUnfiltered)); } { const renderLayer = new SliceViewAnnotationLayer( annotationLayer, this.annotationCrossSectionRenderScaleHistogram); refCounted.registerDisposer(this.addRenderLayer(renderLayer)); refCounted.registerDisposer(loadedSubsource.messages.addChild(renderLayer.messages)); } { const renderLayer = new PerspectiveViewAnnotationLayer( annotationLayer.addRef(), this.annotationProjectionRenderScaleHistogram); refCounted.registerDisposer(this.addRenderLayer(renderLayer)); refCounted.registerDisposer(loadedSubsource.messages.addChild(renderLayer.messages)); } } selectAnnotation( annotationLayer: Borrowed<AnnotationLayerState>, id: string, pin: boolean|'toggle') { this.manager.root.selectionState.captureSingleLayerState(this, state => { state.annotationId = id; state.annotationSourceIndex = annotationLayer.sourceIndex; state.annotationSubsource = annotationLayer.subsourceId; return true; }, pin); } toJSON() { const x = super.toJSON(); x[ANNOTATION_COLOR_JSON_KEY] = this.annotationDisplayState.color.toJSON(); return x; } } return C; } export type UserLayerWithAnnotations = InstanceType<ReturnType<typeof UserLayerWithAnnotationsMixin>>;
the_stack
import {litLocalizeTransform} from '../modes/transform.js'; import ts from 'typescript'; import {Message, makeMessageIdMap} from '../messages.js'; import {test} from 'uvu'; // eslint-disable-next-line import/extensions import * as assert from 'uvu/assert'; import prettier from 'prettier'; import { compileTsFragment, CompilerHostCache, } from '@lit/ts-transformers/tests/compile-ts-fragment.js'; const cache = new CompilerHostCache(); const IMPORT_MSG = `import { msg, str } from "@lit/localize";\n`; const IMPORT_LIT = `import { html } from "lit";\n`; /** * Compile the given fragment of TypeScript source code using the lit-localize * litLocalizeTransformer with the given translations. Check that there are no errors and * that the output matches (prettier-formatted). */ function checkTransform( inputTs: string, expectedJs: string, opts?: { messages?: Message[]; autoImport?: boolean; locale?: string; } ) { if (opts?.autoImport ?? true) { // Rather than fuss with imports in all the test cases, this little hack // automatically imports for `msg` and `html` (assuming those strings aren't // used with any other meanings). if (inputTs.includes('msg')) { inputTs = IMPORT_MSG + inputTs; // Note we don't expect to see the `msg` import in the output JS, since it // should be un-used after litLocalizeTransformation. } if (inputTs.includes('html')) { inputTs = IMPORT_LIT + inputTs; expectedJs = IMPORT_LIT + expectedJs; } } const options = ts.getDefaultCompilerOptions(); options.target = ts.ScriptTarget.ES2015; options.module = ts.ModuleKind.ESNext; options.moduleResolution = ts.ModuleResolutionKind.NodeJs; // Don't automatically load typings from nodes_modules/@types, we're not using // them here, so it's a waste of time. options.typeRoots = []; options.experimentalDecorators = true; const result = compileTsFragment(inputTs, '', options, cache, (program) => ({ before: [ litLocalizeTransform( makeMessageIdMap(opts?.messages ?? []), opts?.locale ?? 'en', program ), ], })); let formattedExpected = prettier.format(expectedJs, {parser: 'typescript'}); // TypeScript >= 4 will add an empty export statement if there are no imports // or exports to ensure this is a module. We don't care about checking this. const unformattedActual = (result.code || '').replace('export {};', ''); let formattedActual; try { formattedActual = prettier.format(unformattedActual, { parser: 'typescript', }); } catch { // We might emit invalid TypeScript in a failing test. Rather than fail with // a Prettier parse exception, it's more useful to see a diff. formattedExpected = expectedJs; formattedActual = unformattedActual; } assert.is(formattedActual, formattedExpected); assert.equal(result.diagnostics, []); } test('unchanged const', () => { const src = 'const foo = "foo";'; checkTransform(src, src); }); test('unchanged html', () => { const src = 'const foo = "foo"; const bar = "bar"; html`Hello ${foo} and ${bar}!`;'; checkTransform(src, src); }); test('msg(string)', () => { checkTransform('msg("Hello World", {id: "foo"});', '"Hello World";'); }); test('msg(string) unnecessarily tagged with str', () => { checkTransform('msg(str`Hello World`, {id: "foo"});', '`Hello World`;'); }); test('msg(string) translated', () => { checkTransform('msg("Hello World", {id: "foo"});', '`Hola Mundo`;', { messages: [{name: 'foo', contents: ['Hola Mundo']}], }); }); test('html(msg(string))', () => { checkTransform( 'html`<b>${msg("Hello World", {id: "foo"})}</b>`;', 'html`<b>Hello World</b>`;' ); }); test('html(msg(string)) translated', () => { checkTransform( 'html`<b>${msg("Hello World", {id: "foo"})}</b>`;', 'html`<b>Hola Mundo</b>`;', {messages: [{name: 'foo', contents: ['Hola Mundo']}]} ); }); test('html(msg(html))', () => { checkTransform( 'html`<b>${msg(html`Hello <i>World</i>`, {id: "foo"})}</b>`;', 'html`<b>Hello <i>World</i></b>`;' ); }); test('html(msg(html)) translated', () => { checkTransform( 'html`<b>${msg(html`Hello <i>World</i>`, {id: "foo"})}</b>`;', 'html`<b>Hola <i>Mundo</i></b>`;', { messages: [ { name: 'foo', contents: [ 'Hola ', {untranslatable: '<i>', index: 0}, 'Mundo', {untranslatable: '</i>', index: 1}, ], }, ], } ); }); test('msg(string(expr))', () => { checkTransform( 'const name = "World";' + 'msg(str`Hello ${name}!`, {id: "foo"});', 'const name = "World";' + '`Hello ${name}!`;' ); }); test('msg(string(expr)) translated', () => { checkTransform( 'const name = "World";' + 'msg(str`Hello ${name}!`, {id: "foo"});', 'const name = "World";' + '`Hola ${name}!`;', { messages: [ { name: 'foo', contents: ['Hola ', {untranslatable: '${name}', index: 0}, '!'], }, ], } ); }); test('msg(string(string))', () => { checkTransform( 'msg(str`Hello ${"World"}!`, {id: "foo"});', '`Hello World!`;' ); }); test('msg(string(string)) translated', () => { checkTransform( 'msg(str`Hello ${"World"}!`, {id: "foo"});', '`Hola World!`;', { messages: [ { name: 'foo', contents: ['Hola ', {untranslatable: '${"World"}', index: 0}, '!'], }, ], } ); }); test('msg(html(expr))', () => { checkTransform( 'const name = "World";' + 'msg(html`Hello <b>${name}</b>!`, {id: "foo"});', 'const name = "World";' + 'html`Hello <b>${name}</b>!`;' ); }); test('msg(html(expr)) translated', () => { checkTransform( 'const name = "World";' + 'msg(html`Hello <b>${name}</b>!`, {id: "foo"});', 'const name = "World";' + 'html`Hola <b>${name}</b>!`;', { messages: [ { name: 'foo', contents: [ 'Hola ', {untranslatable: '<b>${name}</b>', index: 0}, '!', ], }, ], } ); }); test('msg(html(string))', () => { checkTransform( 'msg(html`Hello <b>${"World"}</b>!`, {id: "foo"});', 'html`Hello <b>World</b>!`;' ); }); test('msg(html(string)) translated', () => { checkTransform( 'msg(html`Hello <b>${"World"}</b>!`, {id: "foo"});', 'html`Hola <b>World</b>!`;', { messages: [ { name: 'foo', contents: [ 'Hola ', {untranslatable: '<b>${"World"}</b>', index: 0}, '!', ], }, ], } ); }); test('multiple expression-placeholders and order switching', () => { checkTransform( `const x = 'x'; const y = 'y'; const z = 'z'; msg(html\`a \${x}\${y} b \${z}\`, {id: "foo"});`, `const x = 'x'; const y = 'y'; const z = 'z'; html\`B \${z} A \${x}\${y}\`;`, { messages: [ { name: 'foo', contents: [ 'B ', {untranslatable: 'N/A-1', index: 1}, ' A ', {untranslatable: 'N/A-0', index: 0}, ], }, ], } ); }); // TODO(aomarks) Uncomment with fix for #2426 // test('msg(html(html))', () => { // checkTransform( // 'msg(html`Hello <b>${html`<i>World</i>`}</b>!`, {id: "foo"});', // 'html`Hello <b><i>World</i></b>!`;' // ); // }); // test('msg(html(html)) translated', () => { // checkTransform( // 'msg(html`Hello <b>${html`<i>World</i>`}</b>!`, {id: "foo"});', // 'html`Hola <b><i>World</i></b>!`;', // { // messages: [ // { // name: 'foo', // contents: [ // 'Hola ', // {untranslatable: '<b>${html`<i>World</i>`}</b>', index: 0}, // '!', // ], // }, // ], // } // ); // }); test('msg(string(msg(string)))', () => { checkTransform( 'msg(str`Hello ${msg("World", {id: "bar"})}!`, {id: "foo"});', '`Hello World!`;' ); }); test('msg(string(msg(string))) translated', () => { checkTransform( 'msg(str`Hello ${msg("World", {id: "bar"})}!`, {id: "foo"});', '`Hola Mundo!`;', { messages: [ { name: 'foo', contents: [ 'Hola ', {untranslatable: '${msg("World", {id: "bar"})}', index: 0}, '!', ], }, { name: 'bar', contents: ['Mundo'], }, ], } ); }); test('msg(string(<b>msg(string)</b>)) translated', () => { checkTransform( 'msg(str`Hello <b>${msg("World", {id: "bar"})}</b>!`, {id: "foo"});', '`Hola &lt;b&gt;Mundo&lt;/b&gt;!`;', { messages: [ { name: 'foo', contents: [ 'Hola <b>', {untranslatable: '${msg("World", {id: "bar"})}', index: 0}, '</b>!', ], }, { name: 'bar', contents: ['Mundo'], }, ], } ); }); test('html(msg(string)) with msg as attr value', () => { checkTransform( 'html`Hello <b bar=${msg("World", {id: "bar"})}>${"World"}</b>!`;', 'html`Hello <b bar=${"World"}>World</b>!`;' ); }); test('html(msg(string)) with msg as attr value translated', () => { checkTransform( 'html`Hello <b bar=${msg("world", {id: "bar"})}>${"World"}</b>!`;', 'html`Hello <b bar=${`Mundo`}>World</b>!`;', { messages: [ { name: 'bar', contents: ['Mundo'], }, ], } ); }); test('html(msg(string)) with multiple msg as attr value', () => { checkTransform( 'html`<b foo=${msg("Hello", {id: "foo"})}>${"Hello"}</b>' + '<b bar=${msg("World", {id: "bar"})}>${"World"}</b>!`;', 'html`<b foo=${"Hello"}>Hello</b><b bar=${"World"}>World</b>!`;' ); }); test('html(msg(string)) with multiple msg as attr value translated', () => { checkTransform( 'html`<b foo=${msg("Hello", {id: "foo"})}>${"Hello"}</b>' + '<b bar=${msg("World", {id: "bar"})}>${"World"}</b>!`;', 'html`<b foo=${`Hola`}>Hello</b><b bar=${`Mundo`}>World</b>!`;', { messages: [ { name: 'foo', contents: ['Hola'], }, { name: 'bar', contents: ['Mundo'], }, ], } ); }); test('html(msg(string)) with msg as property attr value', () => { checkTransform( 'html`Hello <b .bar=${msg("World", {id: "bar"})}>${"World"}</b>!`;', 'html`Hello <b .bar=${"World"}>World</b>!`;' ); }); test('html(msg(string)) with msg as property attr value translated', () => { checkTransform( 'html`Hello <b .bar=${msg("World", {id: "bar"})}>${"World"}</b>!`;', 'html`Hello <b .bar=${`Mundo`}>World</b>!`;', { messages: [ { name: 'bar', contents: ['Mundo'], }, ], } ); }); test('import * as litLocalize', () => { checkTransform( ` import * as litLocalize from '@lit/localize'; litLocalize.msg("Hello World", {id: "foo"}); `, '"Hello World";', {autoImport: false} ); }); test('import {msg as foo}', () => { checkTransform( ` import {msg as foo} from '@lit/localize'; foo("Hello World", {id: "foo"}); `, '"Hello World";', {autoImport: false} ); }); test('exclude different msg function', () => { checkTransform( `function msg(template: string, options?: {id?: string}) { return template; } msg("Hello World", {id: "foo"});`, `function msg(template, options) { return template; } msg("Hello World", {id: "foo"});`, {autoImport: false} ); }); test('configureTransformLocalization() -> {getLocale: () => "es-419"}', () => { checkTransform( `import {configureTransformLocalization} from '@lit/localize'; const {getLocale} = configureTransformLocalization({ sourceLocale: 'en', }); const locale = getLocale();`, `const {getLocale} = {getLocale: () => 'es-419'}; const locale = getLocale();`, {locale: 'es-419'} ); }); test('configureLocalization() throws', () => { assert.throws( () => checkTransform( `import {configureLocalization} from '@lit/localize'; configureLocalization({ sourceLocale: 'en', targetLocales: ['es-419'], loadLocale: (locale: string) => import(\`/\${locale}.js\`), });`, `` ), 'Cannot use configureLocalization in transform mode' ); }); test('LOCALE_STATUS_EVENT => "lit-localize-status"', () => { checkTransform( `import {LOCALE_STATUS_EVENT} from '@lit/localize'; window.addEventListener(LOCALE_STATUS_EVENT, () => console.log('ok'));`, `window.addEventListener('lit-localize-status', () => console.log('ok'));` ); }); test('litLocalize.LOCALE_STATUS_EVENT => "lit-localize-status"', () => { checkTransform( `import * as litLocalize from '@lit/localize'; window.addEventListener(litLocalize.LOCALE_STATUS_EVENT, () => console.log('ok'));`, `window.addEventListener('lit-localize-status', () => console.log('ok'));` ); }); test('re-assigned LOCALE_STATUS_EVENT', () => { checkTransform( `import {LOCALE_STATUS_EVENT} from '@lit/localize'; const event = LOCALE_STATUS_EVENT; window.addEventListener(event, () => console.log('ok'));`, `const event = 'lit-localize-status'; window.addEventListener(event, () => console.log('ok'));` ); }); test('different LOCALE_STATUS_EVENT variable unchanged', () => { checkTransform( `const LOCALE_STATUS_EVENT = "x";`, `const LOCALE_STATUS_EVENT = "x";` ); }); test('different variable cast to "lit-localize-status" unchanged', () => { checkTransform(`const x = "x" as "lit-localize-status";`, `const x = "x";`); }); test('updateWhenLocaleChanges -> undefined', () => { checkTransform( `import {LitElement, html} from 'lit'; import {msg, updateWhenLocaleChanges} from '@lit/localize'; class MyElement extends LitElement { constructor() { super(); updateWhenLocaleChanges(this); } render() { return html\`<b>\${msg('Hello World!', {id: 'greeting'})}</b>\`; } }`, `import {LitElement, html} from 'lit'; class MyElement extends LitElement { constructor() { super(); undefined; } render() { return html\`<b>Hello World!</b>\`; } }`, {autoImport: false} ); }); test('@localized removed', () => { checkTransform( `import {LitElement, html} from 'lit'; import {msg, localized} from '@lit/localize'; @localized() class MyElement extends LitElement { render() { return html\`<b>\${msg('Hello World!', {id: 'greeting'})}</b>\`; } }`, `import {LitElement, html} from 'lit'; class MyElement extends LitElement { render() { return html\`<b>Hello World!</b>\`; } }`, {autoImport: false} ); }); test.run();
the_stack
/// <reference path="metricsPlugin.ts"/> /// <reference path="../../includes.ts"/> /// <reference path="services/alertsManager.ts"/> /// <reference path="services/errorsManager.ts"/> module HawkularMetrics { /* tslint:disable:variable-name */ export class AlertSetupController { public static $inject = ['$scope', 'HawkularAlertsManager', 'ErrorsManager', 'NotificationsService', '$log', '$q', '$rootScope', '$routeParams', '$modalInstance', 'resourceId']; public triggerDefinition: any = {}; public adm: any = {}; public admBak: any = {}; public saveProgress: boolean = false; public isSettingChange: boolean = false; constructor(protected $scope: any, protected HawkularAlertsManager: HawkularMetrics.IHawkularAlertsManager, protected ErrorsManager: HawkularMetrics.IErrorsManager, protected NotificationsService: INotificationsService, protected $log: ng.ILogService, protected $q: ng.IQService, protected $rootScope: any, protected $routeParams: any, protected $modalInstance: any, protected resourceId) { // TODO - update the pfly notification service to support more and category based notifications containers. this.$rootScope.hkNotifications = { alerts: [] }; let triggersPromises = this.loadTriggers(); this.$q.all(triggersPromises).then(() => { this.admBak = angular.copy(this.adm); this.isSettingChange = false; }); this.$scope.$watch(angular.bind(this, () => { return this.adm; }), () => { this.isSettingChange = !angular.equals(this.adm, this.admBak); }, true); } public save(): void { this.$log.debug('Saving Alert Settings'); // Clear alerts notifications on save (discard previous success/error list) this.$rootScope.hkNotifications.alerts = []; // Error notification done with callback function on error let errorCallback = (error: any, msg: string) => { this.$rootScope.hkNotifications.alerts.push({ type: 'error', message: msg }); }; this.saveProgress = true; let isError = false; // Check if email action exists let saveTriggersPromises = this.saveTriggers(errorCallback); this.$q.all(saveTriggersPromises).finally(() => { this.saveProgress = false; if (!isError) { // notify success this.NotificationsService.alertSettingsSaved(); this.$rootScope.hkNotifications.alerts.push({ type: 'success', message: 'Changes saved successfully.' }); } this.cancel(); }); } public cancel(): void { this.$modalInstance.dismiss('cancel'); } public loadTriggers(): Array<ng.IPromise<any>> { throw new Error('This method is abstract'); } public saveTriggers(errorCallback): Array<ng.IPromise<any>> { throw new Error('This method is abstract'); } } export class TriggerSetupController { public static $inject = ['$scope', 'HawkularAlertsManager', 'ErrorsManager', 'NotificationsService', '$log', '$q', '$rootScope', '$routeParams', '$location', 'MetricsService']; public fullTrigger: any = {}; public adm: any = {}; public admBak: any = {}; public saveProgress: boolean = false; public isSettingChange: boolean = false; public alertList: any = []; constructor(protected $scope: any, protected HawkularAlertsManager: HawkularMetrics.IHawkularAlertsManager, protected ErrorsManager: HawkularMetrics.IErrorsManager, protected NotificationsService: INotificationsService, protected $log: ng.ILogService, protected $q: ng.IQService, protected $rootScope: any, protected $routeParams: any, protected $location: any, protected MetricsService: IMetricsService) { // TODO - update the pfly notification service to support more and category based notifications containers. this.$rootScope.hkNotifications = { alerts: [] }; let triggerId = this.decodeResourceId(this.$routeParams.triggerId); let triggerPromise = this.loadTrigger(triggerId); this.$q.all(triggerPromise).then(() => { this.admBak = angular.copy(this.adm); this.isSettingChange = false; this.getAlerts(triggerId); }); this.$scope.$watch(angular.bind(this, () => { return this.adm; }), () => { this.isSettingChange = !angular.equals(this.adm, this.admBak); }, true); $scope.$on('SwitchedPersona', () => $location.path('/hawkular-ui/alerts-center-triggers/')); } public cancel(): string { if (this.$rootScope.prevLocation) { return this.$rootScope.prevLocation; } return '/hawkular-ui/alerts-center-triggers'; } public save(): void { this.$log.debug('Saving Settings'); // Clear alerts notifications on save (discard previous success/error list) this.$rootScope.hkNotifications.alerts = []; // Error notification done with callback function on error let errorCallback = (error: any, msg: string) => { this.$rootScope.hkNotifications.alerts.push({ type: 'error', message: msg }); }; this.saveProgress = true; let isError = false; // Check if email action exists let saveTriggerPromise = this.saveTrigger(errorCallback); this.$q.all(saveTriggerPromise).finally(() => { this.saveProgress = false; if (!isError) { // notify success this.NotificationsService.alertSettingsSaved(); this.$rootScope.hkNotifications.alerts.push({ type: 'success', message: 'Changes saved successfully.' }); } }); } public getAlerts(triggerId: string): void { this.HawkularAlertsManager.queryAlerts({ statuses: 'OPEN,ACKNOWLEDGED', triggerIds: triggerId, currentPage: 0, perPage: 10, thin: true }) // just the top 10 .then((queriedAlerts) => { this.alertList = queriedAlerts.alertList; }, (error) => { return this.ErrorsManager.errorHandler(error, 'Error fetching alerts for trigger:' + triggerId); }); } public getAlertRoute(alertId: AlertId): string { let route = 'unknown-trigger-type'; let encodedId = this.encodeResourceId(alertId); route = '/hawkular-ui/alerts-center-detail/' + encodedId; return route; } public loadTrigger(triggerId: string): Array<ng.IPromise<any>> { throw new Error('This method is abstract'); } public saveTrigger(errorCallback): Array<ng.IPromise<any>> { throw new Error('This method is abstract'); } protected encodeResourceId(resourceId: string): string { // for some reason using standard encoding is not working correctly in the route. So do something dopey... //let encoded = encodeURIComponent(resourceId); let encoded = resourceId; while (encoded.indexOf('/') > -1) { encoded = encoded.replace('/', '$'); } return encoded; } protected decodeResourceId(encodedResourceId: string): string { // for some reason using standard encoding is not working correctly in the route. So do something dopey... //let decoded = decodeURIComponent(encodedResourceId); let decoded = encodedResourceId; while (decoded.indexOf('$') > -1) { decoded = decoded.replace('$', '/'); } return decoded; } // 0 indicates we should use default dampening (alert every time), anything above 0 is time-based dampening protected getEvalTimeSetting(evalTimeSetting: any): number { if ((undefined === evalTimeSetting) || (null === evalTimeSetting) || (0 > evalTimeSetting)) { return 0; } return evalTimeSetting; } protected updateAction(actions: ITriggerAction[], actionPlugin: string, actionId: string, properties: any) { if ((undefined === actions) || (null === actions)) { actions = [{ actionPlugin: actionPlugin, actionId: actionId }]; return actions; } let i = actions.length; while( i-- ) { if( actions[i] && actions[i].actionPlugin === actionPlugin ) { actions[i].actionId = actionId; return actions; } } actions[actions.length].actionPlugin = actionPlugin; actions[actions.length].actionId = actionId; return actions; } protected removeAction(actions: any, actionPlugin: string) { if ( !actions ) { return null; } let i = actions.length; while( i-- ) { if( actions[i] && actions[i].actionPlugin === actionPlugin ) { actions.splice(i,1); } } return actions; } } export class MetricsAlertController { public static $inject = ['$scope', 'HawkularAlertsManager', 'ErrorsManager', 'NotificationsService', '$log', '$q', '$rootScope', '$routeParams', '$modal', '$interval', '$location', 'HkHeaderParser']; public alertList: any = []; public openSetup: any; public isResolvingAll: boolean = false; public alertsTimeStart: TimestampInMillis; public alertsTimeEnd: TimestampInMillis; public alertsTimeOffset: TimestampInMillis; public resCurPage: number = 0; public resPerPage: number = 5; public headerLinks: any; constructor(private $scope: any, private HawkularAlertsManager: HawkularMetrics.IHawkularAlertsManager, private ErrorsManager: HawkularMetrics.IErrorsManager, private NotificationsService: INotificationsService, private $log: ng.ILogService, private $q: ng.IQService, private $rootScope: IHawkularRootScope, private $routeParams: any, private $modal: any, private $interval: ng.IIntervalService, private $location: ng.ILocationService, private HkHeaderParser: any) { this.$log.debug('querying data'); this.$log.debug('$routeParams', $routeParams); this.alertsTimeOffset = $routeParams.timeOffset || 3600000; // If the end time is not specified in URL use current time as end time this.alertsTimeEnd = $routeParams.endTime ? $routeParams.endTime : (new Date()).getTime(); this.alertsTimeStart = this.alertsTimeEnd - this.alertsTimeOffset; this.getAlerts(); $scope.$on('SwitchedPersona', () => $location.path('/hawkular-ui/url/url-list')); this.autoRefresh(20); } private autoRefresh(intervalInSeconds: number): void { let autoRefreshPromise = this.$interval(() => { this.getAlerts(); }, intervalInSeconds * 1000); this.$scope.$on('$destroy', () => { this.$interval.cancel(autoRefreshPromise); }); } public getAlerts(): void { this.alertsTimeEnd = this.$routeParams.endTime ? this.$routeParams.endTime : (new Date()).getTime(); this.alertsTimeStart = this.alertsTimeEnd - this.alertsTimeOffset; let resourceId: string = this.$routeParams.resourceId; let triggerIds: string = resourceId + '_trigger_avail,' + resourceId + '_trigger_thres'; this.HawkularAlertsManager.queryAlerts({ statuses: 'OPEN', triggerIds: triggerIds, startTime: this.alertsTimeStart, endTime: this.alertsTimeEnd, currentPage: this.resCurPage, perPage: this.resPerPage }).then((queriedAlerts) => { this.headerLinks = this.HkHeaderParser.parse(queriedAlerts.headers); _.forEach(queriedAlerts.alertList, (item) => { if (item['type'] === 'THRESHOLD') { item['alertType'] = 'PINGRESPONSE'; } else if (item['type'] === 'AVAILABILITY') { item['alertType'] = 'PINGAVAIL'; } }); this.alertList = queriedAlerts.alertList; this.alertList.$resolved = true; // FIXME }, (error) => { return this.ErrorsManager.errorHandler(error, 'Error fetching alerts.'); }); } public setPage(page: number): void { this.resCurPage = page; this.getAlerts(); } public resolveAll(): void { this.isResolvingAll = true; let alertIdList = ''; for (let i = 0; i < this.alertList.length; i++) { alertIdList = alertIdList + this.alertList[i].id + ','; } alertIdList = alertIdList.slice(0, -1); let resolvedAlerts = { alertIds: alertIdList, resolvedBy: this.$rootScope.currentPersona.name, resolvedNotes: 'Manually resolved' }; this.HawkularAlertsManager.resolveAlerts(resolvedAlerts).then(() => { this.alertList.length = 0; this.isResolvingAll = false; }); } } _module.controller('MetricsAlertController', MetricsAlertController); export class AlertUrlAvailabilitySetupController extends AlertSetupController { public loadTriggers(): Array<ng.IPromise<any>> { let availabilityTriggerId = this.$routeParams.resourceId + '_trigger_avail'; let availabilityTriggerPromise = this.HawkularAlertsManager.getTrigger(availabilityTriggerId) .then((triggerData) => { this.$log.debug('triggerData', triggerData); this.triggerDefinition['avail'] = triggerData; this.adm['avail'] = {}; this.adm.avail['email'] = triggerData.trigger.actions.email[0]; this.adm.avail['responseDuration'] = triggerData.dampenings[0].evalTimeSetting; this.adm.avail['conditionEnabled'] = triggerData.trigger.enabled; }); return [availabilityTriggerPromise]; } public saveTriggers(errorCallback): Array<ng.IPromise<any>> { // Set the actual object to save let availabilityTrigger = angular.copy(this.triggerDefinition.avail); availabilityTrigger.trigger.actions.email[0] = this.adm.avail.email; availabilityTrigger.trigger.enabled = this.adm.avail.conditionEnabled; availabilityTrigger.dampenings[0].evalTimeSetting = this.adm.avail.responseDuration; availabilityTrigger.dampenings[1].evalTimeSetting = this.adm.avail.responseDuration; let availabilitySavePromise = this.HawkularAlertsManager.updateTrigger(availabilityTrigger, errorCallback, this.triggerDefinition.avail); return [availabilitySavePromise]; } } _module.controller('AlertUrlAvailabilitySetupController', AlertUrlAvailabilitySetupController); export class AlertUrlResponseSetupController extends AlertSetupController { public loadTriggers(): Array<ng.IPromise<any>> { let responseTriggerId = this.$routeParams.resourceId + '_trigger_thres'; let responseTriggerPromise = this.HawkularAlertsManager.getTrigger(responseTriggerId).then( (triggerData) => { this.$log.debug('triggerData', triggerData); this.triggerDefinition['thres'] = triggerData; this.adm['thres'] = {}; this.adm.thres['email'] = triggerData.trigger.actions.email[0]; this.adm.thres['responseDuration'] = triggerData.dampenings[0].evalTimeSetting; this.adm.thres['conditionEnabled'] = triggerData.trigger.enabled; this.adm.thres['conditionThreshold'] = triggerData.conditions[0].threshold; }); return [responseTriggerPromise]; } public saveTriggers(errorCallback): Array<ng.IPromise<any>> { // Set the actual object to save let responseTrigger = angular.copy(this.triggerDefinition.thres); responseTrigger.trigger.enabled = this.adm.thres.conditionEnabled; if (this.adm.thres.conditionEnabled) { responseTrigger.trigger.actions.email[0] = this.adm.thres.email; responseTrigger.dampenings[0].evalTimeSetting = this.adm.thres.responseDuration; responseTrigger.dampenings[1].evalTimeSetting = this.adm.thres.responseDuration; responseTrigger.conditions[0].threshold = this.adm.thres.conditionThreshold; responseTrigger.conditions[1].threshold = this.adm.thres.conditionThreshold; } let responseSavePromise = this.HawkularAlertsManager.updateTrigger(responseTrigger, errorCallback, this.triggerDefinition.thres); return [responseSavePromise]; } } _module.controller('AlertUrlResponseSetupController', AlertUrlResponseSetupController); // TODO - update the pfly notification service to support other methods of notification container dismissal. export interface IHkClearNotifications extends ng.IScope { hkClearNotifications: Array<any>; } export class HkClearNotifications { public link: (scope: IHkClearNotifications, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void; public scope = { hkClearNotifications: '=' }; constructor() { this.link = (scope: IHkClearNotifications, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => { angular.element('html').on('click', () => { if (scope.hkClearNotifications && scope.hkClearNotifications.length && scope.hkClearNotifications.length > 0) { scope.$apply(() => { scope.hkClearNotifications = []; }); } }); }; } public static Factory() { let directive = () => { return new HkClearNotifications(); }; directive['$inject'] = []; return directive; } } _module.directive('hkClearNotifications', HkClearNotifications.Factory()); }
the_stack
import * as path from 'path'; import fs from 'fs-extra'; import chai, { expect } from 'chai'; import Helper from '../../src/e2e-helper/e2e-helper'; import * as fixtures from '../../src/fixtures/fixtures'; import NpmCiRegistry, { supportNpmCiRegistryTesting } from '../npm-ci-registry'; import { componentIssuesLabels } from '../../src/cli/templates/component-issues-template'; chai.use(require('chai-fs')); (supportNpmCiRegistryTesting ? describe : describe.skip)( 'installing dependencies as packages (not as components)', function() { this.timeout(0); let helper: Helper; let npmCiRegistry; before(() => { helper = new Helper(); helper.command.setFeatures('legacy-workspace-config'); }); after(() => { helper.scopeHelper.destroy(); }); describe('components with nested dependencies', () => { before(async () => { npmCiRegistry = new NpmCiRegistry(helper); await npmCiRegistry.init(); helper.scopeHelper.setNewLocalAndRemoteScopes(); npmCiRegistry.setCiScopeInBitJson(); helper.fs.createFile('utils', 'is-type.js', fixtures.isType); helper.fixtures.addComponentUtilsIsType(); helper.fs.createFile('utils', 'is-string.js', fixtures.isString); helper.fixtures.addComponentUtilsIsString(); helper.fixtures.createComponentBarFoo(fixtures.barFooFixture); // creating a dev dependency for bar/foo to make sure the links are not generated. (see bug #1614) helper.fs.createFile('fixtures', 'mock.json'); helper.command.addComponent('fixtures'); helper.fs.createFile('bar', 'foo.spec.js', "require('../fixtures/mock.json');"); helper.command.addComponent('bar/foo.js', { t: 'bar/foo.spec.js', i: 'bar/foo' }); helper.command.tagAllComponents(); helper.command.tagAllComponents('-s 0.0.2'); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); npmCiRegistry.setCiScopeInBitJson(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); helper.command.importComponent('utils/is-type'); helper.command.importComponent('utils/is-string'); helper.command.importComponent('fixtures'); helper.scopeHelper.removeRemoteScope(); npmCiRegistry.publishComponent('utils/is-type'); npmCiRegistry.publishComponent('utils/is-string'); npmCiRegistry.publishComponent('bar/foo'); npmCiRegistry.publishComponent('fixtures'); npmCiRegistry.publishComponent('utils/is-type', '0.0.2'); npmCiRegistry.publishComponent('utils/is-string', '0.0.2'); npmCiRegistry.publishComponent('bar/foo', '0.0.2'); npmCiRegistry.publishComponent('fixtures', '0.0.2'); }); after(() => { npmCiRegistry.destroy(); }); describe('installing a component using NPM', () => { before(() => { helper.scopeHelper.reInitLocalScope(); helper.command.runCmd('npm init -y'); helper.command.runCmd(`npm install @ci/${helper.scopes.remote}.bar.foo`); const appJsFixture = `const barFoo = require('@ci/${helper.scopes.remote}.bar.foo'); console.log(barFoo());`; fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), appJsFixture); }); it('should be able to require its direct dependency and print results from all dependencies', () => { const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); describe('isolating a component that requires Bit component as a package (no objects for the component)', () => { before(() => { helper.command.addComponent('app.js'); helper.bitJson.modifyField('bindingPrefix', '@ci'); helper.scopeHelper.addRemoteScope(); }); it('should be able to isolate without throwing an error ComponentNotFound', () => { const capsuleDir = helper.general.generateRandomTmpDirName(); helper.command.isolateComponentWithCapsule('app', capsuleDir); // makes sure the bar/foo was saved as a component and not as a package expect(path.join(capsuleDir, '.dependencies/bar/foo')).to.be.a.path(); }); }); }); describe('importing a component using Bit', () => { let beforeImportScope; let afterImportScope; before(() => { helper.scopeHelper.reInitLocalScope(); npmCiRegistry.setCiScopeInBitJson(); npmCiRegistry.setResolver(); beforeImportScope = helper.scopeHelper.cloneLocalScope(); helper.command.importComponent('bar/foo'); afterImportScope = helper.scopeHelper.cloneLocalScope(); }); it('should not create .dependencies directory', () => { expect(path.join(helper.scopes.localPath, 'components/.dependencies')).to.not.be.a.path(); }); it('should install the dependencies using NPM', () => { const basePath = path.join(helper.scopes.localPath, 'components/bar/foo/node_modules/@ci'); expect(path.join(basePath, `${helper.scopes.remote}.utils.is-string`, 'is-string.js')).to.be.a.file(); expect(path.join(basePath, `${helper.scopes.remote}.utils.is-type`, 'is-type.js')).to.be.a.file(); }); it('bit status should not show any error', () => { helper.command.expectStatusToBeClean(); }); it('should be able to require its direct dependency and print results from all dependencies', () => { const appJsFixture = "const barFoo = require('./components/bar/foo'); console.log(barFoo());"; fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), appJsFixture); const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); describe('checkout to an older version', () => { before(() => { helper.command.checkout('0.0.1 bar/foo'); }); it('should not create .dependencies directory', () => { expect(path.join(helper.scopes.localPath, 'components/.dependencies')).to.not.be.a.path(); }); it('should install the dependencies using NPM', () => { const basePath = path.join(helper.scopes.localPath, 'components/bar/foo/node_modules/@ci'); expect(path.join(basePath, `${helper.scopes.remote}.utils.is-string`, 'is-string.js')).to.be.a.file(); expect(path.join(basePath, `${helper.scopes.remote}.utils.is-type`, 'is-type.js')).to.be.a.file(); }); it('bit status should not show any error', () => { const output = helper.command.runCmd('bit status'); const outputWithoutLinebreaks = output.replace(/\n/, ''); expect(outputWithoutLinebreaks).to.have.string('pending updates'); }); it('should be able to require its direct dependency and print results from all dependencies', () => { const appJsFixture = "const barFoo = require('./components/bar/foo'); console.log(barFoo());"; fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), appJsFixture); const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); }); describe('import all dependencies directly', () => { before(() => { helper.scopeHelper.getClonedLocalScope(afterImportScope); helper.command.importComponent('utils/is-string'); helper.command.importComponent('utils/is-type'); }); it('should write the correct scope in the package.json file', () => { const packageJson = helper.packageJson.read(); const packages = Object.keys(packageJson.dependencies); expect(packages).to.include(`@ci/${helper.scopes.remote}.bar.foo`); expect(packages).to.include(`@ci/${helper.scopes.remote}.utils.is-string`); expect(packages).to.include(`@ci/${helper.scopes.remote}.utils.is-type`); }); it('bit status should not show any error', () => { helper.command.expectStatusToBeClean(); }); describe('bit checkout all components to an older version', () => { let checkoutOutput; before(() => { checkoutOutput = helper.command.checkout('0.0.1 --all'); }); it('should not crash and show a success message', () => { expect(checkoutOutput).to.have.string('successfully switched'); }); it('should be able to require its direct dependency and print results from all dependencies', () => { const appJsFixture = "const barFoo = require('./components/bar/foo'); console.log(barFoo());"; fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), appJsFixture); const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); }); }); describe('updating dependency version from the dependent package.json', () => { describe('when using caret (^) in the version', () => { before(() => { helper.scopeHelper.getClonedLocalScope(afterImportScope); const barFooDir = path.join(helper.scopes.localPath, 'components/bar/foo'); const packageJson = helper.packageJson.read(barFooDir); packageJson.dependencies[`@ci/${helper.scopes.remote}.utils.is-string`] = '^1.0.0'; helper.packageJson.write(packageJson, barFooDir); }); it('should show the dependency version from the package.json', () => { const barFoo = helper.command.showComponentParsed('bar/foo'); expect(barFoo.dependencies[0].id).to.equal(`${helper.scopes.remote}/utils/is-string@1.0.0`); }); }); describe('when importing also the dependency so the package.json has a different version than the model', () => { before(() => { helper.scopeHelper.getClonedLocalScope(beforeImportScope); helper.command.importComponent('bar/foo'); helper.command.importComponent('utils/is-string'); const barFooDir = path.join(helper.scopes.localPath, 'components/bar/foo'); const packageJson = helper.packageJson.read(barFooDir); packageJson.dependencies[`@ci/${helper.scopes.remote}.utils.is-string`] = '0.0.1'; helper.packageJson.write(packageJson, barFooDir); }); it('should show the dependency version from the package.json', () => { const barFoo = helper.command.showComponentParsed('bar/foo'); expect(barFoo.dependencies[0].id).to.equal(`${helper.scopes.remote}/utils/is-string@0.0.1`); }); it('bit diff should show the dependencies ', () => { const diff = helper.command.diff('bar/foo'); expect(diff).to.have.string(`- [ ${helper.scopes.remote}/utils/is-string@0.0.2 ]`); expect(diff).to.have.string(`+ [ ${helper.scopes.remote}/utils/is-string@0.0.1 ]`); }); describe('tagging the component', () => { before(() => { helper.command.tagAllComponents(); }); it('should save the version from package.json into the scope', () => { const barFoo = helper.command.catComponent(`${helper.scopes.remote}/bar/foo@latest`); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.dependencies[0].id.version).to.equal('0.0.1'); }); it('bit status should not show the component as modified', () => { const status = helper.command.status(); const statusWithoutLinebreaks = status.replace(/\n/, ''); expect(statusWithoutLinebreaks).to.not.have.string('modified'); }); }); }); }); describe('import dependency and dependent with the same command', () => { describe('when the dependent comes before the dependency', () => { before(() => { helper.scopeHelper.getClonedLocalScope(beforeImportScope); helper.command.importManyComponents(['bar/foo', 'utils/is-string']); }); it('should write the path of the dependency into the dependent package.json instead of the version', () => { const packageJson = helper.packageJson.read(path.join(helper.scopes.localPath, 'components/bar/foo')); expect(packageJson.dependencies[`@ci/${helper.scopes.remote}.utils.is-string`]).to.equal( 'file:../../utils/is-string' ); }); }); describe('when the dependency comes before the dependent', () => { before(() => { helper.scopeHelper.getClonedLocalScope(beforeImportScope); helper.command.importManyComponents(['utils/is-string', 'bar/foo']); }); it('should write the path of the dependency into the dependent package.json instead of the version', () => { const packageJson = helper.packageJson.read(path.join(helper.scopes.localPath, 'components/bar/foo')); expect(packageJson.dependencies[`@ci/${helper.scopes.remote}.utils.is-string`]).to.equal( 'file:../../utils/is-string' ); }); }); }); describe('isolating with capsule', () => { let capsuleDir; before(() => { helper.scopeHelper.getClonedLocalScope(afterImportScope); capsuleDir = helper.general.generateRandomTmpDirName(); helper.command.runCmd( `bit isolate ${helper.scopes.remote}/bar/foo --use-capsule --directory ${capsuleDir}` ); fs.outputFileSync(path.join(capsuleDir, 'app.js'), fixtures.appPrintBarFooCapsule); }); it('should have the components and dependencies installed correctly with all the links', () => { const result = helper.command.runCmd('node app.js', capsuleDir); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); }); describe('monorepo structure, import a dependency from a sub-package', () => { before(() => { helper.scopeHelper.getClonedLocalScope(beforeImportScope); helper.npm.initNpm(); helper.fs.createNewDirectoryInLocalWorkspace('sub-pkg'); const subPkgDir = path.join(helper.scopes.localPath, 'sub-pkg'); helper.npm.initNpm(subPkgDir); helper.command.runCmd(`npm install @ci/${helper.scopes.remote}.bar.foo`, subPkgDir); helper.fs.outputFile('sub-pkg/comp/comp.js', `require('@ci/${helper.scopes.remote}.bar.foo');`); helper.command.addComponent('sub-pkg/comp/comp.js'); }); it('bit status should not show the dependency as missing', () => { const status = helper.command.statusJson(); expect(status.componentsWithMissingDeps).to.have.lengthOf(0); }); it('bit show should show the correct dependency', () => { const show = helper.command.showComponentParsed('comp'); expect(show.dependencies).to.have.lengthOf(1); expect(show.dependencies[0].id).to.equal(`${helper.scopes.remote}/bar/foo@0.0.2`); }); }); describe('multiple test files require the same package', () => { before(() => { helper.scopeHelper.getClonedLocalScope(afterImportScope); const barFooDir = 'components/bar/foo/bar'; helper.fs.createFile(path.join(barFooDir, 'foo.js'), ''); // remove the prod dep helper.fs.outputFile( path.join(barFooDir, 'foo.spec.js'), `require('@ci/${helper.scopes.remote}.utils.is-string');` ); // add dev-dep helper.fs.outputFile( path.join(barFooDir, 'foo1.spec.js'), `require('@ci/${helper.scopes.remote}.utils.is-string');` ); // add another spec with same dep helper.command.addComponent('-t components/bar/foo/bar/foo1.spec.js -i bar/foo'); }); it('bit show should not show the same devDependency twice', () => { const show = helper.command.showComponentParsed('bar/foo'); expect(show.devDependencies).to.have.lengthOf(1); }); it('bit tag should tag them successfully', () => { const tag = helper.command.tagAllComponents(); expect(tag).to.have.string('1 component(s) tagged'); }); }); }); }); describe('components with nested dependencies and compiler', () => { before(async () => { helper = new Helper(); helper.command.setFeatures('legacy-workspace-config'); npmCiRegistry = new NpmCiRegistry(helper); await npmCiRegistry.init(); helper.scopeHelper.setNewLocalAndRemoteScopes(); npmCiRegistry.setCiScopeInBitJson(); helper.fs.createFile('utils', 'is-type.js', fixtures.isType); helper.fixtures.addComponentUtilsIsType(); helper.fs.createFile('utils', 'is-string.js', fixtures.isString); helper.fixtures.addComponentUtilsIsString(); helper.fixtures.createComponentBarFoo(fixtures.barFooFixture); helper.fixtures.addComponentBarFoo(); helper.env.importCompiler(); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); helper.command.importComponent('utils/is-type'); helper.command.importComponent('utils/is-string'); helper.scopeHelper.removeRemoteScope(); npmCiRegistry.publishComponent('utils/is-type'); npmCiRegistry.publishComponent('utils/is-string'); npmCiRegistry.publishComponent('bar/foo'); }); after(() => { npmCiRegistry.destroy(); }); describe('installing a component using NPM', () => { before(() => { helper.scopeHelper.reInitLocalScope(); helper.command.runCmd('npm init -y'); helper.command.runCmd(`npm install @ci/${helper.scopes.remote}.bar.foo`); }); it('should be able to require its direct dependency and print results from all dependencies', () => { const appJsFixture = `const barFoo = require('@ci/${helper.scopes.remote}.bar.foo'); console.log(barFoo());`; fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), appJsFixture); const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); }); describe('importing a component using Bit', () => { let beforeImportScope; before(() => { helper.scopeHelper.reInitLocalScope(); npmCiRegistry.setCiScopeInBitJson(); npmCiRegistry.setResolver(); beforeImportScope = helper.scopeHelper.cloneLocalScope(); helper.command.importComponent('bar/foo'); }); it('bit status should not show any error', () => { helper.command.expectStatusToBeClean(); }); it('should be able to require its direct dependency and print results from all dependencies', () => { const appJsFixture = "const barFoo = require('./components/bar/foo'); console.log(barFoo());"; fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), appJsFixture); const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); describe('deleting the dependency package from the FS', () => { before(() => { helper.fs.deletePath('components/bar/foo/node_modules/@ci'); }); it('bit status should show not show it as untracked components', () => { const statusJson = helper.command.statusJson(); expect(statusJson.invalidComponents).to.have.lengthOf(0); expect(statusJson.componentsWithMissingDeps).to.have.lengthOf(0); const status = helper.command.status(); const statusWithoutLinebreaks = status.replace(/\n/g, ''); expect(statusWithoutLinebreaks).not.to.have.string(componentIssuesLabels.untrackedDependencies); }); }); describe('import with dist outside the component directory', () => { before(() => { helper.scopeHelper.getClonedLocalScope(beforeImportScope); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! helper.bitJson.modifyField('dist', { target: 'dist' }); helper.command.importComponent('bar/foo'); }); it('bit status should not show any error', () => { helper.command.expectStatusToBeClean(); }); describe('running bit link after deleting the symlink from dist directory', () => { let symlinkPath; before(() => { symlinkPath = 'dist/components/bar/foo/node_modules/@ci'; helper.fs.deletePath(symlinkPath); helper.command.runCmd('bit link'); }); it('should recreate the symlink with the correct path', () => { const expectedDest = path.join(helper.scopes.localPath, symlinkPath); expect(expectedDest).to.be.a.path(); const symlinkValue = fs.readlinkSync(expectedDest); expect(symlinkValue).to.have.string( path.join(helper.scopes.local, 'components/bar/foo/node_modules/@ci') ); }); }); }); }); }); } );
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 ChildProcess from 'child_process'; const CompareVersion = require('compare-versions'); import * as deploy_contracts from './contracts'; import * as deploy_globals from './globals'; import * as deploy_values from './values'; import * as deploy_workspace from './workspace'; import * as FileType from 'file-type'; import * as FS from 'fs'; const FTP = require('jsftp'); const Glob = require('glob'); import * as HTTP from 'http'; import * as HTTPs from 'https'; import * as i18 from './i18'; const IsBinaryFile = require("isbinaryfile"); const MergeDeep = require('merge-deep'); const MIME = require('mime'); import * as Minimatch from 'minimatch'; import * as Moment from 'moment'; import * as Net from 'net'; import * as Path from 'path'; import * as SFTP from 'ssh2-sftp-client'; import * as TMP from 'tmp'; import * as URL from 'url'; import * as vscode from 'vscode'; import * as Workflows from 'node-workflows'; /** * A download result. */ export interface DownloadResult { /** * The downloaded data. */ data: Buffer; /** * The MIME type (if available). */ mime?: string; /** * The name (of the file if available). */ name?: string; } /** * Options for open function. */ export interface OpenOptions { /** * The app (or options) to open. */ app?: string | string[]; /** * The custom working directory. */ cwd?: string; /** * An optional list of environment variables * to submit to the new process. */ env?: any; /** * Wait until exit or not. */ wait?: boolean; } /** * Describes a simple 'completed' action. * * @param {any} [err] The occurred error. * @param {TResult} [result] The result. */ export type SimpleCompletedAction<TResult> = (err?: any, result?: TResult) => void; let nextHtmlDocId = -1; /** * Applies values to an object. * * @param {T} obj The object to apply the values to. * @param {deploy_contracts.ObjectWithNameAndValue|deploy_contracts.ObjectWithNameAndValue[]} values The values to apply. * @param {boolean} [cloneObj] Clone object or not. * * @return {T} The object with the applied values. */ export function applyValues<T extends deploy_contracts.Applyable>(obj: T, values: deploy_contracts.ObjectWithNameAndValue | deploy_contracts.ObjectWithNameAndValue[], cloneObj = true): T { values = asArray(values).filter(v => v); if (toBooleanSafe(cloneObj)) { obj = cloneObject(obj); } if (obj) { let applyTo = cloneObject(obj.applyValuesTo); if (applyTo) { for (let p in applyTo) { let valueToSet = applyTo[p]; if (values.length > 0) { valueToSet = deploy_values.replaceWithValues(values, valueToSet); } obj[p] = valueToSet; } } } return obj; } /** * Returns a value as array. * * @param {T | T[]} val The value. * * @return {T[]} The value as array. */ export function asArray<T>(val: T | T[]): T[] { if (!Array.isArray(val)) { return [ val ]; } return val; } /** * Clones an object / value deep. * * @param {T} val The value / object to clone. * * @return {T} The cloned value / object. */ export function cloneObject<T>(val: T): T { if (!val) { return val; } return JSON.parse(JSON.stringify(val)); } /** * Compares two values for a sort operation. * * @param {T} x The left value. * @param {T} y The right value. * * @return {number} The "sort value". */ export function compareValues<T>(x: T, y: T): number { if (x === y) { return 0; } if (x > y) { return 1; } if (x < y) { return -1; } return 0; } /** * Compares values by using a selector. * * @param {T} x The left value. * @param {T} y The right value. * @param {Function} selector The selector. * * @return {number} The "sort value". */ export function compareValuesBy<T, U>(x: T, y: T, selector: (t: T) => U): number { if (!selector) { selector = (t) => <any>t; } return compareValues<U>(selector(x), selector(y)); } /** * Compares two versions. * * @param {any} current The current value. * @param {any} other The other value. * * @returns {number} The sort value. */ export function compareVersions(current: any, other: any): number { if (!isNullOrUndefined(current)) { current = toStringSafe(current).trim(); } if (!isNullOrUndefined(other)) { other = toStringSafe(other).trim(); } return CompareVersion(current, other); } /** * Creates a quick pick for deploying a single file. * * @param {string} file The file to deploy. * @param {deploy_contracts.DeployTarget} target The target to deploy to. * @param {number} index The zero based index. * @param {deploy_values.ValueBase[]} [values] Values / placeholders to use. * * @returns {deploy_contracts.DeployFileQuickPickItem} The new item. */ export function createFileQuickPick(file: string, target: deploy_contracts.DeployTarget, index: number, values?: deploy_values.ValueBase[]): deploy_contracts.DeployFileQuickPickItem { let qp: any = createTargetQuickPick(target, index, values); qp['file'] = file; return qp; } /** * Creates a quick pick for a package. * * @param {deploy_contracts.DeployPackage} pkg The package. * @param {number} index The zero based index. * @param {deploy_values.ValueBase[]} [values] Values / placeholders to use. * * @returns {deploy_contracts.DeployPackageQuickPickItem} The new item. */ export function createPackageQuickPick(pkg: deploy_contracts.DeployPackage, index: number, values?: deploy_values.ValueBase[]): deploy_contracts.DeployPackageQuickPickItem { let name = toStringSafe(pkg.name).trim(); if ('' === name) { name = i18.t('packages.defaultName', index + 1); } let description = toStringSafe(pkg.description).trim(); let item: deploy_contracts.DeployPackageQuickPickItem = { description: description, label: name, package: pkg, }; // item.detail Object.defineProperty(item, 'detail', { enumerable: true, get: () => { return deploy_values.replaceWithValues(values, pkg.detail); } }); return item; } /** * Creates a simple 'completed' callback for a promise. * * @param {Function} resolve The 'succeeded' callback. * @param {Function} reject The 'error' callback. * * @return {SimpleCompletedAction<TResult>} The created action. */ export function createSimplePromiseCompletedAction<TResult>(resolve: Function, reject?: Function): SimpleCompletedAction<TResult> { return (err?, result?) => { if (err) { if (reject) { reject(err); } } else { if (resolve) { resolve(result); } } }; } /** * Creates a quick pick for a target. * * @param {deploy_contracts.DeployTarget} target The target. * @param {number} index The zero based index. * @param {deploy_values.ValueBase[]} [values] Values / placeholders to use. * * @returns {deploy_contracts.DeployTargetQuickPickItem} The new item. */ export function createTargetQuickPick(target: deploy_contracts.DeployTarget, index: number, values?: deploy_values.ValueBase[]): deploy_contracts.DeployTargetQuickPickItem { let name = toStringSafe(target.name).trim(); if (!name) { name = i18.t('targets.defaultName', index + 1); } let description = toStringSafe(target.description).trim(); let item: deploy_contracts.DeployTargetQuickPickItem = { description: description, label: name, target: target, }; // item.detail Object.defineProperty(item, 'detail', { enumerable: true, get: () => { return deploy_values.replaceWithValues(values, target.detail); } }); return item; } /** * Deploys files. * * @param {string | string[]} files The files to deploy. * @param {deploy_contracts.DeployTargetList} targets The targets to deploy to. * @param {symbol} [sym] The custom symbol to use for the identification. * * @return {Promise<deploy_contracts.DeployFilesEventArguments>} The promise. */ export function deployFiles(files: string | string[], targets: deploy_contracts.DeployTargetList, sym?: symbol): Promise<deploy_contracts.DeployFilesEventArguments> { return new Promise<deploy_contracts.DeployFilesEventArguments>((resolve, reject) => { let completed = (err?: any, args?: deploy_contracts.DeployFilesEventArguments) => { if (err) { reject(err); } else { resolve(args); } }; try { let alreadyInvoked = false; let listener: Function; listener = function(args: deploy_contracts.DeployFilesEventArguments) { if (alreadyInvoked) { return; } if (!isNullOrUndefined(sym) && (sym !== args.symbol)) { return; } alreadyInvoked = true; try { deploy_globals.EVENTS.removeListener(deploy_contracts.EVENT_DEPLOYFILES_COMPLETE, listener); } catch (e) { log(i18.t('errors.withCategory', 'helpers.deployFiles()', e)); } completed(); }; deploy_globals.EVENTS.on(deploy_contracts.EVENT_DEPLOYFILES_COMPLETE, listener); deploy_globals.EVENTS.emit(deploy_contracts.EVENT_DEPLOYFILES, files, targets, sym); } catch (e) { completed(e); } }); } /** * Tries to detect the MIME type of a file. * * @param {string} file The Filename. * @param {any} defValue The default value. * * @return {string} The MIME type. */ export function detectMimeByFilename(file: string, defValue: any = 'application/octet-stream'): string { let mime: string; try { mime = MIME.lookup(file); } catch (e) { log(i18.t('errors.withCategory', 'helpers.detectMimeByFilename()', e)); } mime = normalizeString(mime); if ('' === mime) { mime = defValue; } return mime; } /** * Checks if a file path does match by any pattern. * * @param {string} file The path to check. * @param {deploy_contracts.FileFilter} filter The filter to use. * * @return {boolean} Does match or not. */ export function doesFileMatchByFilter(file: string, filter: deploy_contracts.FileFilter): boolean { if (!filter) { return null; } file = toStringSafe(file); // files in include let allFilePatterns: string[] = []; if (filter.files) { allFilePatterns = asArray(filter.files).map(x => toStringSafe(x)) .filter(x => '' !== x); allFilePatterns = distinctArray(allFilePatterns); } if (allFilePatterns.length < 1) { allFilePatterns.push('**'); // include all by default } // files to exclude let allExcludePatterns: string[] = []; if (filter.exclude) { allExcludePatterns = asArray(filter.exclude).map(x => toStringSafe(x)) .filter(x => '' !== x); } allExcludePatterns = distinctArray(allExcludePatterns); let doesPatternMatch = (pattern: string) => { return Minimatch(file, pattern, { dot: true, nonegate: true, nocomment: true, }); }; // first check if ignored while (allExcludePatterns.length > 0) { let ep = allExcludePatterns.shift(); if (doesPatternMatch(ep)) { return false; // ignored / excluded } } // now check if matches while (allFilePatterns.length > 0) { let fp = allFilePatterns.shift(); if (doesPatternMatch(fp)) { return true; // included / does match } } return false; } /** * Removes duplicate entries from an array. * * @param {T[]} arr The input array. * * @return {T[]} The filtered array. */ export function distinctArray<T>(arr: T[]): T[] { if (!arr) { return arr; } return arr.filter((x, i) => { return arr.indexOf(x) === i; }); } /** * Filters "conditional" items. * * @param {T|T[]} items The items to filter. * @param {deploy_values.ValueBase|deploy_values.ValueBase[]} [values] The values to use. * * @return {T[]} The filtered items. */ export function filterConditionalItems<T extends deploy_contracts.ConditionalItem>(items: T | T[], values?: deploy_values.ValueBase | deploy_values.ValueBase[]): T[] { let result = asArray(items).filter(x => x); result = result.filter((x, idx) => { try { let conditions = asArray(x.if).map(x => toStringSafe(x)) .filter(x => '' !== x.trim()); for (let i = 0; i < conditions.length; i++) { let cv = new deploy_values.CodeValue({ code: conditions[i], name: `condition_${idx}_${i}`, type: 'code', }); cv.otherValueProvider = () => asArray(values).filter(x => x); if (!toBooleanSafe(cv.value)) { return false; // at least one condition does NOT match } } } catch (e) { log(i18.t('errors.withCategory', 'helpers.filterConditionalItems()', e)); return false; } return true; }); return result; } /** * Filters items by platform. * * @param {(T|T[])} items The items to filter. * @param {string} [platform] The custom name of the platform to use. * * @returns {T[]} The new list of filtered items. */ export function filterPlatformItems<T extends deploy_contracts.PlatformItem>(items: T | T[], platform?: string): T[] { platform = normalizeString(platform); if ('' === platform) { platform = normalizeString(process.platform); } return asArray<T>(items).filter(x => x) .filter(x => { let platformNames = asArray(x.platforms).map(x => normalizeString(x)) .filter(x => x); return platformNames.length < 1 || platformNames.indexOf(platform) > -1; }); } /** * Formats a string. * * @param {any} formatStr The value that represents the format string. * @param {any[]} [args] The arguments for 'formatStr'. * * @return {string} The formated string. */ export function format(formatStr: any, ...args: any[]): string { return formatArray(formatStr, args); } /** * Formats a string. * * @param {any} formatStr The value that represents the format string. * @param {any[]} [args] The arguments for 'formatStr'. * * @return {string} The formated string. */ export function formatArray(formatStr: any, args: any[]): string { if (!args) { args = []; } formatStr = toStringSafe(formatStr); // apply arguments in // placeholders return formatStr.replace(/{(\d+)(\:)?([^}]*)}/g, (match, index, formatSeparator, formatExpr) => { index = parseInt(toStringSafe(index).trim()); let resultValue = args[index]; if (':' === formatSeparator) { // collect "format providers" let formatProviders = toStringSafe(formatExpr).split(',') .map(x => x.toLowerCase().trim()) .filter(x => x); // transform argument by // format providers formatProviders.forEach(fp => { switch (fp) { case 'leading_space': resultValue = toStringSafe(resultValue); if ('' !== resultValue) { resultValue = ' ' + resultValue; } break; case 'lower': resultValue = toStringSafe(resultValue).toLowerCase(); break; case 'trim': resultValue = toStringSafe(resultValue).trim(); break; case 'upper': resultValue = toStringSafe(resultValue).toUpperCase(); break; case 'surround': resultValue = toStringSafe(resultValue); if ('' !== resultValue) { resultValue = "'" + toStringSafe(resultValue) + "'"; } break; } }); } if ('undefined' === typeof resultValue) { return match; } return toStringSafe(resultValue); }); } /** * Returns the list of files by a filter that should be deployed. * * @param {deploy_contracts.FileFilter} filter The filter. * @param {boolean} useGitIgnoreStylePatterns Also check directory patterns, like in .gitignore files, or not. * * @return {string[]} The list of files. */ export function getFilesByFilter(filter: deploy_contracts.FileFilter, useGitIgnoreStylePatterns: boolean): string[] { if (!filter) { return []; } useGitIgnoreStylePatterns = toBooleanSafe(useGitIgnoreStylePatterns); // files in include let allFilePatterns: string[] = []; if (filter.files) { allFilePatterns = asArray(filter.files).map(x => toStringSafe(x)) .filter(x => '' !== x); allFilePatterns = distinctArray(allFilePatterns); } if (allFilePatterns.length < 1) { allFilePatterns.push('**'); // include all by default } // files to exclude let allExcludePatterns: string[] = []; if (filter.exclude) { allExcludePatterns = asArray(filter.exclude).map(x => toStringSafe(x)) .filter(x => '' !== x); } allExcludePatterns = distinctArray(allExcludePatterns); // collect files to deploy let filesToDeploy: string[] = []; allFilePatterns.forEach(x => { let matchingFiles: string[] = Glob.sync(x, { absolute: true, cwd: deploy_workspace.getRootPath(), dot: true, ignore: allExcludePatterns, nodir: true, root: deploy_workspace.getRootPath(), }); matchingFiles.forEach(y => filesToDeploy.push(y)); }); return distinctArray(filesToDeploy); } /** * Returns the list of files by a filter that should be deployed. * * @param {deploy_contracts.FileFilter} filter The filter. * @param {boolean} useGitIgnoreStylePatterns Also check directory patterns, like in .gitignore files, or not. * * @return {Promise<string[]>} The promise. */ export function getFilesByFilterAsync(filter: deploy_contracts.FileFilter, useGitIgnoreStylePatterns: boolean): Promise<string[]> { useGitIgnoreStylePatterns = toBooleanSafe(useGitIgnoreStylePatterns); // files in include let allFilePatterns: string[] = []; if (filter.files) { allFilePatterns = asArray(filter.files).map(x => toStringSafe(x)) .filter(x => '' !== x); allFilePatterns = distinctArray(allFilePatterns); } if (allFilePatterns.length < 1) { allFilePatterns.push('**'); // include all by default } // files to exclude let allExcludePatterns: string[] = []; if (filter.exclude) { allExcludePatterns = asArray(filter.exclude).map(x => toStringSafe(x)) .filter(x => '' !== x); } allExcludePatterns = distinctArray(allExcludePatterns); return new Promise<string[]>((resolve, reject) => { let completed = (err: any, files?: string[]) => { if (err) { reject(err); } else { resolve(distinctArray(files || [])); } }; if (filter) { try { let wf = Workflows.create(); wf.next((ctx) => { ctx.result = []; }); allFilePatterns.forEach(x => { wf.next((ctx) => { let files: string[] = ctx.result; return new Promise<any>((res, rej) => { try { Glob(x, { absolute: true, cwd: deploy_workspace.getRootPath(), dot: true, ignore: allExcludePatterns, nodir: true, root: deploy_workspace.getRootPath(), }, (err: any, matchingFiles: string[]) => { if (err) { rej(err); } else { ctx.result = files.concat(matchingFiles); res(); } }); } catch (e) { rej(e); } }); }); }); wf.start().then((files: string[]) => { completed(null, files); }).catch((err) => { completed(err); }); } catch (e) { completed(e); } } else { completed(null); } }); } /** * Returns the list of files of a package that should be deployed. * * @param {deploy_contracts.DeployPackage} pkg The package. * @param {boolean} useGitIgnoreStylePatterns Also check directory patterns, like in .gitignore files, or not. * * @return {string[]} The list of files. */ export function getFilesOfPackage(pkg: deploy_contracts.DeployPackage, useGitIgnoreStylePatterns: boolean): string[] { pkg = cloneObject(pkg); if (pkg) { if (!pkg.exclude) { pkg.exclude = []; } if (toBooleanSafe(pkg.noNodeModules)) { pkg.exclude.push('node_modules/**'); } } return getFilesByFilter(pkg, useGitIgnoreStylePatterns); } /** * Loads the body from a HTTP response. * * @param {HTTP.IncomingMessage} resp The response. * * @return {Promise<Buffer>} The promise. */ export function getHttpBody(resp: HTTP.IncomingMessage): Promise<Buffer> { return new Promise<Buffer>((resolve, reject) => { let body: Buffer; let completed = (err?: any) => { if (err) { reject(err); } else { resolve(body); } }; if (!resp) { completed(); return; } body = Buffer.alloc(0); try { let appendChunk = (chunk: Buffer): boolean => { try { if (chunk) { body = Buffer.concat([body, chunk]); } return true; } catch (e) { completed(e); return false; } }; resp.on('data', (chunk: Buffer) => { if (!appendChunk(chunk)) { return; } }); resp.on('end', (chunk: Buffer) => { if (!appendChunk(chunk)) { return; } let l = body.length; completed(); }); resp.on('error', (err) => { completed(err); }); } catch (e) { completed(e); } }); } /** * Returns the sort value from a sortable. * * @param {deploy_contracts.Sortable} s The sortable object. * @param {deploy_contracts.ValueProvider<string>} [nameProvider] The custom function that provides the name of the machine. * * @return {any} The sort value. */ export function getSortValue(s: deploy_contracts.Sortable, nameProvider?: deploy_contracts.ValueProvider<string>): any { let name: string; if (nameProvider) { name = normalizeString(nameProvider()); } let sortValue: any = s.sortOrder; if (!sortValue) { sortValue = 0; } if ('number' !== typeof sortValue) { // handle as object and find a property // that has the same name as this machine let sortObj = sortValue; let valueAlreadySet = false; Object.getOwnPropertyNames(sortObj).forEach(p => { if (!valueAlreadySet && !normalizeString(p)) { sortValue = sortObj[p]; // custom default value defined } if (normalizeString(p) == name) { sortValue = sortObj[p]; // found valueAlreadySet = true; } }); } // keep sure to have a number here sortValue = parseFloat(('' + sortValue).trim()); if (isNaN(sortValue)) { sortValue = 0; } return sortValue; } /** * Returns the color for a status bar item based an operation result. * * @param {any} err The error. * @param {number} succeedCount The number of successed operations. * @param {number} failedCount The number of failed operations. * * @return {string} The color. */ export function getStatusBarItemColor(err: any, succeedCount: number, failedCount: number): string { let color: string; if (err || failedCount > 0) { if (succeedCount < 1) { color = '#ff0000'; } else { color = '#ffff00'; } } return color; } /** * Returns the value from a "parameter" object. * * @param {Object} params The object. * @param {string} name The name of the parameter. * * @return {string} The value of the parameter (if found). */ export function getUrlParam(params: Object, name: string): string { if (params) { name = normalizeString(name); for (let p in params) { if (normalizeString(p) === name) { return toStringSafe(params[p]); } } } } /** * Checks if data is binary or text content. * * @param {Buffer} data The data to check. * * @returns {Promise<boolean>} The promise. */ export function isBinaryContent(data: Buffer): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { let completed = createSimplePromiseCompletedAction<boolean>(resolve, reject); if (!data) { completed(null); return; } try { IsBinaryFile(data, data.length, (err, result) => { if (err) { completed(err); return; } completed(null, toBooleanSafe(result)); }); } catch (e) { completed(e); } }); } /** * Checks if the string representation of a value is empty * or contains whitespaces only. * * @param {any} val The value to check. * * @return {boolean} Is empty or not. */ export function isEmptyString(val: any): boolean { return '' === toStringSafe(val).trim(); } /** * Checks if a file (or directory) path is ignored. * * @param {string} fileOrDir The file / directory to check. * @param {string|string[]} patterns One or more (glob) pattern to use. * @param {boolean} useGitIgnoreStylePatterns Also check directory patterns, like in .gitignore files, or not. * @param {boolean} {fastCheck} Use 'minimatch' instead of 'node.glob'. * * @return {boolean} Is ignored or not. */ export function isFileIgnored(file: string, patterns: string | string[], useGitIgnoreStylePatterns: boolean, fastCheck?: boolean): boolean { useGitIgnoreStylePatterns = toBooleanSafe(useGitIgnoreStylePatterns); file = toStringSafe(file); if ('' === file.trim()) { return true; } if (!Path.isAbsolute(file)) { file = Path.join(deploy_workspace.getRootPath(), file); } file = Path.resolve(file); file = replaceAllStrings(file, Path.sep, '/'); patterns = asArray(patterns).map(p => toStringSafe(p)) .filter(p => '' !== p.trim()); patterns = distinctArray(patterns); fastCheck = toBooleanSafe(fastCheck); while (patterns.length > 0) { let p = patterns.shift(); let isMatching = false; if (fastCheck) { // use minimatch isMatching = Minimatch(file, p, { dot: true, nonegate: true, nocomment: true, }); } else { let matchingFiles: string[] = Glob.sync(p, { absolute: true, cwd: deploy_workspace.getRootPath(), dot: true, nodir: true, root: deploy_workspace.getRootPath(), }); isMatching = matchingFiles.indexOf(file) > -1; } if (isMatching) { return true; } } return false; } /** * Checks if a value is (null) or (undefined). * * @param {any} val The value to check. * * @return {boolean} Is (null)/(undefined) or not. */ export function isNullOrUndefined(val: any): boolean { return null === val || 'undefined' === typeof val; } /** * Checks if a value is (null), (undefined) or an empty string. * * @param {any} val The value to check. * * @return {boolean} Is (null)/(undefined)/empty string or not. */ export function isNullUndefinedOrEmptyString(val: any): boolean { return isNullOrUndefined(val) || '' === toStringSafe(val); } /** * Loads base settings for object from files. * * @param {T|T[]} objs The objects. * @param {deploy_values.ValueBase|deploy_values.ValueBase[]} values The values to use for the file path(s). * @param {boolean} cloneObjects Clone objects or not. * * @return {T[]} The new list. */ export function loadBaseSettingsFromFiles<T extends deploy_contracts.CanLoadFrom>(objs: T | T[], values?: deploy_values.ValueBase | deploy_values.ValueBase[], cloneObjects = true): T[] { return asArray(objs).filter(x => x).map(x => { let loadFrom: string; try { loadFrom = deploy_values.replaceWithValues(values, x.loadFrom); if (!isEmptyString(x.loadFrom)) { if (!Path.isAbsolute(loadFrom)) { loadFrom = Path.join(deploy_workspace.getRootPath(), '.vscode', loadFrom); } let basePackages: T[] = JSON.parse( FS.readFileSync(loadFrom).toString('utf8') ); basePackages = loadBaseSettingsFromFiles(basePackages, values); let args = [ {}, x ].concat(basePackages); x = MergeDeep.apply(null, [{}, x].concat(basePackages)); } if (toBooleanSafe(cloneObjects)) { x = cloneObject(x); } delete x['loadFrom']; } catch (e) { vscode.window.showErrorMessage(i18.t('load.from.failed', loadFrom, e)).then(() => {}, (err) => { log(`[ERROR] helpers.loadBaseSettingsFromFiles(): ${e}`); }); } return x; }); } /** * Loads a "data transformer" module. * * @param {string} file The path of the module's file. * @param {boolean} useCache Use cache or not. * * @return {deploy_contracts.DataTransformModule} The loaded module. */ export function loadDataTransformerModule(file: string, useCache: boolean = false): deploy_contracts.DataTransformModule { return loadModule<deploy_contracts.DataTransformModule>(file, useCache); } /** * Loads a module for a deploy operation. * * @param {string} file The path of the module's file. * @param {boolean} useCache Use cache or not. * * @return {deploy_contracts.DeployScriptOperationModule} The loaded module. */ export function loadDeployScriptOperationModule(file: string, useCache: boolean = false): deploy_contracts.DeployScriptOperationModule { return loadModule<deploy_contracts.DeployScriptOperationModule>(file, useCache); } /** * Loads data from a source. * * @param {string} src The path or URL to the source. * * @return {Promise<DownloadResult>} The promise. */ export function loadFrom(src: string): Promise<DownloadResult> { return new Promise<DownloadResult>((resolve, reject) => { let completedInvoked = false; let completed = (err: any, result?: DownloadResult) => { if (completedInvoked) { return; } completedInvoked = true; if (err) { reject(err); } else { resolve(result); } }; try { src = toStringSafe(src); let url: URL.Url; try { url = URL.parse(src); } catch (e) { url = null; } let wf = Workflows.create(); let isLocal = true; if (url) { isLocal = false; let fileName = Path.basename(url.path); let protocol = normalizeString(url.protocol); let getUserAndPassword = () => { let user: string; let pwd: string; if (!isNullUndefinedOrEmptyString(url.auth)) { let auth = url.auth; if (auth.indexOf(':') > -1) { let parts = auth.split(':'); user = parts[0]; if ('' === user) { user = undefined; } pwd = parts.filter((x, i) => i > 0).join(':'); if ('' === pwd) { pwd = undefined; } } else { user = auth; } } return { password: pwd, user: user, }; }; switch (protocol) { case 'ftp:': // FTP server { wf.next((ctx) => { return new Promise<any>((res, rej) => { try { let port = 21; if (!isNullUndefinedOrEmptyString(url.port)) { port = parseInt(toStringSafe(url.port).trim()); } // authorization let auth = getUserAndPassword(); // open connection let conn = new FTP({ host: url.hostname, port: port, user: auth.user, pass: auth.password, }); conn.get(url.path, (err: any, socket: Net.Socket) => { if (err) { rej(err); // could not get file from FTP } else { try { let result: Buffer = Buffer.alloc(0); socket.on("data", function(data: Buffer) { try { if (data) { result = Buffer.concat([result, data]); } } catch (e) { rej(e); } }); socket.once("close", function(hadErr: boolean) { if (hadErr) { rej(new Error('FTP error!')); } else { res({ data: result, fileName: fileName, }); } }); socket.resume(); } catch (e) { rej(e); // socket error } } }); } catch (e) { rej(e); // global FTP error } }); }); } break; case 'sftp:': // SFTP server { // start connection wf.next((ctx) => { return new Promise<SFTP>((res, rej) => { try { let port = 22; if (!isNullUndefinedOrEmptyString(url.port)) { port = parseInt(toStringSafe(url.port).trim()); } // authorization let auth = getUserAndPassword(); let conn = new SFTP(); conn.connect({ host: url.hostname, port: port, username: auth.user, password: auth.password, }).then(() => { res(conn); }).catch((err) => { rej(err); }); } catch (e) { rej(e); } }); }); // start reading file wf.next((ctx) => { let conn: SFTP = ctx.previousValue; return new Promise<NodeJS.ReadableStream>((res, rej) => { conn.get(url.path).then((stream) => { try { res(stream); } catch (e) { rej(e); } }).catch((err) => { rej(err); }); }); }); // create temp file wf.next((ctx) => { let stream: NodeJS.ReadableStream = ctx.previousValue; return new Promise<any>((res, rej) => { TMP.tmpName({ keep: true, }, (err, tempFile) => { if (err) { rej(err); } else { res({ deleteTempFile: () => { return new Promise<any>((res2, rej2) => { FS.exists(tempFile, (exists) => { if (exists) { FS.unlink(tempFile, (err) => { if (err) { rej2(err); } else { res2(); } }); } else { res2(); } }); }); }, tempFile: tempFile, stream: stream, }); } }); }); }); // write to temp file wf.next((ctx) => { let deleteTempFile: () => Promise<any> = ctx.previousValue.deleteTempFile; let stream: NodeJS.ReadableStream = ctx.previousValue.stream; let tempFile: string = ctx.previousValue.tempFile; return new Promise<any>((res, rej) => { let downloadCompleted = (err: any) => { if (err) { deleteTempFile().then(() => { rej(err); }).catch((e) => { //TODO: log rej(err); }); } else { res({ deleteTempFile: deleteTempFile, tempFile: tempFile, }); } }; try { stream.once('error', (err) => { if (err) { downloadCompleted(err); } }); let pipe = stream.pipe(FS.createWriteStream(tempFile)); pipe.once('error', (err) => {; if (err) { downloadCompleted(err); } }); stream.once('end', () => { downloadCompleted(null); }); } catch (e) { downloadCompleted(e); } }); }); wf.next((ctx) => { let deleteTempFile: () => Promise<any> = ctx.previousValue.deleteTempFile; let tempFile: string = ctx.previousValue.tempFile; return new Promise<any>((res, rej) => { let readCompleted = (err: any, d?: Buffer) => { if (err) { rej(err); } else { res({ data: d, fileName: fileName, }); } }; FS.readFile(tempFile, (err, data) => { deleteTempFile().then(() => { readCompleted(err, data); }).catch((e) => { //TODO: log readCompleted(err, data); }); }); }); }); } break; case 'http:': case 'https:': // web resource { wf.next((ctx) => { return new Promise<any>((resolve, reject) => { try { let requestOpts: HTTP.RequestOptions = { hostname: url.hostname, path: url.path, method: 'GET', }; let setHeader = (name: string, value: string) => { if (isNullOrUndefined(requestOpts.headers)) { requestOpts.headers = {}; } requestOpts.headers[name] = value; }; // authorization? if (!isNullUndefinedOrEmptyString(url.auth)) { let b64Auth = (new Buffer(toStringSafe(url.auth))).toString('base64'); setHeader('Authorization', 'Basic ' + b64Auth); } let requestHandler = (resp: HTTP.IncomingMessage) => { let mime: string; if (resp.headers) { for (let h in resp.headers) { if ('content-type' === normalizeString(h)) { mime = normalizeString(resp.headers[h]); break; } } } readHttpBody(resp).then((data) => { resolve({ data: data, fileName: fileName, mime: mime, }); }).catch((err) => { reject(err); }); }; let requestFactory: (options: HTTP.RequestOptions, callback?: (res: HTTP.IncomingMessage) => void) => HTTP.ClientRequest; switch (protocol) { case 'https:': requestFactory = HTTPs.request; requestOpts.protocol = 'https:'; requestOpts.port = 443; break; default: // http requestFactory = HTTP.request; requestOpts.protocol = 'http:'; requestOpts.port = 80; break; } if (!isNullUndefinedOrEmptyString(url.port)) { requestOpts.port = parseInt(toStringSafe(url.port).trim()); } if (requestFactory) { let request = requestFactory(requestOpts, requestHandler); request.once('error', (err) => { reject(err); }); request.end(); } else { resolve(null); } } catch (e) { reject(e); } }); }); } break; case 'file:': default: isLocal = true; break; } } if (isLocal) { // handle as local file let filePath = src; if (!Path.isAbsolute(filePath)) { filePath = Path.join(deploy_workspace.getRootPath(), filePath); } filePath = Path.resolve(filePath); let fileName = Path.basename(filePath); wf.next((ctx) => { return new Promise<any>((resolve, reject) => { try { FS.readFile(filePath, (err, data) => { if (err) { reject(err); } else { resolve({ data: data, fileName: fileName, }); } }); } catch (e) { reject(e); } }); }); } // check if binary file wf.next((ctx) => { let data: Buffer = ctx.previousValue.data; if (!data) { data = Buffer.alloc(0); } let fileName: string = ctx.previousValue.fileName; let mime: string = ctx.previousValue.mime; return new Promise<any>((resolve, reject) => { isBinaryContent(data).then((isBinary) => { resolve({ data: data, fileName: fileName, isBinary: isBinary, mime: mime, }); }).catch((err) => { reject(err); }); }); }); wf.next((ctx) => { let data: Buffer = ctx.previousValue.data; let fileName: string = ctx.previousValue.fileName; let isBinary: boolean = ctx.previousValue.isBinary; let getMimeSafe = (m: any): string => { m = normalizeString(m); if ('' === m) { m = 'application/octet-stream'; } return m; }; // mime let mime = normalizeString(ctx.previousValue.mime); if ('' === mime) { // try to detect... if (isBinary) { try { let type = FileType(data); if (type) { mime = type.mime; } } catch (e) { /* TODO: log */ } } mime = getMimeSafe(mime); if ('application/octet-stream' === mime) { if (!isNullUndefinedOrEmptyString(fileName)) { try { mime = detectMimeByFilename(fileName); } catch (e) { /* TODO: log */ } } } } if (mime.indexOf(';') > -1) { mime = normalizeString(mime.split(';')[0]); } let result: DownloadResult = { data: data, mime: getMimeSafe(mime), name: fileName, }; ctx.result = result; }); wf.start().then((result: DownloadResult) => { completed(null, result); }).catch((err) => { completed(err); }); } catch (e) { completed(e); } }); } /** * Loads a module. * * @param {string} file The path of the module's file. * @param {boolean} useCache Use cache or not. * * @return {TModule} The loaded module. */ export function loadModule<TModule>(file: string, useCache: boolean = false): TModule { if (!Path.isAbsolute(file)) { file = Path.join(deploy_workspace.getRootPath(), file); } file = Path.resolve(file); let stats = FS.lstatSync(file); if (!stats.isFile()) { throw new Error(i18.t('isNo.file', file)); } if (!useCache) { delete require.cache[file]; // remove from cache } return require(file); } /** * Loads a script based command module. * * @param {string} file The path of the module's file. * @param {boolean} useCache Use cache or not. * * @return {deploy_contracts.ScriptCommandModule} The loaded module. */ export function loadScriptCommandModule(file: string, useCache: boolean = false): deploy_contracts.ScriptCommandModule { return loadModule<deploy_contracts.ScriptCommandModule>(file, useCache); } /** * Loads a "validator" module. * * @param {string} file The path of the module's file. * @param {boolean} useCache Use cache or not. * * @return {deploy_contracts.ValidatorModule<T>} The loaded module. */ export function loadValidatorModule<T>(file: string, useCache: boolean = false): deploy_contracts.ValidatorModule<T> { return loadModule<deploy_contracts.ValidatorModule<T>>(file, useCache); } /** * Logs a message. * * @param {any} msg The message to log. */ export function log(msg: any) { let now = Moment(); msg = toStringSafe(msg); console.log(`[vs-deploy :: ${now.format('YYYY-MM-DD HH:mm:ss')}] => ${msg}`); } /** * Creates a storage of nvironment variables for a process object. * * @param {deploy_contracts.ProcessObject} obj The object from where to create the storage from. * @param {(deploy_values.ValueBase|deploy_values.ValueBase[])} [values] The optional list of values to use. * * @returns {{[name: string]: any}} The created storage. */ export function makeEnvVarsForProcess(obj: deploy_contracts.ProcessObject, values?: deploy_values.ValueBase | deploy_values.ValueBase[]): { [name: string]: any } { values = asArray(values).filter(x => x); let envVars: { [name: string]: any }; if (toBooleanSafe(obj.useEnvVarsOfWorkspace)) { if (process.env) { envVars = {}; for (let prop in process.env) { envVars[prop] = process.env[prop]; } } } if (obj) { if (obj.envVars) { if (!envVars) { envVars = {}; } for (let prop in obj.envVars) { let name = toStringSafe(prop).trim(); let val = obj.envVars[prop]; let usePlaceholders: boolean; if ('boolean' === typeof obj.noPlaceholdersForTheseVars) { usePlaceholders = !obj.noPlaceholdersForTheseVars; } else { usePlaceholders = asArray(obj.noPlaceholdersForTheseVars) .map(x => toStringSafe(prop).trim()) .indexOf(name) < 0; } if (usePlaceholders) { val = deploy_values.replaceWithValues(values, val); } if ('' === val) { val = undefined; } envVars[name] = val; } } } return envVars; } /** * Merge inheritable objects. * * @param {T|T[]} objs The objects to merge. * * @return {T[]} The new and normalized list of merged objects. */ export function mergeInheritables<T extends deploy_contracts.Inheritable>(objs: T | T[]): T[] { let clonedObjects = asArray(objs).filter(o => o) .map(o => cloneObject(o)); return clonedObjects.map(o => { let inheritFrom = asArray(o.inheritFrom).map(on => normalizeString(on)); delete o['inheritFrom']; if (inheritFrom.length > 0) { clonedObjects.filter(baseObj => baseObj !== o).forEach(baseObj => { if (inheritFrom.indexOf(normalizeString(baseObj.name)) > -1) { // merge current with base o = cloneObject(Object.assign(cloneObject(baseObj), cloneObject(o))); } }); } return o; }); } /** * Normalizes a value as string so that is comparable. * * @param {any} val The value to convert. * @param {(str: string) => string} [normalizer] The custom normalizer. * * @return {string} The normalized value. */ export function normalizeString(val: any, normalizer?: (str: string) => string): string { if (!normalizer) { normalizer = (str) => str.toLowerCase().trim(); } return normalizer(toStringSafe(val)); } /** * Opens a target. * * @param {string} target The target to open. * @param {OpenOptions} [opts] The custom options to set. * * @param {Promise<ChildProcess.ChildProcess>} The promise. */ export function open(target: string, opts?: OpenOptions): Promise<ChildProcess.ChildProcess> { let me = this; if (!opts) { opts = {}; } opts.wait = toBooleanSafe(opts.wait, true); return new Promise((resolve, reject) => { let completed = (err?: any, cp?: ChildProcess.ChildProcess) => { if (err) { reject(err); } else { resolve(cp); } }; try { if (typeof target !== 'string') { throw new Error('Expected a `target`'); } let cmd: string; let appArgs: string[] = []; let args: string[] = []; let cpOpts: ChildProcess.SpawnOptions = { cwd: opts.cwd || deploy_workspace.getRootPath(), env: opts.env, }; if (Array.isArray(opts.app)) { appArgs = opts.app.slice(1); opts.app = opts.app[0]; } if (process.platform === 'darwin') { // Apple cmd = 'open'; if (opts.wait) { args.push('-W'); } if (opts.app) { args.push('-a', opts.app); } } else if (process.platform === 'win32') { // Microsoft cmd = 'cmd'; args.push('/c', 'start', '""'); target = target.replace(/&/g, '^&'); if (opts.wait) { args.push('/wait'); } if (opts.app) { args.push(opts.app); } if (appArgs.length > 0) { args = args.concat(appArgs); } } else { // Unix / Linux if (opts.app) { cmd = opts.app; } else { cmd = Path.join(__dirname, 'xdg-open'); } if (appArgs.length > 0) { args = args.concat(appArgs); } if (!opts.wait) { // xdg-open will block the process unless // stdio is ignored even if it's unref'd cpOpts.stdio = 'ignore'; } } args.push(target); if (process.platform === 'darwin' && appArgs.length > 0) { args.push('--args'); args = args.concat(appArgs); } let cp = ChildProcess.spawn(cmd, args, cpOpts); if (opts.wait) { cp.once('error', (err) => { completed(err); }); cp.once('close', function (code) { if (code > 0) { completed(new Error('Exited with code ' + code)); return; } completed(null, cp); }); } else { cp.unref(); completed(null, cp); } } catch (e) { completed(e); } }); } /** * Opens a HTML document in a new tab for a document storage. * * @param {deploy_contracts.Document[]} storage The storage to open for. * @param {string} html The HTML document (source code). * @param {string} [title] The custom title for the tab. * @param {any} [id] The custom ID for the document in the storage. * * @returns {Promise<any>} The promise. */ export function openHtmlDocument(storage: deploy_contracts.Document[], html: string, title?: string, id?: any): Promise<any> { return new Promise((resolve, reject) => { let completed = createSimplePromiseCompletedAction(resolve, reject); try { let body: Buffer; let enc = 'utf8'; if (!isNullOrUndefined(html)) { body = new Buffer(toStringSafe(html), enc); } if (isNullOrUndefined(id)) { id = 'vsdGlobalHtmlDocs::c6bda982-419e-4a28-8412-5822df5223d4::' + (++nextHtmlDocId); } let doc: deploy_contracts.Document = { body: body, encoding: enc, id: id, mime: 'text/html', }; if (!isEmptyString(title)) { doc.title = toStringSafe(title).trim(); } if (storage) { storage.push(doc); } vscode.commands.executeCommand('extension.deploy.openHtmlDoc', doc).then((result: any) => { completed(null, result); }, (err) => { completed(err); }); } catch (e) { completed(e); } }); } /** * Parse a value to use as "target type" value. * * @param {string} [str] The input value. * * @returns {string} The output value. */ export function parseTargetType(str: string): string { return normalizeString(str); } /** * Reads the content of the HTTP request body. * * @param {HTTP.IncomingMessag} msg The HTTP message with the body. * * @returns {Promise<Buffer>} The promise. */ export function readHttpBody(msg: HTTP.IncomingMessage): Promise<Buffer> { return new Promise<Buffer>((resolve, reject) => { let buff: Buffer; let completedInvoked = false; let dataListener: (chunk: Buffer | string) => void; let completed = (err: any) => { if (completedInvoked) { return; } completedInvoked = true; if (dataListener) { try { msg.removeListener('data', dataListener); } catch (e) { log(i18.t('errors.withCategory', 'helpers.readHttpBody()', e)); } } if (err) { reject(err); } else { resolve(buff); } }; dataListener = (chunk: Buffer | string) => { try { if (chunk && chunk.length > 0) { if ('string' === typeof chunk) { chunk = new Buffer(chunk); } buff = Buffer.concat([ buff, chunk ]); } } catch (e) { completed(e); } }; try { buff = Buffer.alloc(0); msg.once('error', (err) => { if (err) { completed(err); } }); msg.on('data', dataListener); msg.once('end', () => { resolve(buff); }); } catch (e) { completed(e); } }); } /** * Reads a number of bytes from a socket. * * @param {Net.Socket} socket The socket. * @param {Number} numberOfBytes The amount of bytes to read. * * @return {Promise<Buffer>} The promise. */ export function readSocket(socket: Net.Socket, numberOfBytes: number): Promise<Buffer> { return new Promise<Buffer>((resolve, reject) => { try { let buff: Buffer = socket.read(numberOfBytes); if (null === buff) { socket.once('readable', function() { readSocket(socket, numberOfBytes).then((b) => { resolve(b); }, (err) => { reject(err); }); }); } else { resolve(buff); } } catch (e) { reject(e); } }); } /** * Removes documents from a storage. * * @param {deploy_contracts.Document|deploy_contracts.Document[]} docs The document(s) to remove. * @param {deploy_contracts.Document[]} storage The storage. * * @return {deploy_contracts.Document[]} The removed documents. */ export function removeDocuments(docs: deploy_contracts.Document | deploy_contracts.Document[], storage: deploy_contracts.Document[]): deploy_contracts.Document[] { let ids = asArray(docs).filter(x => x) .map(x => x.id); let removed = []; if (storage) { for (let i = 0; i < storage.length; ) { let d = storage[i]; if (ids.indexOf(d.id) > -1) { removed.push(d); storage.splice(i, 1); } else { ++i; } } } return removed; } /** * Replaces all occurrences of a string. * * @param {string} str The input string. * @param {string} searchValue The value to search for. * @param {string} replaceValue The value to replace 'searchValue' with. * * @return {string} The output string. */ export function replaceAllStrings(str: string, searchValue: string, replaceValue: string) { str = toStringSafe(str); searchValue = toStringSafe(searchValue); replaceValue = toStringSafe(replaceValue); return str.split(searchValue) .join(replaceValue); } /** * Sorts a list of packages. * * @param {deploy_contracts.DeployPackage[]} pkgs The input list. * @param {deploy_contracts.ValueProvider<string>} [nameProvider] The custom function that provides the name of the machine. * * @return {deploy_contracts.DeployPackage[]} The sorted list. */ export function sortPackages(pkgs: deploy_contracts.DeployPackage[], nameProvider?: deploy_contracts.ValueProvider<string>): deploy_contracts.DeployPackage[] { if (!pkgs) { pkgs = []; } return pkgs.filter(x => x) .map((x, i) => { return { index: i, level0: getSortValue(x, nameProvider), // first sort by "sortOrder" level1: toStringSafe(x.name).toLowerCase().trim(), // then by "name" value: x, }; }) .sort((x, y) => { let comp0 = compareValuesBy(x, y, t => t.level0); if (0 !== comp0) { return comp0; } let comp1 = compareValuesBy(x, y, t => t.level1); if (0 !== comp1) { return comp1; } return compareValuesBy(x, y, t => t.index); }) .map(x => x.value); } /** * Sorts a list of targets. * * @param {deploy_contracts.DeployTarget[]} targets The input list. * @param @param {deploy_contracts.ValueProvider<string>} [nameProvider] The custom function that provides the name of the machine. * * @return {deploy_contracts.DeployTarget[]} The sorted list. */ export function sortTargets(targets: deploy_contracts.DeployTarget[], nameProvider?: deploy_contracts.ValueProvider<string>): deploy_contracts.DeployTarget[] { if (!targets) { targets = []; } return targets.filter(x => x) .map((x, i) => { return { index: i, level0: getSortValue(x, nameProvider), // first sort by "sortOrder" level1: toStringSafe(x.name).toLowerCase().trim(), // then by "name" value: x, }; }) .sort((x, y) => { let comp0 = compareValuesBy(x, y, t => t.level0); if (0 !== comp0) { return comp0; } let comp1 = compareValuesBy(x, y, t => t.level1); if (0 !== comp1) { return comp1; } return compareValuesBy(x, y, t => t.index); }) .map(x => x.value); } /** * Returns an array like object as new array. * * @param {ArrayLike<T>} arr The input object. * @param {boolean} [normalize] Returns an empty array, if input object is (null) / undefined. * * @return {T[]} The input object as array. */ export function toArray<T>(arr: ArrayLike<T>, normalize = true): T[] { if (isNullOrUndefined(arr)) { if (toBooleanSafe(normalize)) { return []; } return <any>arr; } let newArray: T[] = []; for (let i = 0; i < arr.length; i++) { newArray.push(arr[i]); } return newArray; } /** * Converts a value to a boolean. * * @param {any} val The value to convert. * @param {any} defaultValue The value to return if 'val' is (null) or (undefined). * * @return {boolean} The converted value. */ export function toBooleanSafe(val: any, defaultValue: any = false): boolean { if (isNullOrUndefined(val)) { return defaultValue; } return !!val; } /** * Keeps sure to return a "data transformer" that is NOT (null) or (undefined). * * @param {deploy_contracts.DataTransformer} transformer The input value. * * @return {deploy_contracts.DataTransformer} The output value. */ export function toDataTransformerSafe(transformer: deploy_contracts.DataTransformer): deploy_contracts.DataTransformer { if (!transformer) { // use "dummy" transformer transformer = (ctx) => { return new Promise<Buffer>((resolve, reject) => { resolve(ctx.data); }); }; } return transformer; } /** * Tries to convert a file path to a relative path. * * @param {string} path The path to convert. * @param {string} [baseDir] The custom base / root directory to use. * * @return {string | false} The relative path or (false) if not possible. */ export function toRelativePath(path: string, baseDir?: string): string | false { let result: string | false = false; if (isEmptyString(baseDir)) { baseDir = deploy_workspace.getRootPath(); } else { if (!Path.isAbsolute(baseDir)) { baseDir = Path.join(deploy_workspace.getRootPath(), baseDir); } baseDir = Path.resolve(baseDir); } try { let normalizedPath = replaceAllStrings(path, Path.sep, '/'); let wsRootPath = replaceAllStrings(baseDir, Path.sep, '/'); if ('' !== wsRootPath) { if (FS.existsSync(wsRootPath)) { if (FS.lstatSync(wsRootPath).isDirectory()) { if (0 === normalizedPath.indexOf(wsRootPath)) { result = normalizedPath.substr(wsRootPath.length); result = replaceAllStrings(result, Path.sep, '/'); } } } } } catch (e) { log(i18.t('errors.withCategory', 'helpers.toRelativePath()', e)); } return result; } /** * Tries to convert a file path to a relative path * by using the mappings of a target. * * @param {string} path The path to convert. * @param {deploy_contracts.DeployTarget} target The target. * @param {string} [baseDir] The custom base / root directory to use. * * @return {string|false} The relative path or (false) if not possible. */ export function toRelativeTargetPath(path: string, target: deploy_contracts.DeployTarget, baseDir?: string): string | false { return toRelativeTargetPathWithValues(path, target, [], baseDir); } /** * Tries to convert a file path to a relative path * by using the mappings of a target and placeholders / values. * * @param {string} path The path to convert. * @param {deploy_contracts.DeployTarget} target The target. * @param {deploy_contracts.ObjectWithNameAndValue|deploy_contracts.ObjectWithNameAndValue[]} values The values to use. * @param {string} [baseDir] The custom base / root directory to use. * * @return {string|false} The relative path or (false) if not possible. */ export function toRelativeTargetPathWithValues(path: string, target: deploy_contracts.DeployTarget, values: deploy_contracts.ObjectWithNameAndValue | deploy_contracts.ObjectWithNameAndValue[], baseDir?: string): string | false { let relativePath = toRelativePath(path, baseDir); if (false === relativePath) { return relativePath; } let normalizeDirPath = (dir: string): string => { let normalizedDir = toStringSafe(dir).trim(); normalizedDir = replaceAllStrings(normalizedDir, Path.sep, '/'); if (normalizedDir.lastIndexOf('/') !== (normalizedDir.length - 1)) { normalizedDir += '/'; // append ending "/" char } if (normalizedDir.indexOf('/') !== 0) { normalizedDir = '/' + normalizedDir; // append leading "/" char } return normalizedDir; }; let allMappings = asArray(target.mappings).filter(x => x); for (let i = 0; i < allMappings.length; i++) { let mapping = allMappings[i]; let sourceDir: string; let targetDir = toStringSafe(mapping.target); let doesMatch = false; if (toBooleanSafe(mapping.isRegEx)) { let r = new RegExp(toStringSafe(mapping.source), 'g'); let match = r.exec(relativePath); if (match) { sourceDir = match[0]; // RegEx matches let matchValues: deploy_values.ValueBase[] = []; for (let i = 0; i < match.length; i++) { matchValues.push(new deploy_values.StaticValue({ name: '' + i, value: match[i], })); } sourceDir = deploy_values.replaceWithValues(values, sourceDir); sourceDir = normalizeDirPath(sourceDir); // apply RegEx matches to targetDir targetDir = deploy_values.replaceWithValues(matchValues, targetDir); doesMatch = true; } } else { sourceDir = deploy_values.replaceWithValues(values, mapping.source); sourceDir = normalizeDirPath(sourceDir); doesMatch = 0 === relativePath.indexOf(sourceDir); } targetDir = normalizeDirPath(targetDir); if (doesMatch) { // is matching => rebuild path relativePath = Path.join(targetDir, relativePath.substr(sourceDir.length)); // remove the source prefix break; } } return replaceAllStrings(relativePath, Path.sep, '/'); } /** * Converts a value to a string that is NOT (null) or (undefined). * * @param {any} str The input value. * @param {any} defValue The default value. * * @return {string} The output value. */ export function toStringSafe(str: any, defValue: any = ''): string { if (isNullOrUndefined(str)) { str = ''; } str = '' + str; if (!str) { str = defValue; } return str; } /** * Keeps sure to return a "validator" that is NOT (null) or (undefined). * * @param {deploy_contracts.Validator<T>} validator The input value. * * @return {deploy_contracts.Validator<T>} The output value. */ export function toValidatorSafe<T>(validator: deploy_contracts.Validator<T>): deploy_contracts.Validator<T> { if (!validator) { // use "dummy" validator validator = (): Promise<boolean> => { return new Promise<boolean>((resolve) => { resolve(true); }); }; } return validator; } /** * Tries to clear a timeout. * * @param {NodeJS.Timer} timeoutId The timeout (ID). * * @return {boolean} Operation was successful or not. */ export function tryClearTimeout(timeoutId: NodeJS.Timer): boolean { try { if (!isNullOrUndefined(timeoutId)) { clearTimeout(timeoutId); } return true; } catch (e) { log(i18.t('errors.withCategory', 'helpers.tryClearTimeout()', e)); return false; } } /** * Tries to dispose an object. * * @param {vscode.Disposable} obj The object to dispose. * * @return {boolean} Operation was successful or not. */ export function tryDispose(obj: vscode.Disposable): boolean { try { if (obj) { obj.dispose(); } return true; } catch (e) { log(i18.t('errors.withCategory', 'helpers.tryDispose()', e)); return false; } } /** * Extracts the query parameters of an URI to an object. * * @param {vscode.Uri} uri The URI. * * @return {Object} The parameters of the URI as object. */ export function uriParamsToObject(uri: vscode.Uri): Object { if (!uri) { return uri; } let params: any; if (!isEmptyString(uri.query)) { // s. https://css-tricks.com/snippets/jquery/get-query-params-object/ params = uri.query.replace(/(^\?)/,'') .split("&") .map(function(n) { return n = n.split("="), this[normalizeString(n[0])] = toStringSafe(decodeURIComponent(n[1])), this} .bind({}))[0]; } if (!params) { params = {}; } return params; }
the_stack
import { module, test } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { setupMirage } from 'ember-cli-mirage/test-support'; import { MirageTestContext } from 'ember-cli-mirage/test-support'; import sinon from 'sinon'; import WorkflowPersistence from '@cardstack/web-client/services/workflow-persistence'; import { click, currentURL, visit, waitFor } from '@ember/test-helpers'; import Layer2TestWeb3Strategy from '@cardstack/web-client/utils/web3-strategies/test-layer2'; import Layer1TestWeb3Strategy from '@cardstack/web-client/utils/web3-strategies/test-layer1'; import { BN } from 'bn.js'; import { buildState } from '@cardstack/web-client/models/workflow/workflow-session'; import { createDepotSafe, createSafeToken, } from '@cardstack/web-client/utils/test-factories'; import { MILESTONE_TITLES, WORKFLOW_VERSION, } from '@cardstack/web-client/components/card-pay/withdrawal-workflow'; import Layer2Network from '@cardstack/web-client/services/layer2-network'; interface Context extends MirageTestContext {} const withdrawalSafeAddress = '0x2Fe77303eBc9F6375852bBEe1bd43FC0fa1e7B08'; module('Acceptance | withdrawal persistence', function (hooks) { setupApplicationTest(hooks); setupMirage(hooks); let workflowPersistenceService: WorkflowPersistence; hooks.beforeEach(async function () { workflowPersistenceService = this.owner.lookup( 'service:workflow-persistence' ); let layer1AccountAddress = '0xaCD5f5534B756b856ae3B2CAcF54B3321dd6654Fb6'; let layer1Service = this.owner.lookup('service:layer1-network') .strategy as Layer1TestWeb3Strategy; layer1Service.test__simulateAccountsChanged( [layer1AccountAddress], 'metamask' ); layer1Service.test__simulateBalances({ defaultToken: new BN('2141100000000000000'), dai: new BN('250500000000000000000'), card: new BN('10000000000000000000000'), }); let layer2AccountAddress = '0x182619c6Ea074C053eF3f1e1eF81Ec8De6Eb6E44'; let layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ address: withdrawalSafeAddress, owners: [layer2AccountAddress], tokens: [ createSafeToken('CARD.CPXD', '1000000000000000000'), createSafeToken('DAI.CPXD', '4215997042758579167'), ], }), ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); workflowPersistenceService.clear(); }); test('Generates a flow uuid query parameter used as a persistence identifier and can be dismissed via the header button', async function (this: Context, assert) { await visit('/card-pay/deposit-withdrawal'); await click('[data-test-workflow-button="withdrawal"]'); assert.equal( new URL('http://domain.test/' + currentURL()).searchParams.get('flow-id') ?.length, 22 ); await click('[data-test-return-to-dashboard]'); assert.dom('[data-test-workflow-thread]').doesNotExist(); }); module('Restoring from a previously saved state', function () { test('it restores an unfinished workflow', async function (this: Context, assert) { const state = buildState({ withdrawalToken: 'DAI.CPXD', withdrawnAmount: new BN('1000000000000000000'), completedMilestonesCount: 5, layer2BlockHeightBeforeBridging: new BN('22867914'), milestonesCount: 6, minimumBalanceForWithdrawalClaim: new BN('290000000000000'), relayTokensTxnHash: '0x08ef93a1ac2911210c8e1b351dd90aa00f033b3658abdfb449eda75f84e9f501', bridgeValidationResult: { encodedData: '0x00050000249bfc2f3cc8d68f6b6bf7230ea0a8ed853de7310000000000000b0816a80598dd2f143cfbf091638ce3fb02c9135528366b4cc64d30849568af65522de3a68ea6cc78ce000249f00101004d2a125e4cfb0000000000000000000000004f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa000000000000000000000000511ec1515cdc483d57bc1f38e1325c221debd1e40000000000000000000000000000000000000000000000000de0b6b3a7640000', messageId: '0x00050000249bfc2f3cc8d68f6b6bf7230ea0a8ed853de7310000000000000b08', }, withdrawalSafe: withdrawalSafeAddress, meta: { version: WORKFLOW_VERSION, completedCardNames: [ 'LAYER1_CONNECT', 'CHECK_BALANCE', 'LAYER2_CONNECT', 'CHOOSE_BALANCE', 'TRANSACTION_AMOUNT', 'TRANSACTION_STATUS', ], createdAt: '1627908405', }, }); workflowPersistenceService.persistData('abc123', { name: 'WITHDRAWAL', state, }); await visit( '/card-pay/deposit-withdrawal?flow=withdrawal&flow-id=abc123' ); assert.dom('[data-test-milestone="0"]').exists(); // L1 assert.dom('[data-test-milestone="1"]').exists(); // Check ETH balance assert.dom('[data-test-milestone="2"]').exists(); // Connect L2 wallet assert.dom('[data-test-milestone="3"]').exists(); // Withdraw from L2 assert.dom('[data-test-milestone="4"]').exists(); // Bridge to L1 assert.dom('[data-test-milestone="5"]').exists(); // Claim assert.dom('[data-test-claim-button]').exists(); assert .dom('[data-test-milestone="5"] [data-test-balance-display-amount]') .hasText('1.00 DAI.CPXD'); assert .dom('[data-test-withdrawal-next-step="new-withdrawal"]') .doesNotExist(); }); test('it restores a finished workflow', async function (this: Context, assert) { const state = buildState({ withdrawalToken: 'DAI.CPXD', withdrawnAmount: new BN('1000000000000000000'), layer2BlockHeightBeforeBridging: new BN('22867914'), minimumBalanceForWithdrawalClaim: new BN('290000000000000'), relayTokensTxnHash: '0x08ef93a1ac2911210c8e1b351dd90aa00f033b3658abdfb449eda75f84e9f501', bridgeValidationResult: { encodedData: '0x00050000249bfc2f3cc8d68f6b6bf7230ea0a8ed853de7310000000000000b0816a80598dd2f143cfbf091638ce3fb02c9135528366b4cc64d30849568af65522de3a68ea6cc78ce000249f00101004d2a125e4cfb0000000000000000000000004f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa000000000000000000000000511ec1515cdc483d57bc1f38e1325c221debd1e40000000000000000000000000000000000000000000000000de0b6b3a7640000', messageId: '0x00050000249bfc2f3cc8d68f6b6bf7230ea0a8ed853de7310000000000000b08', }, withdrawalSafe: withdrawalSafeAddress, meta: { version: WORKFLOW_VERSION, completedMilestonesCount: 6, milestonesCount: 6, completedCardNames: [ 'LAYER1_CONNECT', 'CHECK_BALANCE', 'LAYER2_CONNECT', 'CHOOSE_BALANCE', 'TRANSACTION_AMOUNT', 'TRANSACTION_STATUS', 'TOKEN_CLAIM', 'TRANSACTION_CONFIRMED', 'EPILOGUE_SAFE_BALANCE_CARD', ], }, didClaimTokens: true, }); workflowPersistenceService.persistData('abc123', { name: 'WITHDRAWAL', state, }); await visit( '/card-pay/deposit-withdrawal?flow=withdrawal&flow-id=abc123' ); assert.dom('[data-test-milestone="0"]').exists(); // L1 assert.dom('[data-test-milestone="1"]').exists(); // Check ETH balance assert.dom('[data-test-milestone="2"]').exists(); // Connect L2 wallet assert.dom('[data-test-milestone="3"]').exists(); // Withdraw from L2 assert.dom('[data-test-milestone="4"]').exists(); // Bridge to L1 assert.dom('[data-test-milestone="5"]').exists(); // Claim assert.dom('[data-test-claim-button]').doesNotExist(); assert .dom( '[data-test-withdrawal-transaction-confirmed-from] [data-test-balance-display-amount]' ) .hasText('1.00 DAI.CPXD'); assert .dom( '[data-test-withdrawal-transaction-confirmed-to] [data-test-balance-display-amount]' ) .hasText('1.00 DAI'); assert.dom('[data-test-withdrawal-next-step="new-withdrawal"]').exists(); }); test('it restores a canceled workflow', async function (this: Context, assert) { const state = buildState({ withdrawalToken: 'DAI.CPXD', withdrawnAmount: new BN('1000000000000000000'), layer2BlockHeightBeforeBridging: new BN('22867914'), minimumBalanceForWithdrawalClaim: new BN('290000000000000'), relayTokensTxnHash: '0x08ef93a1ac2911210c8e1b351dd90aa00f033b3658abdfb449eda75f84e9f501', bridgeValidationResult: { encodedData: '0x00050000249bfc2f3cc8d68f6b6bf7230ea0a8ed853de7310000000000000b0816a80598dd2f143cfbf091638ce3fb02c9135528366b4cc64d30849568af65522de3a68ea6cc78ce000249f00101004d2a125e4cfb0000000000000000000000004f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa000000000000000000000000511ec1515cdc483d57bc1f38e1325c221debd1e40000000000000000000000000000000000000000000000000de0b6b3a7640000', messageId: '0x00050000249bfc2f3cc8d68f6b6bf7230ea0a8ed853de7310000000000000b08', }, withdrawalSafe: withdrawalSafeAddress, meta: { version: WORKFLOW_VERSION, completedMilestonesCount: 5, milestonesCount: 6, completedCardNames: [ 'LAYER1_CONNECT', 'CHECK_BALANCE', 'LAYER2_CONNECT', 'CHOOSE_BALANCE', 'TRANSACTION_AMOUNT', 'TRANSACTION_STATUS', ], isCanceled: true, cancelationReason: 'DISCONNECTED', }, }); workflowPersistenceService.persistData('abc123', { name: 'WITHDRAWAL', state, }); await visit( '/card-pay/deposit-withdrawal?flow=withdrawal&flow-id=abc123' ); assert.dom('[data-test-milestone="0"]').exists(); // L1 assert.dom('[data-test-milestone="1"]').exists(); // Check ETH balance assert.dom('[data-test-milestone="2"]').exists(); // Connect L2 wallet assert.dom('[data-test-milestone="3"]').exists(); // Withdraw from L2 assert.dom('[data-test-milestone="4"]').exists(); // Bridge to L1 assert .dom('[data-test-cancelation]') .includesText( 'It looks like your wallet(s) got disconnected. If you still want to withdraw tokens, please start again by connecting your wallet(s).' ); await waitFor( '[data-test-workflow-default-cancelation-restart="withdrawal"]' ); assert .dom('[data-test-workflow-default-cancelation-restart="withdrawal"]') .exists(); }); test('it cancels a persisted flow when Layer 1 wallet address is different', async function (this: Context, assert) { const state = buildState({ meta: { version: WORKFLOW_VERSION, completedCardNames: [ 'LAYER1_CONNECT', 'CHECK_BALANCE', 'LAYER2_CONNECT', 'CHOOSE_BALANCE', 'TRANSACTION_AMOUNT', 'TRANSACTION_STATUS', ], }, layer1WalletAddress: '0xaaaaaaaaaaaaaaa', // Differs from layer1WalletAddress set in beforeEach }); workflowPersistenceService.persistData('abc123', { name: 'WITHDRAWAL', state, }); await visit( '/card-pay/deposit-withdrawal?flow=withdrawal&flow-id=abc123' ); assert.dom('[data-test-milestone="0"]').doesNotExist(); assert.dom('[data-test-milestone="1"]').doesNotExist(); assert.dom('[data-test-milestone="2"]').doesNotExist(); assert.dom('[data-test-milestone="3"]').doesNotExist(); assert.dom('[data-test-milestone="4"]').doesNotExist(); assert .dom('[data-test-cancelation]') .includesText( 'You attempted to restore an unfinished workflow, but you changed your Layer 1 wallet address. Please restart the workflow.' ); }); test('it cancels a persisted flow when card wallet address is different', async function (this: Context, assert) { const state = buildState({ meta: { version: WORKFLOW_VERSION, completedCardNames: [ 'LAYER1_CONNECT', 'CHECK_BALANCE', 'LAYER2_CONNECT', 'CHOOSE_BALANCE', 'TRANSACTION_AMOUNT', 'TRANSACTION_STATUS', ], }, layer2WalletAddress: '0xaaaaaaaaaaaaaaa', // Differs from layer2WalletAddress set in beforeEach }); workflowPersistenceService.persistData('abc123', { name: 'WITHDRAWAL', state, }); await visit( '/card-pay/deposit-withdrawal?flow=withdrawal&flow-id=abc123' ); assert.dom('[data-test-milestone="0"]').doesNotExist(); assert.dom('[data-test-milestone="1"]').doesNotExist(); assert.dom('[data-test-milestone="2"]').doesNotExist(); assert.dom('[data-test-milestone="3"]').doesNotExist(); assert.dom('[data-test-milestone="4"]').doesNotExist(); assert .dom('[data-test-cancelation]') .includesText( 'You attempted to restore an unfinished workflow, but you changed your Card Wallet address. Please restart the workflow.' ); }); test('it restores the workflow and resumes the transaction when restoring during withdraw step', async function (this: Context, assert) { const state = buildState({ withdrawalToken: 'DAI.CPXD', withdrawnAmount: new BN('1000000000000000000'), layer2BlockHeightBeforeBridging: new BN('22867914'), minimumBalanceForWithdrawalClaim: new BN('290000000000000'), relayTokensTxnHash: '0x08ef93a1ac2911210c8e1b351dd90aa00f033b3658abdfb449eda75f84e9f501', withdrawalSafe: withdrawalSafeAddress, meta: { version: WORKFLOW_VERSION, completedMilestonesCount: 5, milestonesCount: 6, completedCardNames: [ 'LAYER1_CONNECT', 'CHECK_BALANCE', 'LAYER2_CONNECT', 'CHOOSE_BALANCE', ], }, }); workflowPersistenceService.persistData('abc123', { name: 'WITHDRAWAL', state, }); let layer2Network: Layer2Network = this.owner.lookup( 'service:layer2-network' ); layer2Network.strategy.bridgeToLayer1( '0xsource', '0xdestination', 'DAI.CPXD', '20', { onTxnHash: () => {}, } ); let resumeSpy = sinon.spy(layer2Network, 'resumeBridgeToLayer1'); await visit( '/card-pay/deposit-withdrawal?flow=withdrawal&flow-id=abc123' ); assert.dom('[data-test-milestone="0"]').exists(); // L1 assert.dom('[data-test-milestone="1"]').exists(); // Check ETH balance assert.dom('[data-test-milestone="2"]').exists(); // Connect L2 wallet assert.dom('[data-test-milestone="3"]').exists(); // Withdraw from L2 assert.ok(resumeSpy.calledOnce); assert.true( JSON.parse( workflowPersistenceService.getPersistedData('abc123').state.meta ).value.completedCardNames.includes('TRANSACTION_AMOUNT') // Did complete ); assert.dom('[data-test-milestone="4"]').exists(); // Bridge to L1 }); test('it restores the workflow when restoring during bridging', async function (this: Context, assert) { const state = buildState({ withdrawalToken: 'DAI.CPXD', withdrawnAmount: new BN('1000000000000000000'), layer2BlockHeightBeforeBridging: new BN('22867914'), minimumBalanceForWithdrawalClaim: new BN('290000000000000'), relayTokensTxnHash: '0x08ef93a1ac2911210c8e1b351dd90aa00f033b3658abdfb449eda75f84e9f501', relayTokensTxnReceipt: { blockNumber: 0, }, withdrawalSafe: withdrawalSafeAddress, meta: { version: WORKFLOW_VERSION, completedMilestonesCount: 5, milestonesCount: 6, completedCardNames: [ 'LAYER1_CONNECT', 'CHECK_BALANCE', 'LAYER2_CONNECT', 'CHOOSE_BALANCE', 'TRANSACTION_AMOUNT', ], }, }); workflowPersistenceService.persistData('abc123', { name: 'WITHDRAWAL', state, }); let layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; layer2Service.bridgeToLayer1( '0xsource', '0xdestination', 'DAI.CPXD', '20', { onTxnHash: () => {}, } ); layer2Service.test__simulateBridgedToLayer1(); await visit( '/card-pay/deposit-withdrawal?flow=withdrawal&flow-id=abc123' ); assert.dom('[data-test-milestone="0"]').exists(); // L1 assert.dom('[data-test-milestone="1"]').exists(); // Check ETH balance assert.dom('[data-test-milestone="2"]').exists(); // Connect L2 wallet assert.dom('[data-test-milestone="3"]').exists(); // Withdraw from L2 assert.dom('[data-test-milestone="4"]').exists(); // Bridge to L1 assert.dom('[data-test-milestone="5"]').exists(); // Claim assert.dom('[data-test-claim-button]').exists(); assert.true( JSON.parse( workflowPersistenceService.getPersistedData('abc123').state.meta ).value.completedCardNames.includes('TRANSACTION_STATUS') // Did complete ); }); test('it cancels a persisted flow when state version is old', async function (this: Context, assert) { const state = buildState({ withdrawalToken: 'DAI.CPXD', withdrawnAmount: new BN('1000000000000000000'), layer2BlockHeightBeforeBridging: new BN('22867914'), minimumBalanceForWithdrawalClaim: new BN('290000000000000'), relayTokensTxnHash: '0x08ef93a1ac2911210c8e1b351dd90aa00f033b3658abdfb449eda75f84e9f501', bridgeValidationResult: { encodedData: '0x00050000249bfc2f3cc8d68f6b6bf7230ea0a8ed853de7310000000000000b0816a80598dd2f143cfbf091638ce3fb02c9135528366b4cc64d30849568af65522de3a68ea6cc78ce000249f00101004d2a125e4cfb0000000000000000000000004f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa000000000000000000000000511ec1515cdc483d57bc1f38e1325c221debd1e40000000000000000000000000000000000000000000000000de0b6b3a7640000', messageId: '0x00050000249bfc2f3cc8d68f6b6bf7230ea0a8ed853de7310000000000000b08', }, withdrawalSafe: withdrawalSafeAddress, meta: { version: WORKFLOW_VERSION - 1, completedMilestonesCount: 5, milestonesCount: MILESTONE_TITLES.length, completedCardNames: [ 'LAYER1_CONNECT', 'CHECK_BALANCE', 'LAYER2_CONNECT', 'CHOOSE_BALANCE', 'TRANSACTION_AMOUNT', 'TRANSACTION_STATUS', ], }, }); workflowPersistenceService.persistData('abc123', { name: 'WITHDRAWAL', state, }); await visit( '/card-pay/deposit-withdrawal?flow=withdrawal&flow-id=abc123' ); assert.dom('[data-test-milestone="0"]').doesNotExist(); assert.dom('[data-test-milestone="1"]').doesNotExist(); assert.dom('[data-test-milestone="2"]').doesNotExist(); assert.dom('[data-test-milestone="3"]').doesNotExist(); assert.dom('[data-test-milestone="4"]').doesNotExist(); assert .dom('[data-test-cancelation]') .includesText( 'You attempted to restore an unfinished workflow, but the workflow has been upgraded by the Cardstack development team since then, so you will need to start again. Sorry about that!' ); }); }); });
the_stack
interface Array<T> { $remove(item: T): Array<T>; $set(index: any, val: T): T; } declare namespace vuejs { interface PropOption { type?: { new (...args: any[]): any; }; required?: boolean; default?: any; twoWay?: boolean; validator?(value: any): boolean; coerce?(value: any): any; } interface ComputedOption { get(): any; set(value: any): void; } interface WatchOption { handler(val: any, oldVal: any): void; deep?: boolean; immidiate?: boolean; } interface DirectiveOption { bind?(): any; update?(newVal?: any, oldVal?: any): any; unbind?(): any; params?: string[]; deep?: boolean; twoWay?: boolean; acceptStatement?: boolean; priority?: number; [key: string]: any; } interface FilterOption { read?: Function; write?: Function; } interface TransitionOption { css?: boolean; animation?: string; enterClass?: string; leaveClass?: string; beforeEnter?(el: HTMLElement): void; enter?(el: HTMLElement, done?: () => void): void; afterEnter?(el: HTMLElement): void; enterCancelled?(el: HTMLElement): void; beforeLeave?(el: HTMLElement): void; leave?(el: HTMLElement, done?: () => void): void; afterLeave?(el: HTMLElement): void; leaveCancelled?(el: HTMLElement): void; stagger?(index: number): number; enterStagger?(index: number): number; leaveStagger?(index: number): number; [key: string]: any; } interface ComponentOption { data?: { [key: string]: any } | Function; props?: string[] | { [key: string]: (PropOption | { new (...args: any[]): any; }) }; computed?: { [key: string]: (Function | ComputedOption) }; methods?: { [key: string]: Function }; watch?: { [key: string]: ((val: any, oldVal: any) => void) | string | WatchOption }; el?: string | HTMLElement | (() => HTMLElement); template?: string; replace?: boolean; created?(): void; beforeCompile?(): void; compiled?(): void; ready?(): void; attached?(): void; detached?(): void; beforeDestroy?(): void; destroyed?(): void; activate?(): void; directives?: { [key: string]: (DirectiveOption | Function) }; elementDirectives?: { [key: string]: (DirectiveOption | Function) }; filters?: { [key: string]: (Function | FilterOption) }; components?: { [key: string]: any }; transitions?: { [key: string]: TransitionOption }; partials?: { [key: string]: string }; parent?: Vue; events?: { [key: string]: ((...args: any[]) => (boolean | void)) | string }; mixins?: Object[]; name?: string; [key: string]: any; } // instance/api/data.js interface $get { (exp: string, asStatement?: boolean): any; } interface $set { <T>(key: string | number, value: T): T; } interface $delete { (key: string): void; } interface $watch { (expOrFn: string | Function, callback: ((newVal: any, oldVal?: any) => any) | string, options?: { deep?: boolean, immidiate?: boolean }): Function; } interface $eval { (expression: string): string; } interface $interpolate { (expression: string): string; } interface $log { (keypath?: string): void; } // instance/api/dom.js interface $nextTick { (callback: Function): void; } interface $appendTo<V> { (target: (HTMLElement | string), callback?: Function, withTransition?: boolean): V; } interface $prependTo<V> { (target: (HTMLElement | string), callback?: Function, withTransition?: boolean): V; } interface $before<V> { (target: (HTMLElement | string), callback?: Function, withTransition?: boolean): V; } interface $after<V> { (target: (HTMLElement | string), callback?: Function, withTransition?: boolean): V; } interface $remove<V> { (callback?: Function): V; } // instance/api/events.js interface $on<V> { (event: string, callback: Function): V; } interface $once<V> { (event: string, callback: Function): V; } interface $off<V> { (event?: string, callback?: Function): V; } interface $emit<V> { (event: string, ...args: any[]): V; } interface $broadcast<V> { (event: string, ...args: any[]): V; } interface $dispatch<V> { (event: string, ...args: any[]): V; } // instance/api/lifecycle.js interface $mount<V> { (elementOrSelector?: (HTMLElement | string)): V; } interface $destroy { (remove?: boolean): void; } interface $compile { (el: Element | DocumentFragment, host?: Vue): Function; } interface Vue { $data?: any; $el?: HTMLElement; $options?: Object; $parent?: Vue; $root?: Vue; $children?: Vue[]; $refs?: Object; $els?: Object; $get?: $get; $set?: $set; $delete?: $delete; $eval?: $eval; $interpolate?: $interpolate; $log?: $log; $watch?: $watch; $on?: $on<this>; $once?: $once<this>; $off?: $off<this>; $emit?: $emit<this>; $dispatch?: $dispatch<this>; $broadcast?: $broadcast<this>; $appendTo?: $appendTo<this>; $before?: $before<this>; $after?: $after<this>; $remove?: $remove<this>; $nextTick?: $nextTick; $mount?: $mount<this>; $destroy?: $destroy; $compile?: $compile; _init?(options?: ComponentOption): void; } interface VueConfig { debug: boolean; delimiters: [string, string]; unsafeDelimiters: [string, string]; silent: boolean; async: boolean; convertAllProperties: boolean; } interface VueUtil { // util/lang.js set(obj: Object, key: string, value: any): void; del(obj: Object, key: string): void; hasOwn(obj: Object, key: string): boolean; isLiteral(exp: string): boolean; isReserved(str: string): boolean; _toString(value: any): string; toNumber<T>(value: T): T | number; toBoolean<T>(value: T): T | boolean; stripQuotes(str: string): string; camelize(str: string): string; hyphenate(str: string): string; classify(str: string): string; bind(fn: Function, ctx: Object): Function; toAarray<T>(list: ArrayLike<T>, start?: number): Array<T>; extend<T, F>(to: T, from: F): (T & F); isObject(obj: any): boolean; isPlainObject(obj: any): boolean; isArray: typeof Array.isArray; def(obj: Object, key: string, value: any, enumerable?: boolean): void; debounce(func: Function, wait: number): Function; indexOf<T>(arr: Array<T>, obj: T): number; cancellable(fn: Function): Function; looseEqual(a: any, b: any): boolean; // util/env.js hasProto: boolean; inBrowser: boolean; isIE9: boolean; isAndroid: boolean; transitionProp: string; transitionEndEvent: string; animationProp: string; animationEndEvent: string; nextTick(cb: Function, ctx?: Object): void; // util/dom.js query(el: string | Element): Element; inDoc(node: Node): boolean; getAttr(node: Node, _attr: string): string; getBindAttr(node: Node, name: string): string; before(el: Element, target: Element): void; after(el: Element, target: Element): void; remove(el: Element): void; prepend(el: Element, target: Element): void; replace(target: Element, el: Element): void; on(el: Element, event: string, cb: Function): void; off(el: Element, event: string, cb: Function): void; addClass(el: Element, cls: string): void; removeClass(el: Element, cls: string): void; extractContent(el: Element, asFragment: boolean): (HTMLDivElement | DocumentFragment); trimNode(node: Node): void; isTemplate(el: Element): boolean; createAnchor(content: string, persist: boolean): (Comment | Text); findRef(node: Element): string; mapNodeRange(node: Node, end: Node, op: Function): void; removeNodeRange(start: Node, end: Node, vm: any, frag: DocumentFragment, cb: Function): void; // util/options.js mergeOptions<P, C>(parent: P, child: C, vm?: any): (P & C); resolveAsset(options: Object, type: string, id: string): (Object | Function); assertAsset(val: any, type: string, id: string): void; // util/component.js commonTagRE: RegExp; checkComponentAttr(el: Element, options?: Object): Object; initProp(vm: Vue, prop: Object, value: any): void; assertProp(prop: Object, value: any): boolean; // util/debug.js warn(msg: string, e?: Error): void; // observer/index.js defineReactive(obj: Object, key: string, val: any): void; } // instance/api/global.js interface VueStatic { new (options?: ComponentOption): Vue; prototype: Vue; util: VueUtil; config: VueConfig; set(object: Object, key: string, value: any): void; delete(object: Object, key: string): void; nextTick(callback: Function): any; cid: number; extend(options?: ComponentOption): VueStatic; use(callback: Function | { install: Function, [key: string]: any }, option?: Object): VueStatic; mixin(mixin: Object): void; directive<T extends (Function | DirectiveOption)>(id: string, definition: T): T; directive(id: string): any; elementDirective<T extends (Function | DirectiveOption)>(id: string, definition: T): T; elementDirective(id: string): any; filter<T extends (Function | FilterOption)>(id: string, definition: T): T; filter(id: string): any; component(id: string, definition: ComponentOption): any; component(id: string): any; transition<T extends TransitionOption>(id: string, hooks: T): T; transition(id: string): TransitionOption; partial(id: string, partial: string): string; partial(id: string): string; } } declare var Vue: vuejs.VueStatic; declare module "vue" { export default Vue; }
the_stack
import * as assert from "assert"; import { isValidJSON, JSON2CSV } from "../../views/partition-table/util"; import { CSV2JSON } from "../../views/partition-table/util"; import * as vscode from "vscode"; import { stringify } from "querystring"; import { PartitionTable } from "../../views/partition-table/store"; import { resolve } from "path"; import * as fse from "fs-extra"; suite("PartitionTable Suite", () => { test("CSV2JSON mockdata test", async () => { const urlCSV = resolve(__dirname,"..", "..", "..", "testFiles", "test.csv"); const urlJSON = resolve(__dirname,"..", "..", "..", "testFiles", "test.json"); let dataCSV = await fse.readFile(urlCSV,"utf-8"); let dataJSON = await fse.readFile(urlJSON, "utf-8"); await assert.equal(JSON.stringify(CSV2JSON<PartitionTable.Row>(dataCSV)), JSON.stringify(JSON.parse((dataJSON)))); }); test("Row validation", async () => { let validRow = [{ "name": "ncs", "type": "data", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(validRow)), JSON.stringify({ ok: true, error: "", row: -1 })); }); // Name field related unit tests test("Name field empty validation", async () => { let invalidRow = [{ "name": "", "type": "data", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Name is mandatory", row: 0 })); }); test("Name field too long validation", async () => { let invalidRow = [{ "name": "12345678901234567", "type": "data", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Names longer than 16 characters are not allowed", row: 0 })); }); // Type field related unit tests test("Type field empty validation", async () => { let invalidRow = [{ "name": "ncs", "type": "", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Type is required", row: 0 })); }); test("Type field input string value bigger than 254 validation", async () => { let invalidRow = [{ "name": "ncs", "type": "255", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Partition type field can be specified as app (0x00) or data (0x01). Or it can be a number 0-254 (or as hex 0x00-0xFE). Types 0x00-0x3F are reserved for ESP-IDF core functions.", row: 0 })); }); test("Type field input string value smaller than 0 validation", async () => { let invalidRow = [{ "name": "ncs", "type": "-1", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Partition type field can be specified as app (0x00) or data (0x01). Or it can be a number 0-254 (or as hex 0x00-0xFE). Types 0x00-0x3F are reserved for ESP-IDF core functions.", row: 0 })); }); test("Type field input string invalid", async () => { let invalidRow = [{ "name": "ncs", "type": "testing", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Partition type field can be specified as app (0x00) or data (0x01). Or it can be a number 0-254 (or as hex 0x00-0xFE). Types 0x00-0x3F are reserved for ESP-IDF core functions.", row: 0 })); }); test("Type field input more than 2 hex numbers after 0x prefix", async () => { let invalidRow = [{ "name": "ncs", "type": "0x12c", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Partition type field can be specified as app (0x00) or data (0x01). Or it can be a number 0-254 (or as hex 0x00-0xFE). Types 0x00-0x3F are reserved for ESP-IDF core functions.", row: 0 })); }); test("Type field input is not a hex number", async () => { let invalidRow = [{ "name": "ncs", "type": "0x1g", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Partition type field can be specified as app (0x00) or data (0x01). Or it can be a number 0-254 (or as hex 0x00-0xFE). Types 0x00-0x3F are reserved for ESP-IDF core functions.", row: 0 })); }); test("Type field input 0xFF is not valid", async () => { let invalidRow = [{ "name": "ncs", "type": "0xFF", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Partition type field can be specified as app (0x00) or data (0x01). Or it can be a number 0-254 (or as hex 0x00-0xFE). Types 0x00-0x3F are reserved for ESP-IDF core functions.", row: 0 })); }); // Subtype field related unit tests test("Subtype field empty validation", async () => { let invalidRow = [{ "name": "ncs", "type": "data", "subtype": "", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "SubType is required", row: 0 })); }); test("Subtype field for type app random string", async () => { let invalidRow = [{ "name": "ncs", "type": "app", "subtype": "testing", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "When type is \"app\", the subtype field can only be specified as \"factory\" (0x00), \"ota_0\" (0x10) … \"ota_15\" (0x1F) or \"test\" (0x20)", row: 0 })); }); test("Subtype field for type app valid value contained in a longer string", async () => { let invalidRow = [{ "name": "ncs", "type": "app", "subtype": "0x20ca", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "When type is \"app\", the subtype field can only be specified as \"factory\" (0x00), \"ota_0\" (0x10) … \"ota_15\" (0x1F) or \"test\" (0x20)", row: 0 })); }); test("Subtype field for type app 0x21 should be invalid", async () => { let invalidRow = [{ "name": "ncs", "type": "app", "subtype": "0x21", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "When type is \"app\", the subtype field can only be specified as \"factory\" (0x00), \"ota_0\" (0x10) … \"ota_15\" (0x1F) or \"test\" (0x20)", row: 0 })); }); test("Subtype field for type app invalid hex number", async () => { let invalidRow = [{ "name": "ncs", "type": "app", "subtype": "0x1g", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "When type is \"app\", the subtype field can only be specified as \"factory\" (0x00), \"ota_0\" (0x10) … \"ota_15\" (0x1F) or \"test\" (0x20)", row: 0 })); }); test("Subtype field for type data valid string value contained in a longer string", async () => { let invalidRow = [{ "name": "ncs", "type": "data", "subtype": "otas", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "When type is \"data\", the subtype field can be specified as \"ota\" (0x00), \"phy\" (0x01), \"nvs\" (0x02), \"nvs_keys\" (0x04), or a range of other component-specific subtypes (0x05, 0x06, 0x80, 0x81, 0x82)", row: 0 })); }); test("Subtype field for type data valid hex value contained in a longer string", async () => { let invalidRow = [{ "name": "ncs", "type": "data", "subtype": "0x000", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "When type is \"data\", the subtype field can be specified as \"ota\" (0x00), \"phy\" (0x01), \"nvs\" (0x02), \"nvs_keys\" (0x04), or a range of other component-specific subtypes (0x05, 0x06, 0x80, 0x81, 0x82)", row: 0 })); }); test("Subtype field for type data 0x10 should be invalid", async () => { let invalidRow = [{ "name": "ncs", "type": "data", "subtype": "0x10", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "When type is \"data\", the subtype field can be specified as \"ota\" (0x00), \"phy\" (0x01), \"nvs\" (0x02), \"nvs_keys\" (0x04), or a range of other component-specific subtypes (0x05, 0x06, 0x80, 0x81, 0x82)", row: 0 })); }); test("Subtype field for custom type valid hex value contained in a longer string", async () => { let invalidRow = [{ "name": "ncs", "type": "0x40", "subtype": "0x000", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "If the partition type is any application-defined value (range 0x40-0xFE), then subtype field can be any value chosen by the application (range 0x00-0xFE).", row: 0 })); }); test("Subtype field for custom type random invalid string value", async () => { let invalidRow = [{ "name": "ncs", "type": "0x40", "subtype": "test", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "If the partition type is any application-defined value (range 0x40-0xFE), then subtype field can be any value chosen by the application (range 0x00-0xFE).", row: 0 })); }); test("Subtype field for custom 0xFF should be invalid", async () => { let invalidRow = [{ "name": "ncs", "type": "0x40", "subtype": "0xFF", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "If the partition type is any application-defined value (range 0x40-0xFE), then subtype field can be any value chosen by the application (range 0x00-0xFE).", row: 0 })); }); // Offset field related unit tests test("Offset field empty validation", async () => { let validRow = [{ "name": "ncs", "type": "data", "subtype": "nvs", "offset": "", "size": "10M", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(validRow)), JSON.stringify({ ok: true, error: "", row: -1 })); }); test("Offset field random invalid string input", async () => { let invalidRow = [{ "name": "ncs", "type": "data", "subtype": "nvs", "offset": "testing0x10", "size": "10M", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Offsets can be specified as decimal numbers, hex numbers with the prefix 0x, size multipliers K or M (1024 and 1024*1024 bytes) or left empty.", row: 0 })); }); // Size field related unit tests test("Size field empty validation", async () => { let invalidRow = [{ "name": "ncs", "type": "data", "subtype": "nvs", "offset": "0x9000", "size": "", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Size is required", row: 0 })); }); test("Size field wrong input validation", async () => { let invalidRow = [{ "name": "ncs", "type": "data", "subtype": "nvs", "offset": "0x9000", "size": "Testing", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(invalidRow)), JSON.stringify({ ok: false, error: "Size can be specified as decimal numbers, hex numbers with the prefix 0x, or size multipliers K or M (1024 and 1024*1024 bytes).", row: 0 })); }); test("Size field decimal number ending with M or K validation", async () => { let validRow = [{ "name": "ncs", "type": "data", "subtype": "nvs", "offset": "0x9000", "size": "24M", "flag": false, "error": undefined },{ "name": "ncs", "type": "data", "subtype": "nvs", "offset": "0x9000", "size": "24K", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(validRow)), JSON.stringify({ ok: true, error: "", row: -1 })); }); test("Size field hex number with 0x validation", async () => { let validRow = [{ "name": "ncs", "type": "data", "subtype": "nvs", "offset": "0x9000", "size": "0xfac", "flag": false, "error": undefined },{ "name": "ncs", "type": "data", "subtype": "nvs", "offset": "0x9000", "size": "252", "flag": false, "error": undefined }]; await assert.equal(JSON.stringify(isValidJSON(validRow)), JSON.stringify({ ok: true, error: "", row: -1 })); }); });
the_stack
import { Quad, NamedNode, Quad_Object } from "@rdfjs/types"; import { addRdfJsQuadToDataset, DataFactory, getChainBlankNodes, toRdfJsQuads, } from "../rdfjs.internal"; import { ldp, pim } from "../constants"; import { getJsonLdParser } from "../formats/jsonLd"; import { triplesToTurtle, getTurtleParser } from "../formats/turtle"; import { isLocalNode, isNamedNode, resolveIriForLocalNode } from "../datatypes"; import { UrlString, WithResourceInfo, hasResourceInfo, Url, IriString, Thing, ThingPersisted, WithServerResourceInfo, SolidDataset, WithChangeLog, hasChangelog, LocalNode, SolidClientError, } from "../interfaces"; import { internal_toIriString } from "../interfaces.internal"; import { internal_defaultFetchOptions, getSourceUrl, getResourceInfo, isContainer, FetchError, responseToResourceInfo, getContentType, getLinkedResourceUrlAll, } from "./resource"; import { internal_isUnsuccessfulResponse, internal_parseResourceInfo, } from "./resource.internal"; import { thingAsMarkdown, getThing, getThingAll } from "../thing/thing"; import { internal_getReadableValue, internal_withChangeLog, } from "../thing/thing.internal"; import { getIriAll } from "../thing/get"; import { normalizeServerSideIri } from "./iri.internal"; import { freeze, getLocalNodeName, isLocalNodeIri } from "../rdf.internal"; /** * Initialise a new [[SolidDataset]] in memory. * * @returns An empty [[SolidDataset]]. */ export function createSolidDataset(): SolidDataset { return freeze({ type: "Dataset", graphs: { default: {}, }, }); } /** * A Parser takes a string and generates {@link https://rdf.js.org/data-model-spec/|RDF/JS Quads}. * * By providing an object conforming to the `Parser` interface, you can handle * RDF serialisations other than `text/turtle`, which `@inrupt/solid-client` * supports by default. This can be useful to retrieve RDF data from sources * other than a Solid Pod. * * A Parser has the following properties: * - `onQuad`: Registers the callback with which parsed * {@link https://rdf.js.org/data-model-spec/|RDF/JS Quads} can be provided to * `@inrupt/solid-client`. * - `onError`: Registers the callback with which `@inrupt/solid-client` can be * notified of errors parsing the input. * - `onComplete`: Registers the callback with which `@inrupt/solid-client` can * be notified that parsing is complete. * - `parse`: Accepts the serialised input string and an object containing the * input Resource's metadata. * The input metadata can be read using functions like [[getSourceUrl]] and * [[getContentType]]. * * For example, the following defines a parser that reads an RDFa serialisation * using the * [rdfa-streaming-parser](https://www.npmjs.com/package/rdfa-streaming-parser) * library: * * ```javascript * import { RdfaParser } from "rdfa-streaming-parser"; * * // ... * * const getRdfaParser = () => { * const onQuadCallbacks = []; * const onCompleteCallbacks = []; * const onErrorCallbacks = []; * * return { * onQuad: (callback) => onQuadCallbacks.push(callback), * onError: (callback) => onErrorCallbacks.push(callback), * onComplete: (callback) => onCompleteCallbacks.push(callback), * parse: async (source, resourceInfo) => { * const parser = new RdfaParser({ * baseIRI: getSourceUrl(resourceInfo), * contentType: getContentType(resourceInfo) ?? "text/html", * }); * parser.on("data", (quad) => { * onQuadCallbacks.forEach((callback) => callback(quad)); * }); * parser.on("error", (error) => { * onErrorCallbacks.forEach((callback) => callback(error)); * }); * parser.write(source); * parser.end(); * onCompleteCallbacks.forEach((callback) => callback()); * }, * }; * }; * ``` */ export type Parser = { onQuad: (onQuadCallback: (quad: Quad) => void) => void; onError: (onErrorCallback: (error: unknown) => void) => void; onComplete: (onCompleteCallback: () => void) => void; parse: (source: string, resourceInfo: WithServerResourceInfo) => void; }; type ContentType = string; /** * Custom parsers to load [[SolidDataset]]s serialised in different RDF formats. * * Provide your own parsers by providing an object on the `parsers` property * with the supported content type as the key, and the parser as a value. * For documentation on how to provide a parser, see [[Parser]]. */ export type ParseOptions = { parsers: Record<ContentType, Parser>; }; /** * @hidden This interface is not exposed yet until we've tried it out in practice. */ export async function responseToSolidDataset( response: Response, parseOptions: Partial<ParseOptions> = {} ): Promise<SolidDataset & WithServerResourceInfo> { if (internal_isUnsuccessfulResponse(response)) { throw new FetchError( `Fetching the SolidDataset at [${response.url}] failed: [${response.status}] [${response.statusText}].`, response ); } const resourceInfo = responseToResourceInfo(response); const parsers: Record<ContentType, Parser> = { "text/turtle": getTurtleParser(), ...parseOptions.parsers, }; const contentType = getContentType(resourceInfo); if (contentType === null) { throw new Error( `Could not determine the content type of the Resource at [${getSourceUrl( resourceInfo )}].` ); } const mimeType = contentType.split(";")[0]; const parser = parsers[mimeType]; if (typeof parser === "undefined") { throw new Error( `The Resource at [${getSourceUrl( resourceInfo )}] has a MIME type of [${mimeType}], but the only parsers available are for the following MIME types: [${Object.keys( parsers ).join(", ")}].` ); } const data = await response.text(); const parsingPromise = new Promise<SolidDataset & WithServerResourceInfo>( (resolve, reject) => { let solidDataset: SolidDataset = freeze({ graphs: freeze({ default: freeze({}) }), type: "Dataset", }); // While Quads without Blank Nodes can be added to the SolidDataset as we // encounter them, to parse Quads with Blank Nodes, we'll have to wait until // we've seen all the Quads, so that we can reconcile equal Blank Nodes. const quadsWithBlankNodes: Quad[] = []; const allQuads: Quad[] = []; parser.onError((error) => { reject( new Error( `Encountered an error parsing the Resource at [${getSourceUrl( resourceInfo )}] with content type [${contentType}]: ${error}` ) ); }); parser.onQuad((quad) => { allQuads.push(quad); if ( quad.subject.termType === "BlankNode" || quad.object.termType === "BlankNode" ) { // Quads with Blank Nodes will be parsed when all Quads are known, // so that equal Blank Nodes can be reconciled: quadsWithBlankNodes.push(quad); } else { solidDataset = addRdfJsQuadToDataset(solidDataset, quad); } }); parser.onComplete(async () => { // If a Resource contains more than this number of Blank Nodes, // we consider the detection of chains (O(n^2), I think) to be too // expensive, and just incorporate them as regular Blank Nodes with // non-deterministic, ad-hoc identifiers into the SolidDataset: const maxBlankNodesToDetectChainsFor = 20; // Some Blank Nodes only serve to use a set of Quads as the Object for a // single Subject. Those Quads will be added to the SolidDataset when // their Subject's Blank Node is encountered in the Object position. const chainBlankNodes = quadsWithBlankNodes.length <= maxBlankNodesToDetectChainsFor ? getChainBlankNodes(quadsWithBlankNodes) : []; const quadsWithoutChainBlankNodeSubjects = quadsWithBlankNodes.filter( (quad) => chainBlankNodes.every( (chainBlankNode) => !chainBlankNode.equals(quad.subject) ) ); solidDataset = quadsWithoutChainBlankNodeSubjects.reduce( (datasetAcc, quad) => addRdfJsQuadToDataset(datasetAcc, quad, { otherQuads: allQuads, chainBlankNodes: chainBlankNodes, }), solidDataset ); const solidDatasetWithResourceInfo: SolidDataset & WithServerResourceInfo = freeze({ ...solidDataset, ...resourceInfo, }); resolve(solidDatasetWithResourceInfo); }); parser.parse(data, resourceInfo); } ); return await parsingPromise; } /** * Fetch a SolidDataset from the given URL. Currently requires the SolidDataset to be available as [Turtle](https://www.w3.org/TR/turtle/). * * @param url URL to fetch a [[SolidDataset]] from. * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters). * @returns Promise resolving to a [[SolidDataset]] containing the data at the given Resource, or rejecting if fetching it failed. */ export async function getSolidDataset( url: UrlString | Url, options: Partial< typeof internal_defaultFetchOptions & ParseOptions > = internal_defaultFetchOptions ): Promise<SolidDataset & WithServerResourceInfo> { url = internal_toIriString(url); const config = { ...internal_defaultFetchOptions, ...options, }; const parserContentTypes = Object.keys(options.parsers ?? {}); const acceptedContentTypes = parserContentTypes.length > 0 ? parserContentTypes.join(", ") : "text/turtle"; const response = await config.fetch(url, { headers: { Accept: acceptedContentTypes, }, }); if (internal_isUnsuccessfulResponse(response)) { throw new FetchError( `Fetching the Resource at [${url}] failed: [${response.status}] [${response.statusText}].`, response ); } const solidDataset = await responseToSolidDataset(response, options); return solidDataset; } type UpdateableDataset = SolidDataset & WithChangeLog & WithServerResourceInfo & { internal_resourceInfo: { sourceIri: IriString } }; /** * Create a SPARQL UPDATE Patch request from a [[SolidDataset]] with a changelog. * @param solidDataset the [[SolidDataset]] that has been locally updated, and that should be persisted. * @returns an HTTP PATCH request configuration object, aligned with the [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters), containing a SPARQL UPDATE. * @hidden */ async function prepareSolidDatasetUpdate( solidDataset: UpdateableDataset ): Promise<RequestInit> { const deleteStatement = solidDataset.internal_changeLog.deletions.length > 0 ? `DELETE DATA {${( await triplesToTurtle( solidDataset.internal_changeLog.deletions.map( getNamedNodesForLocalNodes ) ) ).trim()}};` : ""; const insertStatement = solidDataset.internal_changeLog.additions.length > 0 ? `INSERT DATA {${( await triplesToTurtle( solidDataset.internal_changeLog.additions.map( getNamedNodesForLocalNodes ) ) ).trim()}};` : ""; return { method: "PATCH", body: `${deleteStatement} ${insertStatement}`, headers: { "Content-Type": "application/sparql-update", }, }; } /** * Create a Put request to write a locally created [[SolidDataset]] to a Pod. * @param solidDataset the [[SolidDataset]] that has been locally updated, and that should be persisted. * @returns an HTTP PUT request configuration object, aligned with the [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters), containing a serialization of the [[SolidDataset]]. * @hidden */ async function prepareSolidDatasetCreation( solidDataset: SolidDataset ): Promise<RequestInit> { return { method: "PUT", body: await triplesToTurtle( toRdfJsQuads(solidDataset).map(getNamedNodesForLocalNodes) ), headers: { "Content-Type": "text/turtle", "If-None-Match": "*", Link: `<${ldp.Resource}>; rel="type"`, }, }; } /** * Given a SolidDataset, store it in a Solid Pod (overwriting the existing data at the given URL). * * A SolidDataset keeps track of the data changes compared to the data in the Pod; i.e., * the changelog tracks both the old value and new values of the property being modified. This * function applies the changes to the current SolidDataset. If the old value specified in the * changelog does not correspond to the value currently in the Pod, this function will throw an * error. * The SolidDataset returned by this function will contain the data sent to the Pod, and a ChangeLog * up-to-date with the saved data. Note that if the data on the server was modified in between the * first fetch and saving it, the updated data will not be reflected in the returned SolidDataset. * To make sure you have the latest data, call [[getSolidDataset]] again after saving the data. * * The Solid server will create any intermediary Containers that do not exist yet, so they do not * need to be created in advance. For example, if the target URL is * https://example.pod/container/resource and https://example.pod/container/ does not exist yet, * it will exist after this function resolves successfully. * * @param url URL to save `solidDataset` to. * @param solidDataset The [[SolidDataset]] to save. * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters). * @returns A Promise resolving to a [[SolidDataset]] containing the stored data, or rejecting if saving it failed. */ export async function saveSolidDatasetAt<Dataset extends SolidDataset>( url: UrlString | Url, solidDataset: Dataset, options: Partial< typeof internal_defaultFetchOptions > = internal_defaultFetchOptions ): Promise<Dataset & WithServerResourceInfo & WithChangeLog> { url = internal_toIriString(url); const config = { ...internal_defaultFetchOptions, ...options, }; const datasetWithChangelog = internal_withChangeLog(solidDataset); const requestInit = isUpdate(datasetWithChangelog, url) ? await prepareSolidDatasetUpdate(datasetWithChangelog) : await prepareSolidDatasetCreation(datasetWithChangelog); const response = await config.fetch(url, requestInit); if (internal_isUnsuccessfulResponse(response)) { const diagnostics = isUpdate(datasetWithChangelog, url) ? "The changes that were sent to the Pod are listed below.\n\n" + changeLogAsMarkdown(datasetWithChangelog) : "The SolidDataset that was sent to the Pod is listed below.\n\n" + solidDatasetAsMarkdown(datasetWithChangelog); throw new FetchError( `Storing the Resource at [${url}] failed: [${response.status}] [${response.statusText}].\n\n` + diagnostics, response ); } const resourceInfo: WithServerResourceInfo["internal_resourceInfo"] = { ...internal_parseResourceInfo(response), isRawData: false, }; const storedDataset: Dataset & WithChangeLog & WithServerResourceInfo = freeze({ ...solidDataset, internal_changeLog: { additions: [], deletions: [] }, internal_resourceInfo: resourceInfo, }); const storedDatasetWithResolvedIris = resolveLocalIrisInSolidDataset(storedDataset); return storedDatasetWithResolvedIris; } /** * Deletes the SolidDataset at a given URL. * * If operating on a container, the container must be empty otherwise a 409 CONFLICT will be raised. * * @param file The (URL of the) SolidDataset to delete * @since 0.6.0 */ export async function deleteSolidDataset( solidDataset: Url | UrlString | WithResourceInfo, options: Partial< typeof internal_defaultFetchOptions > = internal_defaultFetchOptions ): Promise<void> { const config = { ...internal_defaultFetchOptions, ...options, }; const url = hasResourceInfo(solidDataset) ? internal_toIriString(getSourceUrl(solidDataset)) : internal_toIriString(solidDataset); const response = await config.fetch(url, { method: "DELETE" }); if (internal_isUnsuccessfulResponse(response)) { throw new FetchError( `Deleting the SolidDataset at [${url}] failed: [${response.status}] [${response.statusText}].`, response ); } } /** * Create an empty Container at the given URL. * * Throws an error if creating the Container failed, e.g. because the current user does not have * permissions to, or because the Container already exists. * * Note that a Solid server will automatically create the necessary Containers when storing a * Resource; i.e. there is no need to call this function if it is immediately followed by * [[saveSolidDatasetAt]] or [[overwriteFile]]. * * @param url URL of the empty Container that is to be created. * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters). * @since 0.2.0 */ export async function createContainerAt( url: UrlString | Url, options: Partial< typeof internal_defaultFetchOptions > = internal_defaultFetchOptions ): Promise<SolidDataset & WithServerResourceInfo> { url = internal_toIriString(url); url = url.endsWith("/") ? url : url + "/"; const config = { ...internal_defaultFetchOptions, ...options, }; const response = await config.fetch(url, { method: "PUT", headers: { Accept: "text/turtle", "Content-Type": "text/turtle", "If-None-Match": "*", // This header should not be required to create a Container, // but ESS currently expects it: Link: `<${ldp.BasicContainer}>; rel="type"`, }, }); if (internal_isUnsuccessfulResponse(response)) { if ( response.status === 409 && response.statusText === "Conflict" && (await response.text()).trim() === internal_NSS_CREATE_CONTAINER_SPEC_NONCOMPLIANCE_DETECTION_ERROR_MESSAGE_TO_WORKAROUND_THEIR_ISSUE_1465 ) { return createContainerWithNssWorkaroundAt(url, options); } throw new FetchError( `Creating the empty Container at [${url}] failed: [${response.status}] [${response.statusText}].`, response ); } const resourceInfo = internal_parseResourceInfo(response); const containerDataset: SolidDataset & WithChangeLog & WithServerResourceInfo = freeze({ ...createSolidDataset(), internal_changeLog: { additions: [], deletions: [] }, internal_resourceInfo: resourceInfo, }); return containerDataset; } /** * Unfortunately Node Solid Server does not confirm to the Solid spec when it comes to Container * creation. When we make the (valid, according to the Solid protocol) request to create a * Container, NSS responds with the following exact error message. Thus, when we encounter exactly * this message, we use an NSS-specific workaround ([[createContainerWithNssWorkaroundAt]]). Both * this constant and that workaround should be removed once the NSS issue has been fixed and * no versions of NSS with the issue are in common use/supported anymore. * * @see https://github.com/solid/node-solid-server/issues/1465 * @internal */ export const internal_NSS_CREATE_CONTAINER_SPEC_NONCOMPLIANCE_DETECTION_ERROR_MESSAGE_TO_WORKAROUND_THEIR_ISSUE_1465 = "Can't write file: PUT not supported on containers, use POST instead"; /** * Unfortunately Node Solid Server does not confirm to the Solid spec when it comes to Container * creation. As a workaround, we create a dummy file _inside_ the desired Container (which should * create the desired Container on the fly), and then delete it again. * * @see https://github.com/solid/node-solid-server/issues/1465 */ const createContainerWithNssWorkaroundAt: typeof createContainerAt = async ( url, options ) => { url = internal_toIriString(url); const config = { ...internal_defaultFetchOptions, ...options, }; let existingContainer; try { existingContainer = await getResourceInfo(url, options); } catch (e) { // To create the Container, we'd want it to not exist yet. In other words, we'd expect to get // a 404 error here in the happy path - so do nothing if that's the case. if (!(e instanceof FetchError) || e.statusCode !== 404) { // (But if we get an error other than a 404, just throw that error like we usually would.) throw e; } } if (typeof existingContainer !== "undefined") { throw new Error( `The Container at [${url}] already exists, and therefore cannot be created again.` ); } const dummyUrl = url + ".dummy"; const createResponse = await config.fetch(dummyUrl, { method: "PUT", headers: { Accept: "text/turtle", "Content-Type": "text/turtle", }, }); if (internal_isUnsuccessfulResponse(createResponse)) { throw new FetchError( `Creating the empty Container at [${url}] failed: [${createResponse.status}] [${createResponse.statusText}].`, createResponse ); } await config.fetch(dummyUrl, { method: "DELETE" }); const containerInfoResponse = await config.fetch(url, { method: "HEAD" }); const resourceInfo = internal_parseResourceInfo(containerInfoResponse); const containerDataset: SolidDataset & WithChangeLog & WithServerResourceInfo = freeze({ ...createSolidDataset(), internal_changeLog: { additions: [], deletions: [] }, internal_resourceInfo: resourceInfo, }); return containerDataset; }; function isSourceIriEqualTo( dataset: SolidDataset & WithResourceInfo, iri: IriString ): boolean { return ( normalizeServerSideIri(dataset.internal_resourceInfo.sourceIri) === normalizeServerSideIri(iri) ); } function isUpdate( solidDataset: SolidDataset, url: UrlString ): solidDataset is UpdateableDataset { return ( hasChangelog(solidDataset) && hasResourceInfo(solidDataset) && typeof solidDataset.internal_resourceInfo.sourceIri === "string" && isSourceIriEqualTo(solidDataset, url) ); } type SaveInContainerOptions = Partial< typeof internal_defaultFetchOptions & { slugSuggestion: string; } >; /** * Given a SolidDataset, store it in a Solid Pod in a new Resource inside a Container. * * The Container at the given URL should already exist; if it does not, you can initialise it first * using [[createContainerAt]], or directly save the SolidDataset at the desired location using * [[saveSolidDatasetAt]]. * * This function is primarily useful if the current user does not have access to change existing files in * a Container, but is allowed to add new files; in other words, they have Append, but not Write * access to a Container. This is useful in situations where someone wants to allow others to, * for example, send notifications to their Pod, but not to view or delete existing notifications. * You can pass a suggestion for the new Resource's name, but the server may decide to give it * another name — for example, if a Resource with that name already exists inside the given * Container. * If the user does have access to write directly to a given location, [[saveSolidDatasetAt]] * will do the job just fine, and does not require the parent Container to exist in advance. * * @param containerUrl URL of the Container in which to create a new Resource. * @param solidDataset The [[SolidDataset]] to save to a new Resource in the given Container. * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters). * @returns A Promise resolving to a [[SolidDataset]] containing the saved data. The Promise rejects if the save failed. */ export async function saveSolidDatasetInContainer( containerUrl: UrlString | Url, solidDataset: SolidDataset, options: SaveInContainerOptions = internal_defaultFetchOptions ): Promise<SolidDataset & WithResourceInfo> { const config = { ...internal_defaultFetchOptions, ...options, }; containerUrl = internal_toIriString(containerUrl); const rawTurtle = await triplesToTurtle( toRdfJsQuads(solidDataset).map(getNamedNodesForLocalNodes) ); const headers: RequestInit["headers"] = { "Content-Type": "text/turtle", Link: `<${ldp.Resource}>; rel="type"`, }; if (options.slugSuggestion) { headers.slug = options.slugSuggestion; } const response = await config.fetch(containerUrl, { method: "POST", body: rawTurtle, headers: headers, }); if (internal_isUnsuccessfulResponse(response)) { throw new FetchError( `Storing the Resource in the Container at [${containerUrl}] failed: [${response.status}] [${response.statusText}].\n\n` + "The SolidDataset that was sent to the Pod is listed below.\n\n" + solidDatasetAsMarkdown(solidDataset), response ); } const locationHeader = response.headers.get("Location"); if (locationHeader === null) { throw new Error( "Could not determine the location of the newly saved SolidDataset." ); } const resourceIri = new URL(locationHeader, response.url).href; const resourceInfo: WithResourceInfo = { internal_resourceInfo: { isRawData: false, sourceIri: resourceIri, }, }; const resourceWithResourceInfo: SolidDataset & WithResourceInfo = freeze({ ...solidDataset, ...resourceInfo, }); const resourceWithResolvedIris = resolveLocalIrisInSolidDataset( resourceWithResourceInfo ); return resourceWithResolvedIris; } /** * Create an empty Container inside the Container at the given URL. * * Throws an error if creating the Container failed, e.g. because the current user does not have * permissions to. * * The Container in which to create the new Container should itself already exist. * * This function is primarily useful if the current user does not have access to change existing files in * a Container, but is allowed to add new files; in other words, they have Append, but not Write * access to a Container. This is useful in situations where someone wants to allow others to, * for example, send notifications to their Pod, but not to view or delete existing notifications. * You can pass a suggestion for the new Resource's name, but the server may decide to give it * another name — for example, if a Resource with that name already exists inside the given * Container. * If the user does have access to write directly to a given location, [[createContainerAt]] * will do the job just fine, and does not require the parent Container to exist in advance. * * @param containerUrl URL of the Container in which the empty Container is to be created. * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters). * @since 0.2.0 */ export async function createContainerInContainer( containerUrl: UrlString | Url, options: SaveInContainerOptions = internal_defaultFetchOptions ): Promise<SolidDataset & WithResourceInfo> { containerUrl = internal_toIriString(containerUrl); const config = { ...internal_defaultFetchOptions, ...options, }; const headers: RequestInit["headers"] = { "Content-Type": "text/turtle", Link: `<${ldp.BasicContainer}>; rel="type"`, }; if (options.slugSuggestion) { headers.slug = options.slugSuggestion; } const response = await config.fetch(containerUrl, { method: "POST", headers: headers, }); if (internal_isUnsuccessfulResponse(response)) { throw new FetchError( `Creating an empty Container in the Container at [${containerUrl}] failed: [${response.status}] [${response.statusText}].`, response ); } const locationHeader = response.headers.get("Location"); if (locationHeader === null) { throw new Error( "Could not determine the location of the newly created Container." ); } const resourceIri = new URL(locationHeader, response.url).href; const resourceInfo: WithResourceInfo = { internal_resourceInfo: { isRawData: false, sourceIri: resourceIri, }, }; const resourceWithResourceInfo: SolidDataset & WithResourceInfo = freeze({ ...createSolidDataset(), ...resourceInfo, }); return resourceWithResourceInfo; } /** * Deletes the Container at a given URL. * * @param file The (URL of the) Container to delete * @since 0.6.0 */ export async function deleteContainer( container: Url | UrlString | WithResourceInfo, options: Partial< typeof internal_defaultFetchOptions > = internal_defaultFetchOptions ): Promise<void> { const url = hasResourceInfo(container) ? internal_toIriString(getSourceUrl(container)) : internal_toIriString(container); if (!isContainer(container)) { throw new Error( `You're trying to delete the Container at [${url}], but Container URLs should end in a \`/\`. Are you sure this is a Container?` ); } const config = { ...internal_defaultFetchOptions, ...options, }; const response = await config.fetch(url, { method: "DELETE" }); if (internal_isUnsuccessfulResponse(response)) { throw new FetchError( `Deleting the Container at [${url}] failed: [${response.status}] [${response.statusText}].`, response ); } } /** * Given a [[SolidDataset]] representing a Container (see [[isContainer]]), fetch the URLs of all * contained resources. * If the solidDataset given is not a container, or is missing resourceInfo, throw an error. * * @param solidDataset The container from which to fetch all contained Resource URLs. * @returns A list of URLs, each of which points to a contained Resource of the given SolidDataset. * @since 1.3.0 */ export function getContainedResourceUrlAll( solidDataset: SolidDataset & WithResourceInfo ): UrlString[] { const container = getThing(solidDataset, getSourceUrl(solidDataset)); // See https://www.w3.org/TR/2015/REC-ldp-20150226/#h-ldpc-http_post: // > a containment triple MUST be added to the state of the LDPC whose subject is the LDPC URI, // > whose predicate is ldp:contains and whose object is the URI for the newly created document return container !== null ? getIriAll(container, ldp.contains) : []; } /** * Gets a human-readable representation of the given SolidDataset to aid debugging. * * Note that changes to the exact format of the return value are not considered a breaking change; * it is intended to aid in debugging, not as a serialisation method that can be reliably parsed. * * @param solidDataset The [[SolidDataset]] to get a human-readable representation of. * @since 0.3.0 */ export function solidDatasetAsMarkdown(solidDataset: SolidDataset): string { let readableSolidDataset: string = ""; if (hasResourceInfo(solidDataset)) { readableSolidDataset += `# SolidDataset: ${getSourceUrl(solidDataset)}\n`; } else { readableSolidDataset += `# SolidDataset (no URL yet)\n`; } const things = getThingAll(solidDataset); if (things.length === 0) { readableSolidDataset += "\n<empty>\n"; } else { things.forEach((thing) => { readableSolidDataset += "\n" + thingAsMarkdown(thing); if (hasChangelog(solidDataset)) { readableSolidDataset += "\n" + getReadableChangeLogSummary(solidDataset, thing) + "\n"; } }); } return readableSolidDataset; } /** * Gets a human-readable representation of the local changes to a Resource to aid debugging. * * Note that changes to the exact format of the return value are not considered a breaking change; * it is intended to aid in debugging, not as a serialisation method that can be reliably parsed. * * @param solidDataset The Resource of which to get a human-readable representation of the changes applied to it locally. * @since 0.3.0 */ export function changeLogAsMarkdown( solidDataset: SolidDataset & WithChangeLog ): string { if (!hasResourceInfo(solidDataset)) { return "This is a newly initialized SolidDataset, so there is no source to compare it to."; } if ( !hasChangelog(solidDataset) || (solidDataset.internal_changeLog.additions.length === 0 && solidDataset.internal_changeLog.deletions.length === 0) ) { return ( `## Changes compared to ${getSourceUrl(solidDataset)}\n\n` + `This SolidDataset has not been modified since it was fetched from ${getSourceUrl( solidDataset )}.\n` ); } let readableChangeLog = `## Changes compared to ${getSourceUrl( solidDataset )}\n`; const changeLogsByThingAndProperty = sortChangeLogByThingAndProperty(solidDataset); Object.keys(changeLogsByThingAndProperty).forEach((thingUrl) => { readableChangeLog += `\n### Thing: ${thingUrl}\n`; const changeLogByProperty = changeLogsByThingAndProperty[thingUrl]; Object.keys(changeLogByProperty).forEach((propertyUrl) => { readableChangeLog += `\nProperty: ${propertyUrl}\n`; const deleted = changeLogByProperty[propertyUrl].deleted; const added = changeLogByProperty[propertyUrl].added; if (deleted.length > 0) { readableChangeLog += "- Removed:\n"; deleted.forEach( (deletedValue) => (readableChangeLog += ` - ${internal_getReadableValue( deletedValue )}\n`) ); } if (added.length > 0) { readableChangeLog += "- Added:\n"; added.forEach( (addedValue) => (readableChangeLog += ` - ${internal_getReadableValue( addedValue )}\n`) ); } }); }); return readableChangeLog; } function sortChangeLogByThingAndProperty( solidDataset: WithChangeLog & WithResourceInfo ) { const changeLogsByThingAndProperty: Record< UrlString, Record<UrlString, { added: Quad_Object[]; deleted: Quad_Object[] }> > = {}; solidDataset.internal_changeLog.deletions.forEach((deletion) => { const subjectNode = isLocalNode(deletion.subject) ? /* istanbul ignore next: Unsaved deletions should be removed from the additions list instead, so this code path shouldn't be hit: */ resolveIriForLocalNode(deletion.subject, getSourceUrl(solidDataset)) : deletion.subject; if (!isNamedNode(subjectNode) || !isNamedNode(deletion.predicate)) { return; } const thingUrl = internal_toIriString(subjectNode); const propertyUrl = internal_toIriString(deletion.predicate); changeLogsByThingAndProperty[thingUrl] ??= {}; changeLogsByThingAndProperty[thingUrl][propertyUrl] ??= { added: [], deleted: [], }; changeLogsByThingAndProperty[thingUrl][propertyUrl].deleted.push( deletion.object ); }); solidDataset.internal_changeLog.additions.forEach((addition) => { const subjectNode = isLocalNode(addition.subject) ? /* istanbul ignore next: setThing already resolves local Subjects when adding them, so this code path should never be hit. */ resolveIriForLocalNode(addition.subject, getSourceUrl(solidDataset)) : addition.subject; if (!isNamedNode(subjectNode) || !isNamedNode(addition.predicate)) { return; } const thingUrl = internal_toIriString(subjectNode); const propertyUrl = internal_toIriString(addition.predicate); changeLogsByThingAndProperty[thingUrl] ??= {}; changeLogsByThingAndProperty[thingUrl][propertyUrl] ??= { added: [], deleted: [], }; changeLogsByThingAndProperty[thingUrl][propertyUrl].added.push( addition.object ); }); return changeLogsByThingAndProperty; } function getReadableChangeLogSummary( solidDataset: WithChangeLog, thing: Thing ): string { const subject = DataFactory.namedNode(thing.url); const nrOfAdditions = solidDataset.internal_changeLog.additions.reduce( (count, addition) => (addition.subject.equals(subject) ? count + 1 : count), 0 ); const nrOfDeletions = solidDataset.internal_changeLog.deletions.reduce( (count, deletion) => (deletion.subject.equals(subject) ? count + 1 : count), 0 ); const additionString = nrOfAdditions === 1 ? "1 new value added" : nrOfAdditions + " new values added"; const deletionString = nrOfDeletions === 1 ? "1 value removed" : nrOfDeletions + " values removed"; return `(${additionString} / ${deletionString})`; } function getNamedNodesForLocalNodes(quad: Quad): Quad { const subject = isNamedNode(quad.subject) ? getNamedNodeFromLocalNode(quad.subject) : /* istanbul ignore next: We don't allow non-NamedNodes as the Subject, so this code path should never be hit: */ quad.subject; const object = isNamedNode(quad.object) ? getNamedNodeFromLocalNode(quad.object) : quad.object; return DataFactory.quad(subject, quad.predicate, object, quad.graph); } function getNamedNodeFromLocalNode(node: LocalNode | NamedNode): NamedNode { if (isLocalNodeIri(node.value)) { return DataFactory.namedNode("#" + getLocalNodeName(node.value)); } return node; } function resolveLocalIrisInSolidDataset< Dataset extends SolidDataset & WithResourceInfo >(solidDataset: Dataset): Dataset { const resourceIri = getSourceUrl(solidDataset); const defaultGraph = solidDataset.graphs.default; const thingIris = Object.keys(defaultGraph); const updatedDefaultGraph = thingIris.reduce((graphAcc, thingIri) => { const resolvedThing = resolveLocalIrisInThing( graphAcc[thingIri], resourceIri ); const resolvedThingIri = isLocalNodeIri(thingIri) ? `${resourceIri}#${getLocalNodeName(thingIri)}` : thingIri; const updatedGraph = { ...graphAcc }; delete updatedGraph[thingIri]; updatedGraph[resolvedThingIri] = resolvedThing; return freeze(updatedGraph); }, defaultGraph); const updatedGraphs = freeze({ ...solidDataset.graphs, default: updatedDefaultGraph, }); return freeze({ ...solidDataset, graphs: updatedGraphs, }); } function resolveLocalIrisInThing( thing: Thing, baseIri: IriString ): ThingPersisted { const predicateIris = Object.keys(thing.predicates); const updatedPredicates = predicateIris.reduce( (predicatesAcc, predicateIri) => { const namedNodes = predicatesAcc[predicateIri].namedNodes ?? []; if (namedNodes.every((namedNode) => !isLocalNodeIri(namedNode))) { // This Predicate has no local node Objects, so return it unmodified: return predicatesAcc; } const updatedNamedNodes = freeze( namedNodes.map((namedNode) => isLocalNodeIri(namedNode) ? `${baseIri}#${getLocalNodeName(namedNode)}` : namedNode ) ); const updatedPredicate = freeze({ ...predicatesAcc[predicateIri], namedNodes: updatedNamedNodes, }); return freeze({ ...predicatesAcc, [predicateIri]: updatedPredicate, }); }, thing.predicates ); return freeze({ ...thing, predicates: updatedPredicates, url: isLocalNodeIri(thing.url) ? `${baseIri}#${getLocalNodeName(thing.url)}` : thing.url, }); } /** * Fetch the contents of '.well-known/solid' for a given resource URL. * * The contents of the '.well-known/solid' endpoint define the capabilities of the server, and provide their associated endpoints/locations. * This behaves similarly to the use of '.well-known' endpoints in e.g. (OIDC servers)[https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig] * * @param url URL of a Resource. * @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters). * @returns Promise resolving to a [[SolidDataset]] containing the data at '.well-known/solid' for the given Resource, or rejecting if fetching it failed. * @since 1.12.0 */ export async function getWellKnownSolid( url: UrlString | Url, options: Partial< typeof internal_defaultFetchOptions & ParseOptions > = internal_defaultFetchOptions ): Promise<SolidDataset & WithServerResourceInfo> { const urlString = internal_toIriString(url); const resourceMetadata = await getResourceInfo(urlString, { fetch: options.fetch, // Discovering the .well-known/solid document is useful even for resources // we don't have access to. ignoreAuthenticationErrors: true, }); const linkedResources = getLinkedResourceUrlAll(resourceMetadata); const rootResources = linkedResources[pim.storage]; const rootResource = rootResources?.length === 1 ? rootResources[0] : null; if (rootResource !== null) { const wellKnownSolidUrl = new URL( ".well-known/solid", rootResource.endsWith("/") ? rootResource : rootResource + "/" ).href; try { return await getSolidDataset(wellKnownSolidUrl, { ...options, parsers: { "application/ld+json": getJsonLdParser(), }, }); } catch (e) { // In case of error, do nothing and try to discover the .well-known // at the root of the domain. } } const wellKnownSolidUrl = new URL( "/.well-known/solid", new URL(urlString).origin ).href; return getSolidDataset(wellKnownSolidUrl, { ...options, parsers: { "application/ld+json": getJsonLdParser(), }, }); }
the_stack
module BABYLON { @className("Group2D", "BABYLON") /** * A non renderable primitive that defines a logical group. * Can also serve the purpose of caching its content into a bitmap to reduce rendering overhead */ export class Group2D extends Prim2DBase { static GROUP2D_PROPCOUNT: number = Prim2DBase.PRIM2DBASE_PROPCOUNT + 5; public static sizeProperty: Prim2DPropInfo; public static actualSizeProperty: Prim2DPropInfo; /** * Default behavior, the group will use the caching strategy defined at the Canvas Level */ public static GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0; /** * When used, this group's content won't be cached, no matter which strategy used. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap. */ public static GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1; /** * When used, the group's content will be cached in the nearest cached parent group/canvas */ public static GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2; /** * You can specify this behavior to any cached Group2D to indicate that you don't want the cached content to be resized when the Group's actualScale is changing. It will draw the content stretched or shrink which is faster than a resize. This setting is obviously for performance consideration, don't use it if you want the best rendering quality */ public static GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100; private static GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF; /** * Create an Logical or Renderable Group. * @param settings a combination of settings, possible ones are * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting) * - children: an array of direct children * - id a text identifier, for information purpose * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0] * - rotation: the initial rotation (in radian) of the primitive. default is 0 * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property * - trackNode: if you want the ScreenSpaceCanvas to track the position of a given Scene Node, use this setting to specify the Node to track * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent. * - zOrder: override the zOrder with the specified value * - origin: define the normalized origin point location, default [0.5;0.5] * - size: the size of the group. Alternatively the width and height properties can be set. If null the size will be computed from its content, default is null. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY * - layoutEngine: either an instance of a layout engine based class (StackPanel.Vertical, StackPanel.Horizontal) or a string ('canvas' for Canvas layout, 'StackPanel' or 'HorizontalStackPanel' for horizontal Stack Panel layout, 'VerticalStackPanel' for vertical Stack Panel layout). * - isVisible: true if the group must be visible, false for hidden. Default is true. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersect, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED! * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision). * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString) * - marginHAlignment: one value of the PrimitiveAlignment type's static properties * - marginVAlignment: one value of the PrimitiveAlignment type's static properties * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString) */ constructor(settings?: { parent ?: Prim2DBase, children ?: Array<Prim2DBase>, id ?: string, position ?: Vector2, x ?: number, y ?: number, scale ?: number, scaleX ?: number, scaleY ?: number, dontInheritParentScale ?: boolean, trackNode ?: Node, trackNodeOffset ?: Vector3, opacity ?: number, zOrder ?: number, origin ?: Vector2, size ?: Size, width ?: number, height ?: number, cacheBehavior ?: number, layoutEngine ?: LayoutEngineBase | string, isVisible ?: boolean, isPickable ?: boolean, isContainer ?: boolean, childrenFlatZOrder ?: boolean, levelCollision ?: boolean, deepCollision ?: boolean, layoutData ?: ILayoutData, marginTop ?: number | string, marginLeft ?: number | string, marginRight ?: number | string, marginBottom ?: number | string, margin ?: number | string, marginHAlignment ?: number, marginVAlignment ?: number, marginAlignment ?: string, paddingTop ?: number | string, paddingLeft ?: number | string, paddingRight ?: number | string, paddingBottom ?: number | string, padding ?: number | string, }) { if (settings == null) { settings = {}; } if (settings.origin == null) { settings.origin = new Vector2(0, 0); } super(settings); let size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new Size(settings.width || 0, settings.height || 0))); if (!(this instanceof WorldSpaceCanvas2D)) { this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode; this._trackedNodeOffset = (settings.trackNodeOffset == null) ? null : settings.trackNodeOffset; if (this._trackedNode && this.owner) { this.owner._registerTrackedNode(this); } } this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior; let rd = this._renderableData; if (rd) { rd._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0; } this.size = size; this._viewportPosition = Vector2.Zero(); this._viewportSize = Size.Zero(); } static _createCachedCanvasGroup(owner: Canvas2D): Group2D { var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: Vector2.Zero(), origin: Vector2.Zero(), size: null, isVisible: true, isPickable: false, dontInheritParentScale: true }); return g; } protected applyCachedTexture(vertexData: VertexData, material: StandardMaterial) { this._bindCacheTarget(); if (vertexData) { var uv = vertexData.uvs; let nodeuv = this._renderableData._cacheNodeUVs; for (let i = 0; i < 4; i++) { uv[i * 2 + 0] = nodeuv[i].x; uv[i * 2 + 1] = nodeuv[i].y; } } if (material) { material.diffuseTexture = this._renderableData._cacheTexture; material.emissiveColor = new Color3(1, 1, 1); } this._renderableData._cacheTexture.hasAlpha = true; this._unbindCacheTarget(); } /** * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture. * If the `noWorldSpaceNode` options was used at the creation of a WorldSpaceCanvas, the rendering of the canvas must be made by the caller, so typically you want to bind the cacheTexture property to some material/mesh and you MUST use the Group2D.cachedUVs property to get the UV coordinates to use for your quad that will display the Canvas and NOT the PackedRect.UVs property which are incorrect because the allocated surface may be bigger (due to over-provisioning or shrinking without deallocating) than what the Group is actually using. */ public get cachedRect(): PackedRect { if (!this._renderableData) { return null; } return this._renderableData._cacheNode; } /** * The UVs into the MapTexture that map the cached group */ public get cachedUVs(): Vector2[] { if (!this._renderableData) { return null; } return this._renderableData._cacheNodeUVs; } public get cachedUVsChanged(): Observable<Vector2[]> { if (!this._renderableData) { return null; } if (!this._renderableData._cacheNodeUVsChangedObservable) { this._renderableData._cacheNodeUVsChangedObservable = new Observable<Vector2[]>(); } return this._renderableData._cacheNodeUVsChangedObservable; } /** * Access the texture that maintains a cached version of the Group2D. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself. */ public get cacheTexture(): MapTexture { if (!this._renderableData) { return null; } return this._renderableData._cacheTexture; } /** * Call this method to remove this Group and its children from the Canvas */ public dispose(): boolean { if (!super.dispose()) { return false; } if (this._trackedNode != null) { this.owner._unregisterTrackedNode(this); this._trackedNode = null; } if (this._renderableData) { this._renderableData.dispose(this.owner); this._renderableData = null; } return true; } /** * @returns Returns true if the Group render content, false if it's a logical group only */ public get isRenderableGroup(): boolean { return this._isRenderableGroup; } /** * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time */ public get isCachedGroup(): boolean { return this._isCachedGroup; } @instanceLevelProperty(Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, pi => Group2D.sizeProperty = pi, false, true) public get size(): Size { return this.internalGetSize(); } /** * Get/Set the size of the group. If null the size of the group will be determine from its content. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does. */ public set size(val: Size) { this.internalSetSize(val); } public get viewportSize(): ISize { return this._viewportSize; } /** * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all. */ public get cacheBehavior(): number { return this._cacheBehavior; } public _addPrimToDirtyList(prim: Prim2DBase) { this._renderableData._primDirtyList.push(prim); } public _renderCachedCanvas() { this.owner._addGroupRenderCount(1); this.updateCachedStates(true); let context = new PrepareRender2DContext(); this._prepareGroupRender(context); this._groupRender(); } /** * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node. */ public get trackedNode(): Node { return this._trackedNode; } public set trackedNode(val: Node) { if (val != null) { if (!this._isFlagSet(SmartPropertyPrim.flagTrackedGroup)) { this.owner._registerTrackedNode(this); } this._trackedNode = val; } else { if (this._isFlagSet(SmartPropertyPrim.flagTrackedGroup)) { this.owner._unregisterTrackedNode(this); } this._trackedNode = null; } } /** * Get/set the offset of the tracked node in the tracked node's local space. */ public get trackedNodeOffset(): Vector3 { return this._trackedNodeOffset; } public set trackedNodeOffset(val: Vector3) { if (!this._trackedNodeOffset) { this._trackedNodeOffset = val.clone(); } else { this._trackedNodeOffset.copyFrom(val); } } protected levelIntersect(intersectInfo: IntersectInfo2D): boolean { // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true return true; } protected updateLevelBoundingInfo(): boolean { let size: Size; // If the size is set by the user, the boundingInfo is computed from this value if (this.size) { size = this.size; } // Otherwise the group's level bounding info is "collapsed" else { size = new Size(0, 0); } BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo); return true; } // Method called only on renderable groups to prepare the rendering protected _prepareGroupRender(context: PrepareRender2DContext) { let sortedDirtyList: Prim2DBase[] = null; // Update the Global Transformation and visibility status of the changed primitives let rd = this._renderableData; let curPrimDirtyList = rd._primDirtyList; if ((curPrimDirtyList.length > 0) || context.forceRefreshPrimitive) { // From now on we use the 'curPrimDirtyList' variable to process the primitives that was marked as dirty // But we also allocate a new array in the object's member to get the prim that will be dirty again during the process // and that would need another process next time. rd._primDirtyList = new Array<Prim2DBase>(); // Sort the primitives to process them from the highest in the tree to the lowest sortedDirtyList = curPrimDirtyList.sort((a, b) => a.hierarchyDepth - b.hierarchyDepth); this.updateCachedStatesOf(sortedDirtyList, true); } let s = this.actualSize; let a = this.actualScale; let ss = this.owner._canvasLevelScale; let hwsl = 1/this.owner.engine.getHardwareScalingLevel(); //let sw = Math.ceil(s.width * a.x * ss.x/* * hwsl*/); //let sh = Math.ceil(s.height * a.y *ss.y/* * hwsl*/); let sw = s.width * a.x * ss.x; let sh = s.height * a.y *ss.y; // The dimension must be overridden when using the designSize feature, the ratio is maintain to compute a uniform scale, which is mandatory but if the designSize's ratio is different from the rendering surface's ratio, content will be clipped in some cases. // So we set the width/height to the rendering's one because that's what we want for the viewport! if ((this instanceof Canvas2D || this.id === "__cachedCanvasGroup__") && this.owner.designSize != null) { sw = this.owner.engine.getRenderWidth(); sh = this.owner.engine.getRenderHeight(); } // Setup the size of the rendering viewport // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute if (!this._isCachedGroup) { // Compute the WebGL viewport's location/size let t = this._globalTransform.getTranslation(); let rs = this.owner._renderingSize.multiplyByFloats(hwsl, hwsl); sh = Math.min(sh, rs.height - t.y); sw = Math.min(sw, rs.width - t.x); let x = t.x; let y = t.y; // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed this._viewportPosition.x = x; this._viewportPosition.y = y; } // For a cachedGroup we also check of the group's actualSize is changing, if it's the case then the rendering zone will be change so we also have to dirty all primitives to prepare them again. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) { context.forceRefreshPrimitive = true; this._viewportSize.width = sw; this._viewportSize.height = sh; } if ((curPrimDirtyList.length > 0) || context.forceRefreshPrimitive) { // If the group is cached, set the dirty flag to true because of the incoming changes this._cacheGroupDirty = this._isCachedGroup; rd._primNewDirtyList.splice(0); // If it's a force refresh, prepare all the children if (context.forceRefreshPrimitive) { for (let p of this._children) { if (!p.isDisposed) { p._prepareRender(context); } } } else { // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using // the hierarchyDepth in order to prepare primitives from top to bottom if (!sortedDirtyList) { sortedDirtyList = curPrimDirtyList.sort((a, b) => a.hierarchyDepth - b.hierarchyDepth); } sortedDirtyList.forEach(p => { // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check. if (!p.isDisposed && p._needPrepare()) { p._prepareRender(context); } }); } // Everything is updated, clear the dirty list curPrimDirtyList.forEach(p => { if (rd._primNewDirtyList.indexOf(p) === -1) { p._resetPropertiesDirty(); } else { p._setFlags(SmartPropertyPrim.flagNeedRefresh); } }); rd._primDirtyList = curPrimDirtyList.concat(rd._primNewDirtyList); } // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them rd._childrenRenderableGroups.forEach(g => { g._prepareGroupRender(context); }); } protected _groupRender() { let engine = this.owner.engine; let failedCount = 0; // First recurse to children render group to render them (in their cache or on screen) for (let childGroup of this._renderableData._childrenRenderableGroups) { childGroup._groupRender(); } // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed if (!this.isCachedGroup || this._cacheGroupDirty) { this.owner._addGroupRenderCount(1); if (this.isCachedGroup) { this._bindCacheTarget(); } else { var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height); } let curAlphaTest = engine.getAlphaTesting() === true; let curDepthWrite = engine.getDepthWrite() === true; // =================================================================== // First pass, update the InstancedArray and render Opaque primitives // Disable Alpha Testing, Enable Depth Write engine.setAlphaTesting(false); engine.setDepthWrite(true); // For each different model of primitive to render let context = new Render2DContext(Render2DContext.RenderModeOpaque); this._renderableData._renderGroupInstancesInfo.forEach((k, v) => { // Prepare the context object, update the WebGL Instanced Array buffer if needed let renderCount = this._prepareContext(engine, context, v); // If null is returned, there's no opaque data to render if (renderCount === null) { return; } // Submit render only if we have something to render (everything may be hidden and the floatarray empty) if (!this.owner.supportInstancedArray || renderCount > 0) { // render all the instances of this model, if the render method returns true then our instances are no longer dirty let renderFailed = !v.modelRenderCache.render(v, context); // Update dirty flag/related v.opaqueDirty = renderFailed; failedCount += renderFailed ? 1 : 0; } }); // ======================================================================= // Second pass, update the InstancedArray and render AlphaTest primitives // Enable Alpha Testing, Enable Depth Write engine.setAlphaTesting(true); engine.setDepthWrite(true); // For each different model of primitive to render context = new Render2DContext(Render2DContext.RenderModeAlphaTest); this._renderableData._renderGroupInstancesInfo.forEach((k, v) => { // Prepare the context object, update the WebGL Instanced Array buffer if needed let renderCount = this._prepareContext(engine, context, v); // If null is returned, there's no opaque data to render if (renderCount === null) { return; } // Submit render only if we have something to render (everything may be hidden and the floatarray empty) if (!this.owner.supportInstancedArray || renderCount > 0) { // render all the instances of this model, if the render method returns true then our instances are no longer dirty let renderFailed = !v.modelRenderCache.render(v, context); // Update dirty flag/related v.opaqueDirty = renderFailed; failedCount += renderFailed ? 1 : 0; } }); // ======================================================================= // Third pass, transparent primitive rendering // Enable Alpha Testing, Disable Depth Write engine.setAlphaTesting(true); engine.setDepthWrite(false); // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed) if (this._renderableData._transparentListChanged) { this._updateTransparentData(); } // From this point on we have up to date data to render, so let's go failedCount += this._renderTransparentData(); // ======================================================================= // Unbind target/restore viewport setting, clear dirty flag, and quit // The group's content is no longer dirty this._cacheGroupDirty = failedCount !== 0; if (this.isCachedGroup) { this._unbindCacheTarget(); } else { if (curVP) { engine.setViewport(curVP); } } this._renderableData.resetPrimDirtyList(); // Restore saved states engine.setAlphaTesting(curAlphaTest); engine.setDepthWrite(curDepthWrite); } } public _setCacheGroupDirty() { this._cacheGroupDirty = true; } private _updateTransparentData() { this.owner._addUpdateTransparentDataCount(1); let rd = this._renderableData; // Sort all the primitive from their depth, max (bottom) to min (top) rd._transparentPrimitives.sort((a, b) => b._primitive.actualZOffset - a._primitive.actualZOffset); let checkAndAddPrimInSegment = (seg: TransparentSegment, tpiI: number): boolean => { let tpi = rd._transparentPrimitives[tpiI]; // Fast rejection: if gii are different if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) { return false; } //let tpiZ = tpi._primitive.actualZOffset; // We've made it so far, the tpi can be part of the segment, add it tpi._transparentSegment = seg; tpi._primitive._updateTransparentSegmentIndices(seg); return true; } // Free the existing TransparentSegments for (let ts of rd._transparentSegments) { ts.dispose(this.owner.engine); } rd._transparentSegments.splice(0); let prevSeg = null; for (let tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) { let tpi = rd._transparentPrimitives[tpiI]; // Check if the Data in which the primitive is stored is not sorted properly if (tpi._groupInstanceInfo.transparentOrderDirty) { tpi._groupInstanceInfo.sortTransparentData(); } // Reset the segment, we have to create/rebuild it tpi._transparentSegment = null; // If there's a previous valid segment, check if this prim can be part of it if (prevSeg) { checkAndAddPrimInSegment(prevSeg, tpiI); } // If we couldn't insert in the adjacent segments, he have to create one if (!tpi._transparentSegment) { let ts = new TransparentSegment(); ts.groupInsanceInfo = tpi._groupInstanceInfo; let prim = tpi._primitive; ts.startZ = prim.actualZOffset; prim._updateTransparentSegmentIndices(ts); ts.endZ = ts.startZ; tpi._transparentSegment = ts; rd._transparentSegments.push(ts); } // Update prevSeg prevSeg = tpi._transparentSegment; } //rd._firstChangedPrim = null; rd._transparentListChanged = false; } private _renderTransparentData(): number { let failedCount = 0; let context = new Render2DContext(Render2DContext.RenderModeTransparent); let rd = this._renderableData; let useInstanced = this.owner.supportInstancedArray; let length = rd._transparentSegments.length; for (let i = 0; i < length; i++) { context.instancedBuffers = null; let ts = rd._transparentSegments[i]; let gii = ts.groupInsanceInfo; let mrc = gii.modelRenderCache; let engine = this.owner.engine; let count = ts.endDataIndex - ts.startDataIndex; // Use Instanced Array if it's supported and if there's at least minPartCountToUseInstancedArray prims to draw. // We don't want to create an Instanced Buffer for less that minPartCountToUseInstancedArray prims if (useInstanced && count >= this.owner.minPartCountToUseInstancedArray) { if (!ts.partBuffers) { let buffers = new Array<WebGLBuffer>(); for (let j = 0; j < gii.transparentData.length; j++) { let gitd = gii.transparentData[j]; let dfa = gitd._partData; let data = dfa.pack(); let stride = dfa.stride; let neededSize = count * stride * 4; let buffer = engine.createInstancesBuffer(neededSize); // Create + bind let segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride); engine.updateArrayBuffer(segData); buffers.push(buffer); } ts.partBuffers = buffers; } else if (gii.transparentDirty) { for (let j = 0; j < gii.transparentData.length; j++) { let gitd = gii.transparentData[j]; let dfa = gitd._partData; let data = dfa.pack(); let stride = dfa.stride; let buffer = ts.partBuffers[j]; let segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride); engine.bindArrayBuffer(buffer); engine.updateArrayBuffer(segData); } } context.useInstancing = true; context.instancesCount = count; context.instancedBuffers = ts.partBuffers; context.groupInfoPartData = gii.transparentData; let renderFailed = !mrc.render(gii, context); failedCount += renderFailed ? 1 : 0; } else { context.useInstancing = false; context.partDataStartIndex = ts.startDataIndex; context.partDataEndIndex = ts.endDataIndex; context.groupInfoPartData = gii.transparentData; let renderFailed = !mrc.render(gii, context); failedCount += renderFailed ? 1 : 0; } } return failedCount; } private _prepareContext(engine: Engine, context: Render2DContext, gii: GroupInstanceInfo): number { let gipd: GroupInfoPartData[] = null; let setDirty: (dirty: boolean) => void; let getDirty: () => boolean; // Render Mode specifics switch (context.renderMode) { case Render2DContext.RenderModeOpaque: { if (!gii.hasOpaqueData) { return null; } setDirty = (dirty: boolean) => { gii.opaqueDirty = dirty; }; getDirty = () => gii.opaqueDirty; context.groupInfoPartData = gii.opaqueData; gipd = gii.opaqueData; break; } case Render2DContext.RenderModeAlphaTest: { if (!gii.hasAlphaTestData) { return null; } setDirty = (dirty: boolean) => { gii.alphaTestDirty = dirty; }; getDirty = () => gii.alphaTestDirty; context.groupInfoPartData = gii.alphaTestData; gipd = gii.alphaTestData; break; } default: throw new Error("_prepareContext is only for opaque or alphaTest"); } let renderCount = 0; // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer // Skip it if instanced arrays are not supported if (this.owner.supportInstancedArray) { // Flag for instancing context.useInstancing = true; // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render. for (let i = 0; i < gipd.length; i++) { let pid = gipd[i]; // If the instances of the model was changed, pack the data let array = pid._partData; let instanceData = array.pack(); renderCount += array.usedElementCount; // Compute the size the instance buffer should have let neededSize = array.usedElementCount * array.stride * 4; // Check if we have to (re)create the instancesBuffer because there's none or the size is too small if (!pid._partBuffer || (pid._partBufferSize < neededSize)) { if (pid._partBuffer) { engine.deleteInstancesBuffer(pid._partBuffer); } pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind pid._partBufferSize = neededSize; setDirty(false); // Update the WebGL buffer to match the new content of the instances data engine.updateArrayBuffer(instanceData); } else if (getDirty()) { // Update the WebGL buffer to match the new content of the instances data engine.bindArrayBuffer(pid._partBuffer); engine.updateArrayBuffer(instanceData); } } setDirty(false); } // Can't rely on hardware instancing, use the DynamicFloatArray instance, render its whole content else { context.partDataStartIndex = 0; // Find the first valid object to get the count if (context.groupInfoPartData.length > 0) { let i = 0; while (!context.groupInfoPartData[i]) { i++; } context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount; } } return renderCount; } protected _setRenderingScale(scale: number) { if (this._renderableData._renderingScale === scale) { return; } this._renderableData._renderingScale = scale; } private static _uV = new Vector2(1, 1); private static _s = Size.Zero(); private static _v1 = Vector2.Zero(); private static _s2 = Size.Zero(); private _bindCacheTarget() { let curWidth: number; let curHeight: number; let rd = this._renderableData; let rs = rd._renderingScale; let noResizeScale = rd._noResizeOnScale; let isCanvas = this.parent == null; let scale: Vector2; if (noResizeScale) { scale = isCanvas ? Group2D._uV: this.parent.actualScale.multiply(this.owner._canvasLevelScale); } else { scale = this.actualScale.multiply(this.owner._canvasLevelScale); } let actualSize = this.actualSize; if (isCanvas && this.owner.cachingStrategy===Canvas2D.CACHESTRATEGY_CANVAS && this.owner.isScreenSpace) { if(this.owner.designSize || this.owner.fitRenderingDevice){ Group2D._s.width = this.owner.engine.getRenderWidth(); Group2D._s.height = this.owner.engine.getRenderHeight(); } else{ Group2D._s.copyFrom(this.owner.size); } } else { Group2D._s.width = Math.ceil(actualSize.width * scale.x * rs); Group2D._s.height = Math.ceil(actualSize.height * scale.y * rs); } let sizeChanged = !Group2D._s.equals(rd._cacheSize); if (rd._cacheNode) { let size = Group2D._s2; rd._cacheNode.getInnerSizeToRef(size); // Check if we have to deallocate because the size is too small if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) { // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels... // For World space: no over-provisioning let overprovisioning = this.owner.isScreenSpace ? 1.07 : 1; curWidth = Math.floor(Group2D._s.width * overprovisioning); curHeight = Math.floor(Group2D._s.height * overprovisioning); //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`); rd._cacheTexture.freeRect(rd._cacheNode); rd._cacheNode = null; } } if (!rd._cacheNode) { // Check if we have to allocate a rendering zone in the global cache texture var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel); rd._cacheNode = res.node; rd._cacheTexture = res.texture; if (rd._cacheRenderSprite) { rd._cacheRenderSprite.dispose(); } rd._cacheRenderSprite = res.sprite; sizeChanged = true; } else if (sizeChanged) { let sprite = rd._cacheRenderSprite; if (sprite) { sprite.size = actualSize; sprite.spriteSize = new Size(actualSize.width * scale.x * rs, actualSize.height * scale.y * rs); } } if (sizeChanged) { rd._cacheSize.copyFrom(Group2D._s); rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize); if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) { rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs); } this._setFlags(SmartPropertyPrim.flagWorldCacheChanged); } let pos = Group2D._v1; rd._cacheNode.getInnerPosToRef(pos); rd._cacheTexture.bindTextureForPosSize(pos, Group2D._s, true); } private _unbindCacheTarget() { if (this._renderableData._cacheTexture) { this._renderableData._cacheTexture.unbindTexture(); } } protected _spreadActualScaleDirty() { if (this._renderableData && this._renderableData._cacheRenderSprite) { this.handleGroupChanged(Prim2DBase.actualScaleProperty); } super._spreadActualScaleDirty(); } protected static _unS = new Vector2(1, 1); protected handleGroupChanged(prop: Prim2DPropInfo) { // This method is only for cachedGroup let rd = this._renderableData; if (!rd) { return; } let cachedSprite = rd._cacheRenderSprite; if (!this.isCachedGroup || !cachedSprite) { return; } // For now we only support these property changes // TODO: add more! :) switch (prop.id) { case Prim2DBase.actualPositionProperty.id: cachedSprite.actualPosition = this.actualPosition.clone(); if (cachedSprite.position != null) { cachedSprite.position = cachedSprite.actualPosition.clone(); } break; case Prim2DBase.rotationProperty.id: cachedSprite.rotation = this.rotation; break; case Prim2DBase.scaleProperty.id: cachedSprite.scale = this.scale; break; case Prim2DBase.originProperty.id: cachedSprite.origin = this.origin.clone(); break; case Group2D.actualSizeProperty.id: cachedSprite.size = this.actualSize.clone(); break; case Group2D.xProperty.id: cachedSprite.x = this.x; break; case Group2D.yProperty.id: cachedSprite.y = this.y; } } private detectGroupStates() { var isCanvas = this instanceof Canvas2D; var canvasStrat = this.owner.cachingStrategy; // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group. if (canvasStrat === Canvas2D.CACHESTRATEGY_DONTCACHE) { this._isRenderableGroup = isCanvas; this._isCachedGroup = false; } // In Canvas cached only mode, only the Canvas is cached and renderable, all other groups are logicals else if (canvasStrat === Canvas2D.CACHESTRATEGY_CANVAS) { if (isCanvas) { this._isRenderableGroup = true; this._isCachedGroup = true; } else { this._isRenderableGroup = this.id === "__cachedCanvasGroup__"; this._isCachedGroup = false; } } // Top Level Groups cached only mode, the canvas is a renderable/not cached, its direct Groups are cached/renderable, all other group are logicals else if (canvasStrat === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) { if (isCanvas) { this._isRenderableGroup = true; this._isCachedGroup = false; } else { if (this.hierarchyDepth === 1) { this._isRenderableGroup = true; this._isCachedGroup = true; } else { this._isRenderableGroup = false; this._isCachedGroup = false; } } } // All Group cached mode, all groups are renderable/cached, including the Canvas, groups with the behavior DONTCACHE are renderable/not cached, groups with CACHEINPARENT are logical ones else if (canvasStrat === Canvas2D.CACHESTRATEGY_ALLGROUPS) { if (isCanvas) { this._isRenderableGroup = true; this._isCachedGroup = false; } else { var gcb = this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK; if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) { this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE; this._isCachedGroup = false; } if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) { this._isRenderableGroup = true; this._isCachedGroup = true; } } } if (this._isRenderableGroup) { // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object... if (!this._renderableData) { this._renderableData = new RenderableGroupData(); } } // If the group is tagged as renderable we add it to the renderable tree if (this._isCachedGroup) { this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0; let cur = this.parent; while (cur) { if (cur instanceof Group2D && cur._isRenderableGroup) { if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) { cur._renderableData._childrenRenderableGroups.push(this); } break; } cur = cur.parent; } } } public get _cachedTexture(): MapTexture { if (this._renderableData) { return this._renderableData._cacheTexture; } return null; } private _trackedNode: Node; private _trackedNodeOffset: Vector3; protected _isRenderableGroup: boolean; protected _isCachedGroup: boolean; private _cacheGroupDirty: boolean; private _cacheBehavior: number; private _viewportPosition: Vector2; private _viewportSize: Size; public _renderableData: RenderableGroupData; } export class RenderableGroupData { constructor() { this._primDirtyList = new Array<Prim2DBase>(); this._primNewDirtyList = new Array<Prim2DBase>(); this._childrenRenderableGroups = new Array<Group2D>(); this._renderGroupInstancesInfo = new StringDictionary<GroupInstanceInfo>(); this._transparentPrimitives = new Array<TransparentPrimitiveInfo>(); this._transparentSegments = new Array<TransparentSegment>(); this._transparentListChanged = false; this._cacheNode = null; this._cacheTexture = null; this._cacheRenderSprite = null; this._renderingScale = 1; this._cacheNodeUVs = null; this._cacheNodeUVsChangedObservable = null; this._cacheSize = Size.Zero(); this._useMipMap = false; this._anisotropicLevel = 1; this._noResizeOnScale = false; } dispose(owner: Canvas2D) { let engine = owner.engine; if (this._cacheRenderSprite) { this._cacheRenderSprite.dispose(); this._cacheRenderSprite = null; } if (this._cacheTexture && this._cacheNode) { this._cacheTexture.freeRect(this._cacheNode); this._cacheTexture = null; this._cacheNode = null; } if (this._primDirtyList) { this._primDirtyList.splice(0); this._primDirtyList = null; } if (this._renderGroupInstancesInfo) { this._renderGroupInstancesInfo.forEach((k, v) => { v.dispose(); }); this._renderGroupInstancesInfo = null; } if (this._cacheNodeUVsChangedObservable) { this._cacheNodeUVsChangedObservable.clear(); this._cacheNodeUVsChangedObservable = null; } if (this._transparentSegments) { for (let ts of this._transparentSegments) { ts.dispose(engine); } this._transparentSegments.splice(0); this._transparentSegments = null; } } addNewTransparentPrimitiveInfo(prim: RenderablePrim2D, gii: GroupInstanceInfo): TransparentPrimitiveInfo { let tpi = new TransparentPrimitiveInfo(); tpi._primitive = prim; tpi._groupInstanceInfo = gii; tpi._transparentSegment = null; this._transparentPrimitives.push(tpi); this._transparentListChanged = true; return tpi; } removeTransparentPrimitiveInfo(tpi: TransparentPrimitiveInfo) { let index = this._transparentPrimitives.indexOf(tpi); if (index !== -1) { this._transparentPrimitives.splice(index, 1); this._transparentListChanged = true; } } transparentPrimitiveZChanged(tpi: TransparentPrimitiveInfo) { this._transparentListChanged = true; //this.updateSmallestZChangedPrim(tpi); } resetPrimDirtyList(){ let dirtyList = this._primDirtyList; let numDirty = dirtyList.length; for(let i = 0; i < numDirty; i++){ if(dirtyList[i]._isFlagSet(SmartPropertyPrim.flagPrimInDirtyList)){ dirtyList[i]._resetPropertiesDirty(); } } dirtyList.length = 0; } _primDirtyList: Array<Prim2DBase>; _primNewDirtyList: Array<Prim2DBase>; _childrenRenderableGroups: Array<Group2D>; _renderGroupInstancesInfo: StringDictionary<GroupInstanceInfo>; _cacheNode: PackedRect; _cacheTexture: MapTexture; _cacheRenderSprite: Sprite2D; _cacheNodeUVs: Vector2[]; _cacheNodeUVsChangedObservable: Observable<Vector2[]>; _cacheSize: Size; _useMipMap: boolean; _anisotropicLevel: number; _noResizeOnScale: boolean; _transparentListChanged: boolean; _transparentPrimitives: Array<TransparentPrimitiveInfo>; _transparentSegments: Array<TransparentSegment>; _renderingScale: number; } export class TransparentPrimitiveInfo { _primitive: RenderablePrim2D; _groupInstanceInfo: GroupInstanceInfo; _transparentSegment: TransparentSegment; } }
the_stack
namespace SchemeDesigner { /** * Event manager * @author Nikitchenko Sergey <nikitchenko.sergey@yandex.ru> */ export class EventManager { /** * Scheme object */ protected scheme: Scheme; /** * Is dragging */ protected isDragging: boolean = false; /** * Left button down */ protected leftButtonDown: boolean = false; /** * Hovered objects */ protected hoveredObjects: SchemeObject[] = []; /** * Last client position */ protected lastClientPosition: Coordinates; /** * distance for touch zoom */ protected touchDistance: number; /** * Last touch end time * @type {number} */ protected lastTouchEndTime: number = 0; /** * Delay for prevent double tap */ protected doubleTapDelay: number = 300; /** * Constructor * @param {SchemeDesigner.Scheme} scheme */ constructor(scheme: Scheme) { this.scheme = scheme; this.setLastClientPosition({ x: this.scheme.getWidth() / 2, y: this.scheme.getHeight() / 2 }); this.bindEvents(); } /** * Bind events */ protected bindEvents(): void { // mouse events this.scheme.getCanvas().addEventListener('mousedown', (e: MouseEvent) => { this.onMouseDown(e); }); this.scheme.getCanvas().addEventListener('mouseup', (e: MouseEvent) => { this.onMouseUp(e); }); this.scheme.getCanvas().addEventListener('click', (e: MouseEvent) => { this.onClick(e); }); this.scheme.getCanvas().addEventListener('dblclick', (e: MouseEvent) => { this.onDoubleClick(e); }); this.scheme.getCanvas().addEventListener('mousemove', (e: MouseEvent) => { this.onMouseMove(e); }); this.scheme.getCanvas().addEventListener('mouseout', (e: MouseEvent) => { this.onMouseOut(e); }); this.scheme.getCanvas().addEventListener('mouseenter', (e: MouseEvent) => { this.onMouseEnter(e); }); this.scheme.getCanvas().addEventListener('contextmenu', (e: MouseEvent) => { this.onContextMenu(e); }); // wheel this.scheme.getCanvas().addEventListener('mousewheel', (e: MouseWheelEvent) => { this.onMouseWheel(e); }); // for FF this.scheme.getCanvas().addEventListener('DOMMouseScroll', (e: MouseWheelEvent) => { this.onMouseWheel(e); }); // touch events this.scheme.getCanvas().addEventListener('touchstart', (e: TouchEvent) => { this.touchDistance = 0; this.onMouseDown(e); }); this.scheme.getCanvas().addEventListener('touchmove', (e: TouchEvent) => { if (!e.targetTouches) { return false; } if (e.targetTouches.length == 1) { // one finger - dragging this.onMouseMove(e); } else if (e.targetTouches.length == 2) { // two finger - zoom const p1 = e.targetTouches[0]; const p2 = e.targetTouches[1]; // euclidean distance let distance = Math.sqrt(Math.pow(p2.pageX - p1.pageX, 2) + Math.pow(p2.pageY - p1.pageY, 2)); let delta = 0; if(this.touchDistance) { delta = distance - this.touchDistance; } this.touchDistance = distance; if (delta) { this.scheme.getZoomManager().zoomToPointer(e, delta / 5); } } e.preventDefault(); }); this.scheme.getCanvas().addEventListener('touchend', (e: TouchEvent) => { // prevent double tap zoom let now = (new Date()).getTime(); if (this.lastTouchEndTime && now - this.lastTouchEndTime <= this.doubleTapDelay) { e.preventDefault(); } else { this.onMouseUp(e); } this.lastTouchEndTime = now; }); this.scheme.getCanvas().addEventListener('touchcancel', (e: TouchEvent) => { this.onMouseUp(e); }); // resize window.addEventListener('resize', (e: Event) => { let prevScale = this.scheme.getZoomManager().getScale(); this.scheme.resize(); this.scheme.requestRenderAll(); if (!this.scheme.getZoomManager().zoomByFactor(prevScale)) { this.scheme.getZoomManager().setScale(this.scheme.getZoomManager().getScaleWithAllObjects()); } }); } /** * Mouse down * @param e */ protected onMouseDown(e: MouseEvent | TouchEvent): void { this.leftButtonDown = true; this.setLastClientPositionFromEvent(e); } /** * Mouse up * @param e */ protected onMouseUp(e: MouseEvent | TouchEvent): void { this.leftButtonDown = false; this.setLastClientPositionFromEvent(e); if (this.isDragging) { this.scheme.setCursorStyle(this.scheme.getDefaultCursorStyle()); this.scheme.requestRenderAll(); } // defer for prevent trigger click on mouseUp setTimeout(() => {this.isDragging = false; }, 1); } /** * On click * @param e */ protected onClick(e: MouseEvent): void { if (!this.isDragging) { let objects = this.findObjectsForEvent(e); for (let schemeObject of objects) { schemeObject.click(e, this.scheme, this.scheme.getView()); this.scheme.addChangedObject(schemeObject); this.sendEvent('clickOnObject', schemeObject); } if (objects.length) { this.scheme.requestRenderAll(); this.scheme.updateCache(true); } } } /** * Double click * @param e */ protected onDoubleClick(e: MouseEvent): void { let zoomManager = this.scheme.getZoomManager(); zoomManager.zoomToPointer(e, zoomManager.getClickZoomDelta()); } /** * Right click * @param e */ protected onContextMenu(e: MouseEvent): void { } /** * On mouse move * @param e */ protected onMouseMove(e: MouseEvent | TouchEvent): void { if (this.leftButtonDown) { let newCoordinates = this.getCoordinatesFromEvent(e); let deltaX = Math.abs(newCoordinates.x - this.getLastClientX()); let deltaY = Math.abs(newCoordinates.y - this.getLastClientY()); // 1 - is click with offset - mis drag if (deltaX > 1 || deltaY > 1) { this.isDragging = true; this.scheme.setCursorStyle('move'); } } if (!this.isDragging) { this.handleHover(e); } else { this.scheme.getScrollManager().handleDragging(e); } } /** * Handling hover * @param e */ protected handleHover(e: MouseEvent | TouchEvent): void { this.setLastClientPositionFromEvent(e); let objects = this.findObjectsForEvent(e); let mustReRender = false; let hasNewHovers = false; if (this.hoveredObjects.length) { for (let schemeHoveredObject of this.hoveredObjects) { let alreadyHovered = false; for (let schemeObject of objects) { if (schemeObject == schemeHoveredObject) { alreadyHovered = true; } } if (!alreadyHovered) { schemeHoveredObject.isHovered = false; let result = schemeHoveredObject.mouseLeave(e, this.scheme, this.scheme.getView()); this.scheme.addChangedObject(schemeHoveredObject); this.sendEvent('mouseLeaveObject', schemeHoveredObject); if (result !== false) { mustReRender = true; } hasNewHovers = true; } } } if (!this.hoveredObjects.length || hasNewHovers) { for (let schemeObject of objects) { schemeObject.isHovered = true; this.scheme.setCursorStyle(schemeObject.cursorStyle); let result = schemeObject.mouseOver(e, this.scheme, this.scheme.getView()); if (result !== false) { mustReRender = true; } this.scheme.addChangedObject(schemeObject); this.sendEvent('mouseOverObject', schemeObject, e); } } this.hoveredObjects = objects; if (!objects.length) { this.scheme.setCursorStyle(this.scheme.getDefaultCursorStyle()); } if (mustReRender) { this.scheme.requestRenderAll(); this.scheme.updateCache(true); } } /** * Mouse out * @param e */ protected onMouseOut(e: MouseEvent): void { this.setLastClientPositionFromEvent(e); this.leftButtonDown = false; this.isDragging = false; this.scheme.requestRenderAll(); } /** * Mouse enter * @param e */ protected onMouseEnter(e: MouseEvent): void { } /** * Zoom by wheel * @param e */ protected onMouseWheel(e: MouseWheelEvent): void { return this.scheme.getZoomManager().handleMouseWheel(e); } /** * Set last client position * @param e */ public setLastClientPositionFromEvent(e: MouseEvent | TouchEvent): void { let coordinates = this.getCoordinatesFromEvent(e); this.setLastClientPosition(coordinates); } /** * Find objects by event * @param e * @returns {SchemeObject[]} */ protected findObjectsForEvent(e: MouseEvent | TouchEvent): SchemeObject[] { let coordinates = this.getCoordinatesFromEvent(e); return this.scheme.getStorageManager().findObjectsByCoordinates(coordinates); } /** * Get coordinates from event * @param e * @returns {number[]} */ protected getCoordinatesFromEvent(e: MouseEvent | TouchEvent): Coordinates { let clientRect = this.scheme.getCanvas().getBoundingClientRect(); let x = Tools.getPointer(e, 'clientX') - clientRect.left; let y = Tools.getPointer(e, 'clientY') - clientRect.top; return {x, y}; } /** * Set last client position * @param coordinates */ protected setLastClientPosition(coordinates: Coordinates): void { this.lastClientPosition = coordinates; } /** * Get last client x * @returns {number} */ public getLastClientX(): number { return this.lastClientPosition.x; } /** * Get last client y * @returns {number} */ public getLastClientY(): number { return this.lastClientPosition.y; } /** * Send event * @param {string} eventName * @param data * @param {UIEvent} originalEvent */ public sendEvent(eventName: string, data?: any, originalEvent?: UIEvent): void { let fullEventName = `schemeDesigner.${eventName}`; if (typeof CustomEvent === 'function') { let dataForSend = data; if (typeof originalEvent !== 'undefined') { dataForSend = { data: data, originalEvent: originalEvent, }; } let event = new CustomEvent(fullEventName, { detail: dataForSend }); this.scheme.getCanvas().dispatchEvent(event); } else { let event = document.createEvent('CustomEvent'); event.initCustomEvent(fullEventName, false, false, data); this.scheme.getCanvas().dispatchEvent(event); } } /** * Set doubleTapDelay * @param value */ public setDoubleTapDelay(value: number): void { this.doubleTapDelay = value; } } }
the_stack
import { List, Map, Record } from 'immutable'; import { Range } from 'pyright-internal/common/textRange'; import { ParseNode } from 'pyright-internal/parser/parseNodes'; import { ThStmt, TSFunDef, TSPass } from '../frontend/torchStatements'; import { fetchAddr } from './backUtils'; import { Context } from './context'; import { ShEnv, ShHeap } from './sharpEnvironments'; import { ExpBool, ExpNum, ExpShape, ExpString, SymExp } from './symExpressions'; export type ShValue = | SVAddr | SVInt | SVFloat | SVString | SVBool | SVObject | SVFunc | SVNone | SVNotImpl | SVUndef | SVError; export type SVNumber = SVInt | SVFloat; export type SVNumeric = SVInt | SVFloat | SVBool; export type SVLiteral = SVInt | SVFloat | SVBool | SVString; export const enum ShContFlag { Run, Cnt, Brk, } export const enum SVType { Addr, Int, Float, String, Bool, Object, Func, None, NotImpl, Undef, Error, } export type SVNumberType = SVType.Int | SVType.Float; export type SVNumericType = SVType.Int | SVType.Float | SVType.Bool; export type SVLiteralType = SVType.Int | SVType.Float | SVType.Bool | SVType.String; // defined in builtins.py export enum PrimitiveType { Int = 0, Float = 1, Str = 2, Bool = 3, Tuple = 4, List = 5, Dict = 6, Set = 7, Ellipsis = 8, } let _svId = 0; export function getNextSVId(): number { return ++_svId; } export type CodeSource = ParseNode | CodeRange; export interface CodeRange { // file index (managed from PyteaService) fileId: number; // code range range: Range; } interface ShValueBase { readonly type: SVType; readonly source: CodeSource | undefined; } export namespace ShValue { export function toStringType(type: SVType | undefined): string { if (type === undefined) return 'undefined'; switch (type) { case SVType.Addr: return 'Addr'; case SVType.Int: return 'Int'; case SVType.Float: return 'Float'; case SVType.String: return 'String'; case SVType.Bool: return 'Bool'; case SVType.Object: return 'Object'; case SVType.Func: return 'Func'; case SVType.None: return 'None'; case SVType.NotImpl: return 'NotImpl'; case SVType.Undef: return 'Undef'; case SVType.Error: return 'Error'; } } export function toString(value: ShValue | ShContFlag): string { if (typeof value === 'object') { return value.toString(); } else { switch (value) { case ShContFlag.Run: return 'RUN'; case ShContFlag.Cnt: return 'CNT'; case ShContFlag.Brk: return 'BRK'; } } } export function toStringStrMap(map: Map<string, ShValue>): string { if (map.count() === 0) { return '{}'; } const keyArr = [...map.keys()]; keyArr.sort(); return `{ ${keyArr.map((i) => `${i} => ${map.get(i)?.toString()}`).join(', ')} }`; } export function toStringNumMap(map: Map<number, ShValue>): string { if (map.count() === 0) { return '{}'; } const keyArr = [...map.keys()]; keyArr.sort((a, b) => a - b); return `{ ${keyArr.map((i) => `${i} => ${map.get(i)?.toString()}`).join(', ')} }`; } // add address offset export function addOffset(value: ShValue, offset: number): ShValue { let newVal = value; switch (newVal.type) { case SVType.Addr: newVal = newVal.addOffset(offset); break; case SVType.Object: newVal = newVal.set( 'attrs', newVal.attrs.mapEntries(([k, attr]) => [k, addOffset(attr, offset)]) ); newVal = newVal.set( 'indices', newVal.indices.mapEntries(([k, attr]) => [k, addOffset(attr, offset)]) ); newVal = newVal.set( 'keyValues', newVal.keyValues.mapEntries(([k, attr]) => [k, addOffset(attr, offset)]) ); break; case SVType.Func: SVFunc; newVal = newVal.set( 'defaults', newVal.defaults.mapEntries(([k, v]) => [k, addOffset(v, offset)]) ); if (newVal.funcEnv) { newVal = newVal.set('funcEnv', newVal.funcEnv.addOffset(offset)); } break; default: break; } return newVal; } } interface SVAddrProps extends ShValueBase { readonly type: SVType.Addr; readonly addr: number; } const svAddrDefaults: SVAddrProps = { type: SVType.Addr, addr: -1, source: undefined, }; export class SVAddr extends Record(svAddrDefaults) implements SVAddrProps { readonly type!: SVType.Addr; constructor(values?: Partial<SVAddrProps>) { values ? super(values) : super(); } static create(addr: number, source: CodeSource | undefined): SVAddr { const value: SVAddr = new SVAddr({ addr, source, }); return value; } toString(): string { return `Loc(${this.addr})`; } addOffset(offset: number): SVAddr { return this.addr >= 0 ? this.set('addr', this.addr + offset) : this; } } interface SVIntProps extends ShValueBase { readonly type: SVType.Int; readonly value: number | ExpNum; } const svIntDefaults: SVIntProps = { type: SVType.Int, value: 0, source: undefined, }; export class SVInt extends Record(svIntDefaults) implements SVIntProps { readonly type!: SVType.Int; constructor(values?: Partial<SVIntProps>) { values ? super(values) : super(); } static create(intValue: number | ExpNum, source: CodeSource | undefined): SVInt { const value: SVInt = new SVInt({ value: intValue, source, }); return value; } toString(): string { return typeof this.value === 'number' ? this.value.toString() : ExpNum.toString(this.value); } } interface SVFloatProps extends ShValueBase { readonly type: SVType.Float; readonly value: number | ExpNum; } const svFloatDefaults: SVFloatProps = { type: SVType.Float, value: 0, source: undefined, }; export class SVFloat extends Record(svFloatDefaults) implements SVFloatProps { readonly type!: SVType.Float; constructor(values?: Partial<SVFloatProps>) { values ? super(values) : super(); } static create(floatValue: number | ExpNum, source: CodeSource | undefined): SVFloat { const value: SVFloat = new SVFloat({ value: floatValue, source, }); return value; } toString(): string { if (typeof this.value === 'number') { if (Number.isInteger(this.value)) { return `${this.value}.0`; } else { return this.value.toString(); } } else { return ExpNum.toString(this.value); } } } interface SVStringProps extends ShValueBase { readonly type: SVType.String; readonly value: string | ExpString; } const svStringDefaults: SVStringProps = { type: SVType.String, value: '', source: undefined, }; export class SVString extends Record(svStringDefaults) implements SVStringProps { readonly type!: SVType.String; constructor(values?: Partial<SVStringProps>) { values ? super(values) : super(); } static create(strValue: string | ExpString, source: CodeSource | undefined): SVString { const value: SVString = new SVString({ value: strValue, source, }); return value; } toString(): string { return typeof this.value === 'string' ? `"${this.value}"` : ExpString.toString(this.value); } } interface SVBoolProps extends ShValueBase { readonly type: SVType.Bool; readonly value: boolean | ExpBool; } const svBoolDefaults: SVBoolProps = { type: SVType.Bool, value: false, source: undefined, }; export class SVBool extends Record(svBoolDefaults) implements SVBoolProps { readonly type!: SVType.Bool; constructor(values?: Partial<SVBoolProps>) { values ? super(values) : super(); } static create(boolValue: boolean | ExpBool, source: CodeSource | undefined): SVBool { const value: SVBool = new SVBool({ value: boolValue, source, }); return value; } toString(): string { return typeof this.value === 'boolean' ? (this.value ? 'true' : 'false') : ExpBool.toString(this.value); } } interface SVObjectProps extends ShValueBase { readonly type: SVType.Object; readonly id: number; readonly attrs: Map<string, ShValue>; readonly indices: Map<number, ShValue>; readonly keyValues: Map<string, ShValue>; readonly addr: SVAddr; readonly shape?: ExpShape; } const svObjectProps: SVObjectProps = { type: SVType.Object, id: -1, attrs: Map<string, ShValue>(), // TODO: default methods indices: Map<number, ShValue>(), keyValues: Map<string, ShValue>(), addr: SVAddr.create(Number.NEGATIVE_INFINITY, undefined), source: undefined, shape: undefined, }; export class SVObject extends Record(svObjectProps) implements SVObjectProps { readonly type!: SVType.Object; constructor(values?: Partial<SVObjectProps>) { values ? super(values) : super(); } // from now on, object creation should be bind with address. static create(heap: ShHeap, source: CodeSource | undefined): [SVObject, SVAddr, ShHeap] { const [addr, newHeap] = heap.malloc(source); const value: SVObject = new SVObject({ id: getNextSVId(), addr, source, }); return [value, addr, newHeap.setVal(addr, value)]; } // if address is fixed, use it and set addr after. static createWithAddr(addr: SVAddr, source: CodeSource | undefined): SVObject { const value: SVObject = new SVObject({ id: getNextSVId(), addr, source, }); return value; } setAttr(attr: string, value: ShValue): SVObject { return this.set('attrs', this.attrs.set(attr, value)); } setIndice(index: number, value: ShValue): SVObject { return this.set('indices', this.indices.set(index, value)); } setKeyVal(key: string, value: ShValue): SVObject { return this.set('keyValues', this.keyValues.set(key, value)); } getAttr(attr: string): ShValue | undefined { return this.attrs.get(attr); } getIndice(index: number): ShValue | undefined { return this.indices.get(index); } getKeyVal(key: string): ShValue | undefined { return this.keyValues.get(key); } toString(): string { const attrStr = `${ShValue.toStringStrMap(this.attrs)}`; const indStr = `${ShValue.toStringNumMap(this.indices)}`; const kvStr = `${ShValue.toStringStrMap(this.keyValues)}`; const shapeStr = this.shape ? `, ${ExpShape.toString(this.shape)}` : ''; return `[${this.addr.addr}]{ ${attrStr}, ${indStr}, ${kvStr}${shapeStr} }`; } // assume that this is iterable object like list or tuple, extract numeric values from indices extractIndexedNumber(heap: ShHeap): Map<number, ExpNum> { let map: Map<number, ExpNum> = Map<number, ExpNum>(); this.indices.forEach((v, k) => { const value = fetchAddr(v, heap); if (value?.type === SVType.Int || value?.type === SVType.Float) { const exp = typeof value.value === 'number' ? ExpNum.fromConst(value.value, value.source) : value.value; map = map.set(k, exp); } }); return map; } clone(heap: ShHeap, source: CodeSource | undefined): [SVObject, ShHeap] { const [addr, newHeap] = heap.malloc(source); const obj = this.set('addr', addr).set('id', getNextSVId()).set('source', source); return [obj, newHeap.setVal(addr, obj)]; } } // tuple-like torch.Size implementation export class SVSize extends SVObject { shape!: ExpShape; static createSize(ctx: Context<unknown>, shape: ExpShape, source: CodeSource | undefined): Context<SVSize> { const tupleMro = fetchAddr( (fetchAddr(ctx.env.getId('tuple'), ctx.heap) as SVObject).getAttr('__mro__'), ctx.heap )!; const [addr, heap] = ctx.heap.malloc(source); const value: SVSize = new SVSize({ id: getNextSVId(), addr: addr, shape, source, attrs: Map({ __mro__: tupleMro, $length: SVInt.create(ExpShape.getRank(shape), shape.source) }), }); return ctx.setHeap(heap.setVal(addr, value)).setRetVal(value); } // make SVObject to SVSize static toSize(obj: SVObject, shape: ExpShape): SVSize { const value: SVSize = new SVSize({ id: obj.id, attrs: obj.attrs.set('$length', SVInt.create(ExpShape.getRank(shape), shape.source)), indices: obj.indices, keyValues: obj.keyValues, addr: obj.addr, shape, }); return value; } getAttr(attr: string): ShValue | undefined { if (attr === '$length') { return SVInt.create(ExpShape.getRank(this.shape), this.shape.source); } return this.attrs.get(attr); } getIndice(index: number): ShValue | undefined { return SVInt.create(ExpNum.index(this.shape, index, this.shape.source), this.shape.source); } rank(): number | ExpNum { return ExpShape.getRank(this.shape); } toString(): string { return `Size(${SymExp.toString(this.shape)})`; } } interface SVFuncProps extends ShValueBase { readonly type: SVType.Func; readonly id: number; readonly name: string; readonly params: List<string>; readonly defaults: Map<string, ShValue>; readonly funcBody: ThStmt; readonly hasClosure: boolean; readonly funcEnv?: ShEnv; // make it optional to avoid TypeScript circular import dependency readonly varargsParam?: string; readonly kwargsParam?: string; readonly keyOnlyNum?: number; // length of keyword-only argument. (with respect to varargs and PEP3012 keyword only arg) } const svFuncDefaults: SVFuncProps = { type: SVType.Func, id: -1, name: '', params: List(), defaults: Map<string, ShValue>(), funcBody: TSPass.get(undefined), hasClosure: false, funcEnv: undefined, varargsParam: undefined, kwargsParam: undefined, source: undefined, keyOnlyNum: undefined, }; export class SVFunc extends Record(svFuncDefaults) implements SVFuncProps { readonly type!: SVType.Func; constructor(values?: Partial<SVFuncProps>) { values ? super(values) : super(); } static create( name: string, params: List<string>, funcBody: ThStmt, funcEnv: ShEnv, source: CodeSource | undefined ): SVFunc { const value: SVFunc = new SVFunc({ id: getNextSVId(), name, params, funcBody, funcEnv, hasClosure: TSFunDef.findClosure(funcBody), source, }); return value; } setDefaults(defaults: Map<string, ShValue>): SVFunc { return this.set('defaults', defaults); } setVKParam(varargsParam?: string, kwargsParam?: string, keyOnlyNum?: number): SVFunc { let func: SVFunc = this; if (varargsParam !== undefined) { func = func.set('varargsParam', varargsParam); } if (kwargsParam !== undefined) { func = func.set('kwargsParam', kwargsParam); } if (keyOnlyNum !== undefined) { func = func.set('keyOnlyNum', keyOnlyNum); } return func; } toString(): string { return `${this.name}(${this.params.join(', ')})`; } bound(selfAddr: SVAddr): SVFunc { // TODO: staticmethod. // self value should be given as address. if (this.params.count() === 0) { return this; } const selfName = this.params.get(0)!; const boundParams = this.params.slice(1); const newEnv = this.funcEnv?.setId(selfName, selfAddr); return this.set('params', boundParams).set('funcEnv', newEnv); } } interface SVNoneProps extends ShValueBase { readonly type: SVType.None; } const svNoneDefaults: SVNoneProps = { type: SVType.None, source: undefined, }; export class SVNone extends Record(svNoneDefaults) implements SVNoneProps { readonly type!: SVType.None; static _none = new SVNone(); private constructor(values?: Partial<SVNoneProps>) { values ? super(values) : super(); } static create(source?: CodeSource): SVNone { if (!source) return SVNone._none; const value: SVNone = new SVNone({ source, }); return value; } toString(): string { return 'None'; } } interface SVNotImplProps extends ShValueBase { readonly type: SVType.NotImpl; readonly reason?: string; } const svNotImplDefaults: SVNotImplProps = { type: SVType.NotImpl, reason: undefined, source: undefined, }; export class SVNotImpl extends Record(svNotImplDefaults) implements SVNotImplProps { readonly type!: SVType.NotImpl; static _notImpl = new SVNotImpl(); private constructor(values?: Partial<SVNotImplProps>) { values ? super(values) : super(); } static create(reason: string, source: CodeSource | undefined): SVNotImpl { if (!reason && !source) { return this._notImpl; } const value: SVNotImpl = new SVNotImpl({ reason, source, }); return value; } toString(): string { return `NotImpl(${this.reason ? this.reason : ''})`; } } interface SVUndefProps extends ShValueBase { readonly type: SVType.Undef; } const svUndefDefaults: SVUndefProps = { type: SVType.Undef, source: undefined, }; export class SVUndef extends Record(svUndefDefaults) implements SVUndefProps { readonly type!: SVType.Undef; static _undef = new SVUndef(); private constructor(values?: Partial<SVUndefProps>) { values ? super(values) : super(); } static create(source: CodeSource | undefined): SVUndef { if (!source) { return SVUndef._undef; } const value: SVUndef = new SVUndef({ source, }); return value; } toString(): string { return 'UNDEF'; } } export interface SVErrorProps extends ShValueBase { readonly type: SVType.Error; readonly reason: string; readonly level: SVErrorLevel; } const svErrorDefaults: SVErrorProps = { type: SVType.Error, reason: 'unexpected error', level: SVErrorLevel.Error, source: undefined, }; export const enum SVErrorLevel { Error, Warning, Log, } export class SVError extends Record(svErrorDefaults) implements SVErrorProps { readonly type!: SVType.Error; private constructor(values?: Partial<SVErrorProps>) { values ? super(values) : super(); } static create(reason: string, level: SVErrorLevel, source: CodeSource | undefined): SVError { const value: SVError = new SVError({ reason, level, source, }); return value; } static error(reason: string, source: CodeSource | undefined): SVError { return this.create(reason, SVErrorLevel.Error, source); } static warn(reason: string, source: CodeSource | undefined): SVError { return this.create(reason, SVErrorLevel.Warning, source); } static log(reason: string, source: CodeSource | undefined): SVError { return this.create(reason, SVErrorLevel.Log, source); } toString(): string { // const pos = formatParseNode(this.source); return `SVError<${svErrorLevelToString(this.level)}: "${this.reason}">`; } } export function svErrorLevelToString(level: SVErrorLevel): string { switch (level) { case SVErrorLevel.Error: return 'Error'; case SVErrorLevel.Warning: return 'Warning'; case SVErrorLevel.Log: return 'Log'; } } export function svTypeToString(type: SVType) { switch (type) { case SVType.Addr: return 'Addr'; case SVType.Int: return 'Int'; case SVType.Float: return 'Float'; case SVType.String: return 'String'; case SVType.Bool: return 'Bool'; case SVType.Object: return 'Object'; case SVType.Func: return 'Func'; case SVType.None: return 'None'; case SVType.NotImpl: return 'NotImpl'; case SVType.Undef: return 'Undef'; case SVType.Error: return 'Error'; } }
the_stack
import {extend, bindFunctions} from "../common/common"; import {isFunction, isString, isDefined, isArray} from "../common/predicates"; import {UrlMatcher} from "./module"; import {services} from "../common/coreservices"; import {UrlMatcherFactory} from "./urlMatcherFactory"; import {StateParams} from "../params/stateParams"; let $location = services.location; // Returns a string that is a prefix of all strings matching the RegExp function regExpPrefix(re) { let prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source); return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : ''; } // Interpolates matched values into a String.replace()-style pattern function interpolate(pattern, match) { return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) { return match[what === '$' ? 0 : Number(what)]; }); } function handleIfMatch($injector, $stateParams, handler, match) { if (!match) return false; let result = $injector.invoke(handler, handler, { $match: match, $stateParams: $stateParams }); return isDefined(result) ? result : true; } function appendBasePath(url, isHtml5, absolute) { let baseHref = services.locationConfig.baseHref(); if (baseHref === '/') return url; if (isHtml5) return baseHref.slice(0, -1) + url; if (absolute) return baseHref.slice(1) + url; return url; } // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree function update(rules: Function[], otherwiseFn: Function, evt?: any) { if (evt && evt.defaultPrevented) return; function check(rule) { let handled = rule(services.$injector, $location); if (!handled) return false; if (isString(handled)) { $location.replace(); $location.url(handled); } return true; } let n = rules.length, i; for (i = 0; i < n; i++) { if (check(rules[i])) return; } // always check otherwise last to allow dynamic updates to the set of rules if (otherwiseFn) check(otherwiseFn); } /** * @ngdoc object * @name ui.router.router.$urlRouterProvider * * @requires ui.router.util.$urlMatcherFactoryProvider * @requires $locationProvider * * @description * `$urlRouterProvider` has the responsibility of watching `$location`. * When `$location` changes it runs through a list of rules one by one until a * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify * a url in a state configuration. All urls are compiled into a UrlMatcher object. * * There are several methods on `$urlRouterProvider` that make it useful to use directly * in your module config. */ export class UrlRouterProvider { /** @hidden */ rules = []; /** @hidden */ otherwiseFn: Function = null; /** @hidden */ interceptDeferred = false; constructor(private $urlMatcherFactory: UrlMatcherFactory, private $stateParams: StateParams) { } /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#rule * @methodOf ui.router.router.$urlRouterProvider * * @description * Defines rules that are used by `$urlRouterProvider` to find matches for * specific URLs. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * // Here's an example of how you might allow case insensitive urls * $urlRouterProvider.rule(function ($injector, $location) { * var path = $location.path(), * normalized = path.toLowerCase(); * * if (path !== normalized) { * return normalized; * } * }); * }); * </pre> * * @param {function} rule Handler function that takes `$injector` and `$location` * services as arguments. You can use them to return a valid path as a string. * * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance */ rule(rule) { if (!isFunction(rule)) throw new Error("'rule' must be a function"); this.rules.push(rule); return this; }; /** * @ngdoc object * @name ui.router.router.$urlRouterProvider#otherwise * @methodOf ui.router.router.$urlRouterProvider * * @description * Defines a path that is used when an invalid route is requested. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * // if the path doesn't match any of the urls you configured * // otherwise will take care of routing the user to the * // specified url * $urlRouterProvider.otherwise('/index'); * * // Example of using function rule as param * $urlRouterProvider.otherwise(function ($injector, $location) { * return '/a/valid/url'; * }); * }); * </pre> * * @param {string|function} rule The url path you want to redirect to or a function * rule that returns the url path. The function version is passed two params: * `$injector` and `$location` services, and must return a url string. * * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance */ otherwise(rule) { if (!isFunction(rule) && !isString(rule)) throw new Error("'rule' must be a string or function"); this.otherwiseFn = isString(rule) ? () => rule : rule; return this; }; /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#when * @methodOf ui.router.router.$urlRouterProvider * * @description * Registers a handler for a given url matching. * * If the handler is a string, it is * treated as a redirect, and is interpolated according to the syntax of match * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise). * * If the handler is a function, it is injectable. It gets invoked if `$location` * matches. You have the option of inject the match object as `$match`. * * The handler can return * * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter` * will continue trying to find another one that matches. * - **string** which is treated as a redirect and passed to `$location.url()` * - **void** or any **truthy** value tells `$urlRouter` that the url was handled. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * $urlRouterProvider.when($state.url, function ($match, $stateParams) { * if ($state.$current.navigable !== state || * !equalForKeys($match, $stateParams) { * $state.transitionTo(state, $match, false); * } * }); * }); * </pre> * * @param {string|object} what The incoming path that you want to redirect. * @param {string|function} handler The path you want to redirect your user to. */ when(what, handler) { let {$urlMatcherFactory, $stateParams} = this; let redirect, handlerIsString = isString(handler); // @todo Queue this if (isString(what)) what = $urlMatcherFactory.compile(what); if (!handlerIsString && !isFunction(handler) && !isArray(handler)) throw new Error("invalid 'handler' in when()"); let strategies = { matcher: function (_what, _handler) { if (handlerIsString) { redirect = $urlMatcherFactory.compile(_handler); _handler = ['$match', redirect.format.bind(redirect)]; } return extend(function () { return handleIfMatch(services.$injector, $stateParams, _handler, _what.exec($location.path(), $location.search(), $location.hash())); }, { prefix: isString(_what.prefix) ? _what.prefix : '' }); }, regex: function (_what, _handler) { if (_what.global || _what.sticky) throw new Error("when() RegExp must not be global or sticky"); if (handlerIsString) { redirect = _handler; _handler = ['$match', ($match) => interpolate(redirect, $match)]; } return extend(function () { return handleIfMatch(services.$injector, $stateParams, _handler, _what.exec($location.path())); }, { prefix: regExpPrefix(_what) }); } }; let check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp }; for (var n in check) { if (check[n]) return this.rule(strategies[n](what, handler)); } throw new Error("invalid 'what' in when()"); }; /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#deferIntercept * @methodOf ui.router.router.$urlRouterProvider * * @description * Disables (or enables) deferring location change interception. * * If you wish to customize the behavior of syncing the URL (for example, if you wish to * defer a transition but maintain the current URL), call this method at configuration time. * Then, at run time, call `$urlRouter.listen()` after you have configured your own * `$locationChangeSuccess` event handler. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * * // Prevent $urlRouter from automatically intercepting URL changes; * // this allows you to configure custom behavior in between * // location changes and route synchronization: * $urlRouterProvider.deferIntercept(); * * }).run(function ($rootScope, $urlRouter, UserService) { * * $rootScope.$on('$locationChangeSuccess', function(e) { * // UserService is an example service for managing user state * if (UserService.isLoggedIn()) return; * * // Prevent $urlRouter's default handler from firing * e.preventDefault(); * * UserService.handleLogin().then(function() { * // Once the user has logged in, sync the current URL * // to the router: * $urlRouter.sync(); * }); * }); * * // Configures $urlRouter's listener *after* your custom listener * $urlRouter.listen(); * }); * </pre> * * @param {boolean} defer Indicates whether to defer location change interception. Passing * no parameter is equivalent to `true`. */ deferIntercept(defer) { if (defer === undefined) defer = true; this.interceptDeferred = defer; }; } export class UrlRouter { private location: string; private listener: Function; constructor(private urlRouterProvider: UrlRouterProvider) { bindFunctions(UrlRouter.prototype, this, this); } /** * @ngdoc function * @name ui.router.router.$urlRouter#sync * @methodOf ui.router.router.$urlRouter * * @description * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`. * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event, * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed * with the transition by calling `$urlRouter.sync()`. * * @example * <pre> * angular.module('app', ['ui.router']) * .run(function($rootScope, $urlRouter) { * $rootScope.$on('$locationChangeSuccess', function(evt) { * // Halt state change from even starting * evt.preventDefault(); * // Perform custom logic * var meetsRequirement = ... * // Continue with the update and state transition if logic allows * if (meetsRequirement) $urlRouter.sync(); * }); * }); * </pre> */ sync() { update(this.urlRouterProvider.rules, this.urlRouterProvider.otherwiseFn); } listen() { return this.listener = this.listener || $location.onChange(evt => update(this.urlRouterProvider.rules, this.urlRouterProvider.otherwiseFn, evt)); } update(read?) { if (read) { this.location = $location.url(); return; } if ($location.url() === this.location) return; $location.url(this.location); $location.replace(); } push(urlMatcher, params, options) { $location.url(urlMatcher.format(params || {})); if (options && options.replace) $location.replace(); } /** * @ngdoc function * @name ui.router.router.$urlRouter#href * @methodOf ui.router.router.$urlRouter * * @description * A URL generation method that returns the compiled URL for a given * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters. * * @example * <pre> * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), { * person: "bob" * }); * // $bob == "/about/bob"; * </pre> * * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate. * @param {object=} params An object of parameter values to fill the matcher's required parameters. * @param {object=} options Options object. The options are: * * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". * * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher` */ href(urlMatcher: UrlMatcher, params: any, options: any): string { if (!urlMatcher.validates(params)) return null; let url = urlMatcher.format(params); options = options || {}; let cfg = services.locationConfig; let isHtml5 = cfg.html5Mode(); if (!isHtml5 && url !== null) { url = "#" + cfg.hashPrefix() + url; } url = appendBasePath(url, isHtml5, options.absolute); if (!options.absolute || !url) { return url; } let slash = (!isHtml5 && url ? '/' : ''), port = cfg.port(); port = <any> (port === 80 || port === 443 ? '' : ':' + port); return [cfg.protocol(), '://', cfg.host(), port, slash, url].join(''); } }
the_stack
import { expect } from "chai"; import { ReactionHandler } from "../src/reactionhandler"; import { RedactionEvent } from "@sorunome/matrix-bot-sdk"; // we are a test file and thus our linting rules are slightly different // tslint:disable:no-unused-expression max-file-line-count no-any no-magic-numbers no-string-literal let CLIENT_SEND_EVENT = {} as any; let CLIENT_SEND_EVENT_TYPE = ""; function getClient() { CLIENT_SEND_EVENT = {}; CLIENT_SEND_EVENT_TYPE = ""; return { sendEvent: async (roomId, type, msg) => { CLIENT_SEND_EVENT_TYPE = type; CLIENT_SEND_EVENT = msg; return "$newevent"; }, } as any; } let EVENT_STORE_INSERT = ""; let REACTION_STORE_INSERT = {} as any; let REACTION_STORE_DELETE = ""; let REACTION_STORE_DELETE_FOR_EVENT = ""; let BRIDGE_REDACT_EVENT = ""; let BRIDGE_EVENTS_EMITTED: any[] = []; function getHandler() { EVENT_STORE_INSERT = ""; REACTION_STORE_INSERT = {}; REACTION_STORE_DELETE = ""; REACTION_STORE_DELETE_FOR_EVENT = ""; BRIDGE_REDACT_EVENT = ""; BRIDGE_EVENTS_EMITTED = []; const bridge = { protocol: { id: "remote", }, emit: (type) => { BRIDGE_EVENTS_EMITTED.push(type); }, redactEvent: async (client, roomId, eventId) => { BRIDGE_REDACT_EVENT = `${roomId};${eventId}`; }, reactionStore: { exists: async (entry) => entry.roomId === "foxhole" && entry.userId === "fox" && entry.key === "fox" && entry.eventId === "foxparty", getFromKey: async (entry) => { if (entry.roomId === "foxhole" && entry.userId === "fox" && entry.key === "fox" && entry.eventId === "foxparty") { return { puppetId: 1, roomId: "foxhole", userId: "fox", key: "fox", eventId: "foxparty", reactionMxid: "$oldreaction", }; } return null; }, getForEvent: async (puppetId, eventId) => { if (eventId === "foxparty") { return [{ puppetId: 1, roomId: "foxhole", userId: "fox", key: "fox", eventId: "foxparty", reactionMxid: "$oldreaction", }]; } return []; }, insert: async (entry) => { REACTION_STORE_INSERT = entry; }, delete: async (reactionMxid) => { REACTION_STORE_DELETE = reactionMxid; }, deleteForEvent: async (puppetId, eventId) => { REACTION_STORE_DELETE_FOR_EVENT = `${puppetId};${eventId}`; }, getFromReactionMxid: async (reactionMxid) => { if (reactionMxid === "$oldreaction") { return { puppetId: 1, roomId: "foxhole", userId: "fox", key: "fox", eventId: "foxparty", reactionMxid: "$oldreaction", }; } return null; }, }, eventSync: { getMatrix: async (room, eventId) => { if (eventId === "foxparty") { return ["$foxparty"]; } return []; }, insert: async (room, matrixId, remoteId) => { EVENT_STORE_INSERT = `${room.puppetId};${room.roomId};${matrixId};${remoteId}`; }, }, provisioner: { get: async (puppetId) => { if (puppetId === 1) { return { userId: "puppet", }; } return null; }, }, } as any; return new ReactionHandler(bridge); } describe("ReactionHandler", () => { describe("addRemote", () => { it("should ignore if no event is found", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, } as any; const eventId = "nonexistant"; const key = "newfox"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.addRemote(params, eventId, key, client, mxid); expect(CLIENT_SEND_EVENT).eql({}); }); it("should ignore if the reaction already exists", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, } as any; const eventId = "foxparty"; const key = "fox"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.addRemote(params, eventId, key, client, mxid); expect(CLIENT_SEND_EVENT).eql({}); }); it("shoud send, should all check out", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, } as any; const eventId = "foxparty"; const key = "newfox"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.addRemote(params, eventId, key, client, mxid); expect(CLIENT_SEND_EVENT_TYPE).to.equal("m.reaction"); expect(CLIENT_SEND_EVENT).eql({ "source": "remote", "m.relates_to": { rel_type: "m.annotation", event_id: "$foxparty", key: "newfox", }, }); expect(REACTION_STORE_INSERT).eql({ puppetId: 1, roomId: "foxhole", userId: "fox", eventId: "foxparty", reactionMxid: "$newevent", key: "newfox", }); }); it("should associate a remote event id, if present", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, eventId: "reactevent", } as any; const eventId = "foxparty"; const key = "newfox"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.addRemote(params, eventId, key, client, mxid); expect(EVENT_STORE_INSERT).to.equal("1;foxhole;$newevent;reactevent"); }); it("should set an external url, if present", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, externalUrl: "https://example.org", } as any; const eventId = "foxparty"; const key = "newfox"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.addRemote(params, eventId, key, client, mxid); expect(CLIENT_SEND_EVENT_TYPE).to.equal("m.reaction"); expect(CLIENT_SEND_EVENT).eql({ "source": "remote", "m.relates_to": { rel_type: "m.annotation", event_id: "$foxparty", key: "newfox", }, "external_url": "https://example.org", }); }); }); describe("removeRemote", () => { it("should ignore if event is not found", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, } as any; const eventId = "nonexistant"; const key = "fox"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.removeRemote(params, eventId, key, client, mxid); expect(BRIDGE_REDACT_EVENT).to.equal(""); }); it("should ignore, if the key doesn't exist", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, } as any; const eventId = "foxparty"; const key = "newfox"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.removeRemote(params, eventId, key, client, mxid); expect(BRIDGE_REDACT_EVENT).to.equal(""); }); it("should redact, should all check out", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, } as any; const eventId = "foxparty"; const key = "fox"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.removeRemote(params, eventId, key, client, mxid); expect(BRIDGE_REDACT_EVENT).to.equal("!someroom:example.org;$oldreaction"); expect(REACTION_STORE_DELETE).to.equal("$oldreaction"); }); }); describe("removeRemoteAllOnMessage", () => { it("should ignore if event is not found", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, } as any; const eventId = "nonexistant"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.removeRemoteAllOnMessage(params, eventId, client, mxid); expect(BRIDGE_REDACT_EVENT).to.equal(""); }); it("should redact, should everything check out", async () => { const handler = getHandler(); const params = { user: { userId: "fox", puppetId: 1, }, room: { roomId: "foxhole", puppetId: 1, }, } as any; const eventId = "foxparty"; const client = getClient(); const mxid = "!someroom:example.org"; await handler.removeRemoteAllOnMessage(params, eventId, client, mxid); expect(BRIDGE_REDACT_EVENT).to.equal("!someroom:example.org;$oldreaction"); expect(REACTION_STORE_DELETE_FOR_EVENT).to.equal("1;foxparty"); }); }); describe("addMatrix", () => { it("should ignore if the remote puppet doesn't have a user id", async () => { const handler = getHandler(); const room = { roomId: "foxhole", puppetId: 42, }; const eventId = "foxparty"; const reactionMxid = "$newreaction"; const key = "fox"; await handler.addMatrix(room, eventId, reactionMxid, key, null); expect(REACTION_STORE_INSERT).eql({}); handler.deduplicator.dispose(); }); it("should insert the event to the store, should all be fine", async () => { const handler = getHandler(); const room = { roomId: "foxhole", puppetId: 1, }; const eventId = "foxparty"; const reactionMxid = "$newreaction"; const key = "fox"; await handler.addMatrix(room, eventId, reactionMxid, key, null); expect(REACTION_STORE_INSERT).eql({ puppetId: 1, roomId: "foxhole", userId: "puppet", eventId, reactionMxid, key, }); expect(handler.deduplicator["data"].has("1;foxhole;foxparty;add;puppet;m:fox")).to.be.true; handler.deduplicator.dispose(); }); }); describe("handleRedactEvent", () => { it("should do nothing, if the event isn't found", async () => { const handler = getHandler(); const room = { roomId: "foxhole", puppetId: 1, }; const event = new RedactionEvent({ redacts: "$nonexisting", }); await handler.handleRedactEvent(room, event, null); expect(BRIDGE_EVENTS_EMITTED).eql([]); expect(REACTION_STORE_DELETE).to.equal(""); handler.deduplicator.dispose(); }); it("should do nothing, if the room doesn't match", async () => { const handler = getHandler(); const room = { roomId: "foxmeadow", puppetId: 1, }; const event = new RedactionEvent({ redacts: "$oldreaction", }); await handler.handleRedactEvent(room, event, null); expect(BRIDGE_EVENTS_EMITTED).eql([]); expect(REACTION_STORE_DELETE).to.equal(""); handler.deduplicator.dispose(); }); it("should redact the event, is all fine", async () => { const handler = getHandler(); const room = { roomId: "foxhole", puppetId: 1, }; const event = new RedactionEvent({ redacts: "$oldreaction", }); await handler.handleRedactEvent(room, event, null); expect(BRIDGE_EVENTS_EMITTED).eql(["removeReaction"]); expect(REACTION_STORE_DELETE).to.equal("$oldreaction"); expect(handler.deduplicator["data"].has("1;foxhole;foxparty;remove;puppet;m:fox")).to.be.true; handler.deduplicator.dispose(); }); }); });
the_stack
namespace gdjs { import PIXI = GlobalPIXIModule.PIXI; class PanelSpriteRuntimeObjectPixiRenderer { _object: gdjs.PanelSpriteRuntimeObject; /** * The _wrapperContainer must be considered as the main container of this object * All transformations are applied on this container * See updateOpacity for more info why. */ _wrapperContainer: PIXI.Container; /** * The _spritesContainer is used to create the sprites and apply cacheAsBitmap only. */ _spritesContainer: PIXI.Container; _centerSprite: PIXI.Sprite | PIXI.TilingSprite; _borderSprites: Array<PIXI.Sprite | PIXI.TilingSprite>; _wasRendered: boolean = false; _textureWidth = 0; _textureHeight = 0; constructor( runtimeObject: gdjs.PanelSpriteRuntimeObject, runtimeScene: gdjs.RuntimeScene, textureName: string, tiled: boolean ) { this._object = runtimeObject; const texture = (runtimeScene .getGame() .getImageManager() as gdjs.PixiImageManager).getPIXITexture( textureName ); const StretchedSprite = !tiled ? PIXI.Sprite : PIXI.TilingSprite; this._spritesContainer = new PIXI.Container(); this._wrapperContainer = new PIXI.Container(); // @ts-ignore this._centerSprite = new StretchedSprite(new PIXI.Texture(texture)); this._borderSprites = [ // @ts-ignore new StretchedSprite(new PIXI.Texture(texture)), //Right new PIXI.Sprite(texture), //Top-Right // @ts-ignore new StretchedSprite(new PIXI.Texture(texture)), //Top new PIXI.Sprite(texture), //Top-Left // @ts-ignore new StretchedSprite(new PIXI.Texture(texture)), //Left new PIXI.Sprite(texture), //Bottom-Left // @ts-ignore new StretchedSprite(new PIXI.Texture(texture)), //Bottom new PIXI.Sprite(texture), ]; //Bottom-Right this.setTexture(textureName, runtimeScene); this._spritesContainer.removeChildren(); this._spritesContainer.addChild(this._centerSprite); for (let i = 0; i < this._borderSprites.length; ++i) { this._spritesContainer.addChild(this._borderSprites[i]); } this._wrapperContainer.addChild(this._spritesContainer); runtimeScene .getLayer('') .getRenderer() .addRendererObject(this._wrapperContainer, runtimeObject.getZOrder()); } getRendererObject() { return this._wrapperContainer; } ensureUpToDate() { if (this._spritesContainer.visible && this._wasRendered) { // Cache the rendered sprites as a bitmap to speed up rendering when // lots of panel sprites are on the scene. // Sadly, because of this, we need a wrapper container to workaround // a PixiJS issue with alpha (see updateOpacity). this._spritesContainer.cacheAsBitmap = true; } this._wasRendered = true; } updateOpacity(): void { // The alpha is updated on a wrapper around the sprite because a known bug // in Pixi will create a flicker when cacheAsBitmap is set to true. // (see https://github.com/pixijs/pixijs/issues/4610) this._wrapperContainer.alpha = this._object.opacity / 255; } updateAngle(): void { this._wrapperContainer.rotation = gdjs.toRad(this._object.angle); } updatePosition(): void { this._wrapperContainer.position.x = this._object.x + this._object._width / 2; this._wrapperContainer.position.y = this._object.y + this._object._height / 2; } _updateLocalPositions() { const obj = this._object; this._centerSprite.position.x = obj._lBorder; this._centerSprite.position.y = obj._tBorder; //Right this._borderSprites[0].position.x = obj._width - obj._rBorder; this._borderSprites[0].position.y = obj._tBorder; //Top-right this._borderSprites[1].position.x = obj._width - this._borderSprites[1].width; this._borderSprites[1].position.y = 0; //Top this._borderSprites[2].position.x = obj._lBorder; this._borderSprites[2].position.y = 0; //Top-Left this._borderSprites[3].position.x = 0; this._borderSprites[3].position.y = 0; //Left this._borderSprites[4].position.x = 0; this._borderSprites[4].position.y = obj._tBorder; //Bottom-Left this._borderSprites[5].position.x = 0; this._borderSprites[5].position.y = obj._height - this._borderSprites[5].height; //Bottom this._borderSprites[6].position.x = obj._lBorder; this._borderSprites[6].position.y = obj._height - obj._bBorder; //Bottom-Right this._borderSprites[7].position.x = obj._width - this._borderSprites[7].width; this._borderSprites[7].position.y = obj._height - this._borderSprites[7].height; } _updateSpritesAndTexturesSize() { const obj = this._object; this._centerSprite.width = Math.max( obj._width - obj._rBorder - obj._lBorder, 0 ); this._centerSprite.height = Math.max( obj._height - obj._tBorder - obj._bBorder, 0 ); //Right this._borderSprites[0].width = obj._rBorder; this._borderSprites[0].height = Math.max( obj._height - obj._tBorder - obj._bBorder, 0 ); //Top this._borderSprites[2].height = obj._tBorder; this._borderSprites[2].width = Math.max( obj._width - obj._rBorder - obj._lBorder, 0 ); //Left this._borderSprites[4].width = obj._lBorder; this._borderSprites[4].height = Math.max( obj._height - obj._tBorder - obj._bBorder, 0 ); //Bottom this._borderSprites[6].height = obj._bBorder; this._borderSprites[6].width = Math.max( obj._width - obj._rBorder - obj._lBorder, 0 ); this._wasRendered = true; this._spritesContainer.cacheAsBitmap = false; } setTexture(textureName, runtimeScene): void { const obj = this._object; const texture = runtimeScene .getGame() .getImageManager() .getPIXITexture(textureName); this._textureWidth = texture.width; this._textureHeight = texture.height; function makeInsideTexture(rect) { //TODO if (rect.width < 0) { rect.width = 0; } if (rect.height < 0) { rect.height = 0; } if (rect.x < 0) { rect.x = 0; } if (rect.y < 0) { rect.y = 0; } if (rect.x > texture.width) { rect.x = texture.width; } if (rect.y > texture.height) { rect.y = texture.height; } if (rect.x + rect.width > texture.width) { rect.width = texture.width - rect.x; } if (rect.y + rect.height > texture.height) { rect.height = texture.height - rect.y; } return rect; } this._centerSprite.texture = new PIXI.Texture( texture, makeInsideTexture( new PIXI.Rectangle( obj._lBorder, obj._tBorder, texture.width - obj._lBorder - obj._rBorder, texture.height - obj._tBorder - obj._bBorder ) ) ); //Top, Bottom, Right, Left borders: this._borderSprites[0].texture = new PIXI.Texture( texture, makeInsideTexture( new PIXI.Rectangle( texture.width - obj._rBorder, obj._tBorder, obj._rBorder, texture.height - obj._tBorder - obj._bBorder ) ) ); this._borderSprites[2].texture = new PIXI.Texture( texture, makeInsideTexture( new PIXI.Rectangle( obj._lBorder, 0, texture.width - obj._lBorder - obj._rBorder, obj._tBorder ) ) ); this._borderSprites[4].texture = new PIXI.Texture( texture, makeInsideTexture( new PIXI.Rectangle( 0, obj._tBorder, obj._lBorder, texture.height - obj._tBorder - obj._bBorder ) ) ); this._borderSprites[6].texture = new PIXI.Texture( texture, makeInsideTexture( new PIXI.Rectangle( obj._lBorder, texture.height - obj._bBorder, texture.width - obj._lBorder - obj._rBorder, obj._bBorder ) ) ); this._borderSprites[1].texture = new PIXI.Texture( texture, makeInsideTexture( new PIXI.Rectangle( texture.width - obj._rBorder, 0, obj._rBorder, obj._tBorder ) ) ); this._borderSprites[3].texture = new PIXI.Texture( texture, makeInsideTexture(new PIXI.Rectangle(0, 0, obj._lBorder, obj._tBorder)) ); this._borderSprites[5].texture = new PIXI.Texture( texture, makeInsideTexture( new PIXI.Rectangle( 0, texture.height - obj._bBorder, obj._lBorder, obj._bBorder ) ) ); this._borderSprites[7].texture = new PIXI.Texture( texture, makeInsideTexture( new PIXI.Rectangle( texture.width - obj._rBorder, texture.height - obj._bBorder, obj._rBorder, obj._bBorder ) ) ); this._updateSpritesAndTexturesSize(); this._updateLocalPositions(); this.updatePosition(); this._wrapperContainer.pivot.x = this._object._width / 2; this._wrapperContainer.pivot.y = this._object._height / 2; } updateWidth(): void { this._wrapperContainer.pivot.x = this._object._width / 2; this._updateSpritesAndTexturesSize(); this._updateLocalPositions(); this.updatePosition(); } updateHeight(): void { this._wrapperContainer.pivot.y = this._object._height / 2; this._updateSpritesAndTexturesSize(); this._updateLocalPositions(); this.updatePosition(); } setColor(rgbColor): void { const colors = rgbColor.split(';'); if (colors.length < 3) { return; } this._centerSprite.tint = gdjs.rgbToHexNumber( parseInt(colors[0], 10), parseInt(colors[1], 10), parseInt(colors[2], 10) ); for ( let borderCounter = 0; borderCounter < this._borderSprites.length; borderCounter++ ) { this._borderSprites[borderCounter].tint = gdjs.rgbToHexNumber( parseInt(colors[0], 10), parseInt(colors[1], 10), parseInt(colors[2], 10) ); } this._spritesContainer.cacheAsBitmap = false; } getColor() { const rgb = PIXI.utils.hex2rgb(this._centerSprite.tint); return ( Math.floor(rgb[0] * 255) + ';' + Math.floor(rgb[1] * 255) + ';' + Math.floor(rgb[2] * 255) ); } getTextureWidth() { return this._textureWidth; } getTextureHeight() { return this._textureHeight; } } export const PanelSpriteRuntimeObjectRenderer = PanelSpriteRuntimeObjectPixiRenderer; export type PanelSpriteRuntimeObjectRenderer = PanelSpriteRuntimeObjectPixiRenderer; }
the_stack
import { TemplateRef, Injectable, Injector, OnDestroy, Type, StaticProvider, InjectFlags, Inject, Optional, SkipSelf, } from '@angular/core'; import {BasePortalOutlet, ComponentPortal, TemplatePortal} from '@angular/cdk/portal'; import {of as observableOf, Observable, Subject, defer} from 'rxjs'; import {DialogRef} from './dialog-ref'; import {DialogConfig} from './dialog-config'; import {Directionality} from '@angular/cdk/bidi'; import { ComponentType, Overlay, OverlayRef, OverlayConfig, ScrollStrategy, OverlayContainer, } from '@angular/cdk/overlay'; import {startWith} from 'rxjs/operators'; import {DEFAULT_DIALOG_CONFIG, DIALOG_DATA, DIALOG_SCROLL_STRATEGY} from './dialog-injectors'; import {CdkDialogContainer} from './dialog-container'; /** Unique id for the created dialog. */ let uniqueId = 0; @Injectable() export class Dialog implements OnDestroy { private _openDialogsAtThisLevel: DialogRef<any, any>[] = []; private readonly _afterAllClosedAtThisLevel = new Subject<void>(); private readonly _afterOpenedAtThisLevel = new Subject<DialogRef>(); private _ariaHiddenElements = new Map<Element, string | null>(); private _scrollStrategy: () => ScrollStrategy; /** Keeps track of the currently-open dialogs. */ get openDialogs(): readonly DialogRef<any, any>[] { return this._parentDialog ? this._parentDialog.openDialogs : this._openDialogsAtThisLevel; } /** Stream that emits when a dialog has been opened. */ get afterOpened(): Subject<DialogRef<any, any>> { return this._parentDialog ? this._parentDialog.afterOpened : this._afterOpenedAtThisLevel; } /** * Stream that emits when all open dialog have finished closing. * Will emit on subscribe if there are no open dialogs to begin with. */ readonly afterAllClosed: Observable<void> = defer(() => this.openDialogs.length ? this._getAfterAllClosed() : this._getAfterAllClosed().pipe(startWith(undefined)), ); constructor( private _overlay: Overlay, private _injector: Injector, @Optional() @Inject(DEFAULT_DIALOG_CONFIG) private _defaultOptions: DialogConfig, @Optional() @SkipSelf() private _parentDialog: Dialog, private _overlayContainer: OverlayContainer, @Inject(DIALOG_SCROLL_STRATEGY) scrollStrategy: any, ) { this._scrollStrategy = scrollStrategy; } /** * Opens a modal dialog containing the given component. * @param component Type of the component to load into the dialog. * @param config Extra configuration options. * @returns Reference to the newly-opened dialog. */ open<R = unknown, D = unknown, C = unknown>( component: ComponentType<C>, config?: DialogConfig<D, DialogRef<R, C>>, ): DialogRef<R, C>; /** * Opens a modal dialog containing the given template. * @param template TemplateRef to instantiate as the dialog content. * @param config Extra configuration options. * @returns Reference to the newly-opened dialog. */ open<R = unknown, D = unknown, C = unknown>( template: TemplateRef<C>, config?: DialogConfig<D, DialogRef<R, C>>, ): DialogRef<R, C>; open<R = unknown, D = unknown, C = unknown>( componentOrTemplateRef: ComponentType<C> | TemplateRef<C>, config?: DialogConfig<D, DialogRef<R, C>>, ): DialogRef<R, C>; open<R = unknown, D = unknown, C = unknown>( componentOrTemplateRef: ComponentType<C> | TemplateRef<C>, config?: DialogConfig<D, DialogRef<R, C>>, ): DialogRef<R, C> { const defaults = (this._defaultOptions || new DialogConfig()) as DialogConfig< D, DialogRef<R, C> >; config = {...defaults, ...config}; config.id = config.id || `cdk-dialog-${uniqueId++}`; if ( config.id && this.getDialogById(config.id) && (typeof ngDevMode === 'undefined' || ngDevMode) ) { throw Error(`Dialog with id "${config.id}" exists already. The dialog id must be unique.`); } const overlayConfig = this._getOverlayConfig(config); const overlayRef = this._overlay.create(overlayConfig); const dialogRef = new DialogRef(overlayRef, config); const dialogContainer = this._attachContainer(overlayRef, dialogRef, config); (dialogRef as {containerInstance: BasePortalOutlet}).containerInstance = dialogContainer; this._attachDialogContent(componentOrTemplateRef, dialogRef, dialogContainer, config); // If this is the first dialog that we're opening, hide all the non-overlay content. if (!this.openDialogs.length) { this._hideNonDialogContentFromAssistiveTechnology(); } (this.openDialogs as DialogRef<R, C>[]).push(dialogRef); dialogRef.closed.subscribe(() => this._removeOpenDialog(dialogRef, true)); this.afterOpened.next(dialogRef); return dialogRef; } /** * Closes all of the currently-open dialogs. */ closeAll(): void { reverseForEach(this.openDialogs, dialog => dialog.close()); } /** * Finds an open dialog by its id. * @param id ID to use when looking up the dialog. */ getDialogById<R, C>(id: string): DialogRef<R, C> | undefined { return this.openDialogs.find(dialog => dialog.id === id); } ngOnDestroy() { // Make one pass over all the dialogs that need to be untracked, but should not be closed. We // want to stop tracking the open dialog even if it hasn't been closed, because the tracking // determines when `aria-hidden` is removed from elements outside the dialog. reverseForEach(this._openDialogsAtThisLevel, dialog => { // Check for `false` specifically since we want `undefined` to be interpreted as `true`. if (dialog.config.closeOnDestroy === false) { this._removeOpenDialog(dialog, false); } }); // Make a second pass and close the remaining dialogs. We do this second pass in order to // correctly dispatch the `afterAllClosed` event in case we have a mixed array of dialogs // that should be closed and dialogs that should not. reverseForEach(this._openDialogsAtThisLevel, dialog => dialog.close()); this._afterAllClosedAtThisLevel.complete(); this._afterOpenedAtThisLevel.complete(); this._openDialogsAtThisLevel = []; } /** * Creates an overlay config from a dialog config. * @param config The dialog configuration. * @returns The overlay configuration. */ private _getOverlayConfig<D, R>(config: DialogConfig<D, R>): OverlayConfig { const state = new OverlayConfig({ positionStrategy: config.positionStrategy || this._overlay.position().global().centerHorizontally().centerVertically(), scrollStrategy: config.scrollStrategy || this._scrollStrategy(), panelClass: config.panelClass, hasBackdrop: config.hasBackdrop, direction: config.direction, minWidth: config.minWidth, minHeight: config.minHeight, maxWidth: config.maxWidth, maxHeight: config.maxHeight, width: config.width, height: config.height, disposeOnNavigation: config.closeOnNavigation, }); if (config.backdropClass) { state.backdropClass = config.backdropClass; } return state; } /** * Attaches a dialog container to a dialog's already-created overlay. * @param overlay Reference to the dialog's underlying overlay. * @param config The dialog configuration. * @returns A promise resolving to a ComponentRef for the attached container. */ private _attachContainer<R, D, C>( overlay: OverlayRef, dialogRef: DialogRef<R, C>, config: DialogConfig<D, DialogRef<R, C>>, ): BasePortalOutlet { const userInjector = config.injector ?? config.viewContainerRef?.injector; const providers: StaticProvider[] = [ {provide: DialogConfig, useValue: config}, {provide: DialogRef, useValue: dialogRef}, {provide: OverlayRef, useValue: overlay}, ]; let containerType: Type<BasePortalOutlet>; if (config.container) { if (typeof config.container === 'function') { containerType = config.container; } else { containerType = config.container.type; providers.push(...config.container.providers(config)); } } else { containerType = CdkDialogContainer; } const containerPortal = new ComponentPortal( containerType, config.viewContainerRef, Injector.create({parent: userInjector || this._injector, providers}), config.componentFactoryResolver, ); const containerRef = overlay.attach(containerPortal); return containerRef.instance; } /** * Attaches the user-provided component to the already-created dialog container. * @param componentOrTemplateRef The type of component being loaded into the dialog, * or a TemplateRef to instantiate as the content. * @param dialogRef Reference to the dialog being opened. * @param dialogContainer Component that is going to wrap the dialog content. * @param config Configuration used to open the dialog. */ private _attachDialogContent<R, D, C>( componentOrTemplateRef: ComponentType<C> | TemplateRef<C>, dialogRef: DialogRef<R, C>, dialogContainer: BasePortalOutlet, config: DialogConfig<D, DialogRef<R, C>>, ) { const injector = this._createInjector(config, dialogRef, dialogContainer); if (componentOrTemplateRef instanceof TemplateRef) { let context: any = {$implicit: config.data, dialogRef}; if (config.templateContext) { context = { ...context, ...(typeof config.templateContext === 'function' ? config.templateContext() : config.templateContext), }; } dialogContainer.attachTemplatePortal( new TemplatePortal<C>(componentOrTemplateRef, null!, context, injector), ); } else { const contentRef = dialogContainer.attachComponentPortal<C>( new ComponentPortal( componentOrTemplateRef, config.viewContainerRef, injector, config.componentFactoryResolver, ), ); (dialogRef as {componentInstance: C}).componentInstance = contentRef.instance; } } /** * Creates a custom injector to be used inside the dialog. This allows a component loaded inside * of a dialog to close itself and, optionally, to return a value. * @param config Config object that is used to construct the dialog. * @param dialogRef Reference to the dialog being opened. * @param dialogContainer Component that is going to wrap the dialog content. * @returns The custom injector that can be used inside the dialog. */ private _createInjector<R, D, C>( config: DialogConfig<D, DialogRef<R, C>>, dialogRef: DialogRef<R, C>, dialogContainer: BasePortalOutlet, ): Injector { const userInjector = config && config.viewContainerRef && config.viewContainerRef.injector; const providers: StaticProvider[] = [ {provide: DIALOG_DATA, useValue: config.data}, {provide: DialogRef, useValue: dialogRef}, ]; if (config.providers) { if (typeof config.providers === 'function') { providers.push(...config.providers(dialogRef, config, dialogContainer)); } else { providers.push(...config.providers); } } if ( config.direction && (!userInjector || !userInjector.get<Directionality | null>(Directionality, null, InjectFlags.Optional)) ) { providers.push({ provide: Directionality, useValue: {value: config.direction, change: observableOf()}, }); } return Injector.create({parent: userInjector || this._injector, providers}); } /** * Removes a dialog from the array of open dialogs. * @param dialogRef Dialog to be removed. * @param emitEvent Whether to emit an event if this is the last dialog. */ private _removeOpenDialog<R, C>(dialogRef: DialogRef<R, C>, emitEvent: boolean) { const index = this.openDialogs.indexOf(dialogRef); if (index > -1) { (this.openDialogs as DialogRef<R, C>[]).splice(index, 1); // If all the dialogs were closed, remove/restore the `aria-hidden` // to a the siblings and emit to the `afterAllClosed` stream. if (!this.openDialogs.length) { this._ariaHiddenElements.forEach((previousValue, element) => { if (previousValue) { element.setAttribute('aria-hidden', previousValue); } else { element.removeAttribute('aria-hidden'); } }); this._ariaHiddenElements.clear(); if (emitEvent) { this._getAfterAllClosed().next(); } } } } /** Hides all of the content that isn't an overlay from assistive technology. */ private _hideNonDialogContentFromAssistiveTechnology() { const overlayContainer = this._overlayContainer.getContainerElement(); // Ensure that the overlay container is attached to the DOM. if (overlayContainer.parentElement) { const siblings = overlayContainer.parentElement.children; for (let i = siblings.length - 1; i > -1; i--) { const sibling = siblings[i]; if ( sibling !== overlayContainer && sibling.nodeName !== 'SCRIPT' && sibling.nodeName !== 'STYLE' && !sibling.hasAttribute('aria-live') ) { this._ariaHiddenElements.set(sibling, sibling.getAttribute('aria-hidden')); sibling.setAttribute('aria-hidden', 'true'); } } } } private _getAfterAllClosed(): Subject<void> { const parent = this._parentDialog; return parent ? parent._getAfterAllClosed() : this._afterAllClosedAtThisLevel; } } /** * Executes a callback against all elements in an array while iterating in reverse. * Useful if the array is being modified as it is being iterated. */ function reverseForEach<T>(items: T[] | readonly T[], callback: (current: T) => void) { let i = items.length; while (i--) { callback(items[i]); } }
the_stack
import go = require("go"); class CustomLink extends go.Link { constructor() { super(); this.routing = go.Link.Orthogonal; } hasCurviness(): boolean { if (isNaN(this.curviness)) return true; return super.hasCurviness(); } computeCurviness(): number { if (isNaN(this.curviness)) { var links = this.fromNode.findLinksTo(this.toNode); if (links.count < 2) return 0; var i = 0; while (links.next()) { if (links.value === this) break; i++; } return 10 * (i - (links.count - 1) / 2); } return super.computeCurviness(); } } class CustomTreeLayout extends go.TreeLayout { constructor() { super(); this.extraProp = 3; } extraProp: number; // override various methods cloneProtected(copy: CustomTreeLayout): void { super.cloneProtected(copy); copy.extraProp = this.extraProp; } createNetwork(): CustomTreeNetwork { return new CustomTreeNetwork(); } assignTreeVertexValues(v: CustomTreeVertex): void { super.assignTreeVertexValues(v); v.someProp = Math.random() * 100; } commitNodes(): void { super.commitNodes(); // ... } commitLinks(): void { super.commitLinks(); this.network.edges.each(e => { e.link.path.strokeWidth = (<CustomTreeEdge>(e)).anotherProp; }); } } class CustomTreeNetwork extends go.TreeNetwork { createVertex(): CustomTreeVertex { return new CustomTreeVertex(); } createEdge(): CustomTreeEdge { return new CustomTreeEdge(); } } class CustomTreeVertex extends go.TreeVertex { someProp: number = 17; } class CustomTreeEdge extends go.TreeEdge { anotherProp: number = 1; } function init() { var $ = go.GraphObject.make; // for conciseness in defining templates var myDiagram: go.Diagram = $(go.Diagram, "myDiagram", // create a Diagram for the DIV HTML element { // position the graph in the middle of the diagram initialContentAlignment: go.Spot.Center, // allow double-click in background to create a new node "clickCreatingTool.archetypeNodeData": { text: "Node", color: "white" }, // allow Ctrl-G to call groupSelection() "commandHandler.archetypeGroupData": { text: "Group", isGroup: true, color: "blue" }, layout: $(CustomTreeLayout, { angle: 90 }), // enable undo & redo "undoManager.isEnabled": true }); // Define the appearance and behavior for Nodes: // First, define the shared context menu for all Nodes, Links, and Groups. // To simplify this code we define a function for creating a context menu button: function makeButton(text: string, action: (e: go.InputEvent, obj: go.GraphObject) => void, visiblePredicate?: (obj: go.GraphObject) => boolean) { if (visiblePredicate === undefined) visiblePredicate = o => true; return $("ContextMenuButton", $(go.TextBlock, text), { click: action }, // don't bother with binding GraphObject.visible if there's no predicate visiblePredicate ? new go.Binding("visible", "", visiblePredicate).ofObject() : {}); } // a context menu is an Adornment with a bunch of buttons in them var partContextMenu = $(go.Adornment, "Vertical", makeButton("Properties", (e, obj) => { // the OBJ is this Button var contextmenu = <go.Adornment>obj.part; // the Button is in the context menu Adornment var part = contextmenu.adornedPart; // the adornedPart is the Part that the context menu adorns // now can do something with PART, or with its data, or with the Adornment (the context menu) if (part instanceof go.Link) alert(linkInfo(part.data)); else if (part instanceof go.Group) alert(groupInfo(contextmenu)); else alert(nodeInfo(part.data)); }), makeButton("Cut", (e, obj) => e.diagram.commandHandler.cutSelection(), o => o.diagram.commandHandler.canCutSelection()), makeButton("Copy", (e, obj) => e.diagram.commandHandler.copySelection(), o => o.diagram.commandHandler.canCopySelection()), makeButton("Paste", (e, obj) => e.diagram.commandHandler.pasteSelection(e.diagram.lastInput.documentPoint), o => o.diagram.commandHandler.canPasteSelection()), makeButton("Delete", (e, obj) => e.diagram.commandHandler.deleteSelection(), o => o.diagram.commandHandler.canDeleteSelection()), makeButton("Undo", (e, obj) => e.diagram.commandHandler.undo(), o => o.diagram.commandHandler.canUndo()), makeButton("Redo", (e, obj) => e.diagram.commandHandler.redo(), o => o.diagram.commandHandler.canRedo()), makeButton("Group", (e, obj) => e.diagram.commandHandler.groupSelection(), o => o.diagram.commandHandler.canGroupSelection()), makeButton("Ungroup", (e, obj) => e.diagram.commandHandler.ungroupSelection(), o => o.diagram.commandHandler.canUngroupSelection()) ); function nodeInfo(d: any) { // Tooltip info for a node data object var str = "Node " + d.key + ": " + d.text + "\n"; if (d.group) str += "member of " + d.group; else str += "top-level node"; return str; } // These nodes have text surrounded by a rounded rectangle // whose fill color is bound to the node data. // The user can drag a node by dragging its TextBlock label. // Dragging from the Shape will start drawing a new link. myDiagram.nodeTemplate = $(go.Node, "Auto", { locationSpot: go.Spot.Center }, $(go.Shape, "RoundedRectangle", { fill: "white", // the default fill, if there is no data-binding portId: "", cursor: "pointer", // the Shape is the port, not the whole Node // allow all kinds of links from and to this port fromLinkable: true, fromLinkableSelfNode: true, fromLinkableDuplicates: true, toLinkable: true, toLinkableSelfNode: true, toLinkableDuplicates: true }, new go.Binding("fill", "color")), $(go.TextBlock, { font: "bold 14px sans-serif", stroke: '#333', margin: 6, // make some extra space for the shape around the text isMultiline: false, // don't allow newlines in text editable: true // allow in-place editing by user }, new go.Binding("text", "text").makeTwoWay()), // the label shows the node data's text { // this tooltip Adornment is shared by all nodes toolTip: $(go.Adornment, "Auto", $(go.Shape, { fill: "#FFFFCC" }), $(go.TextBlock, { margin: 4 }, // the tooltip shows the result of calling nodeInfo(data) new go.Binding("text", "", nodeInfo)) ), // this context menu Adornment is shared by all nodes contextMenu: partContextMenu } ); // Define the appearance and behavior for Links: function linkInfo(d: any) { // Tooltip info for a link data object return "Link:\nfrom " + d.from + " to " + d.to; } // The link shape and arrowhead have their stroke brush data bound to the "color" property myDiagram.linkTemplate = $(CustomLink, { relinkableFrom: true, relinkableTo: true }, // allow the user to relink existing links $(go.Shape, { strokeWidth: 2 }, new go.Binding("stroke", "color")), $(go.Shape, { toArrow: "Standard", stroke: null }, new go.Binding("fill", "color")), { // this tooltip Adornment is shared by all links toolTip: $(go.Adornment, "Auto", $(go.Shape, { fill: "#FFFFCC" }), $(go.TextBlock, { margin: 4 }, // the tooltip shows the result of calling linkInfo(data) new go.Binding("text", "", linkInfo)) ), // the same context menu Adornment is shared by all links contextMenu: partContextMenu } ); // Define the appearance and behavior for Groups: function groupInfo(adornment: go.Adornment) { // takes the tooltip, not a group node data object var g = <go.Group>adornment.adornedPart; // get the Group that the tooltip adorns var mems = g.memberParts.count; var links = g.memberParts.filter(p => p instanceof go.Link).count; return "Group " + g.data.key + ": " + g.data.text + "\n" + mems + " members including " + links + " links"; } // Groups consist of a title in the color given by the group node data // above a translucent gray rectangle surrounding the member parts myDiagram.groupTemplate = $(go.Group, "Vertical", { selectionObjectName: "PANEL", // selection handle goes around shape, not label ungroupable: true, // enable Ctrl-Shift-G to ungroup a selected Group layoutConditions: go.Part.LayoutStandard & ~go.Part.LayoutNodeSized }, $(go.TextBlock, { font: "bold 12pt sans-serif", isMultiline: false, // don't allow newlines in text editable: true // allow in-place editing by user }, new go.Binding("text", "text").makeTwoWay(), new go.Binding("stroke", "color")), $(go.Panel, "Auto", { name: "PANEL" }, $(go.Shape, "Rectangle", // the rectangular shape around the members { fill: "rgba(128,128,128,0.2)", stroke: "gray", strokeWidth: 3 }), $(go.Placeholder, { padding: 5 }) // represents where the members are ), { // this tooltip Adornment is shared by all groups toolTip: $(go.Adornment, "Auto", $(go.Shape, { fill: "#FFFFCC" }), $(go.TextBlock, { margin: 4 }, // bind to tooltip, not to Group.data, to allow access to Group properties new go.Binding("text", "", groupInfo).ofObject()) ), // the same context menu Adornment is shared by all groups contextMenu: partContextMenu } ); // Define the behavior for the Diagram background: function diagramInfo(model: go.GraphLinksModel) { // Tooltip info for the diagram's model return "Model:\n" + model.nodeDataArray.length + " nodes, " + model.linkDataArray.length + " links"; } // provide a tooltip for the background of the Diagram, when not over any Part myDiagram.toolTip = $(go.Adornment, "Auto", $(go.Shape, { fill: "#FFFFCC" }), $(go.TextBlock, { margin: 4 }, new go.Binding("text", "", diagramInfo)) ); // provide a context menu for the background of the Diagram, when not over any Part myDiagram.contextMenu = $(go.Adornment, "Vertical", makeButton("Paste", (e, obj) => e.diagram.commandHandler.pasteSelection(e.diagram.lastInput.documentPoint), o => o.diagram.commandHandler.canPasteSelection()), makeButton("Undo", (e, obj) => e.diagram.commandHandler.undo(), o => o.diagram.commandHandler.canUndo()), makeButton("Redo", (e, obj) => e.diagram.commandHandler.redo(), o => o.diagram.commandHandler.canRedo()) ); // Create the Diagram's Model: var nodeDataArray = [ { key: 1, text: "Alpha", color: "lightblue" }, { key: 2, text: "Beta", color: "orange" }, { key: 3, text: "Gamma", color: "lightgreen", group: 5 }, { key: 4, text: "Delta", color: "pink", group: 5 }, { key: 5, text: "Epsilon", color: "green", isGroup: true } ]; var linkDataArray = [ { from: 1, to: 2, color: "blue" }, { from: 2, to: 2 }, { from: 3, to: 4, color: "green" }, { from: 3, to: 1, color: "purple" } ]; myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray); var img = myDiagram.makeImageData({ scale: 0.4, position: new go.Point(-10, -10) }); }
the_stack
import { deepStrictEqual, strictEqual, throws } from 'assert'; import { Terminal } from 'headless/public/Terminal'; let term: Terminal; describe('Headless API Tests', function(): void { beforeEach(() => { // Create default terminal to be used by most tests term = new Terminal(); }); it('Default options', async () => { strictEqual(term.cols, 80); strictEqual(term.rows, 24); }); it('Proposed API check', async () => { term = new Terminal({ allowProposedApi: false }); throws(() => term.buffer, (error) => error.message === 'You must set the allowProposedApi option to true to use proposed API'); }); it('write', async () => { await writeSync('foo'); await writeSync('bar'); await writeSync('文'); lineEquals(0, 'foobar文'); }); it('write with callback', async () => { let result: string | undefined; await new Promise<void>(r => { term.write('foo', () => { result = 'a'; }); term.write('bar', () => { result += 'b'; }); term.write('文', () => { result += 'c'; r(); }); }); lineEquals(0, 'foobar文'); strictEqual(result, 'abc'); }); it('write - bytes (UTF8)', async () => { await writeSync(new Uint8Array([102, 111, 111])); // foo await writeSync(new Uint8Array([98, 97, 114])); // bar await writeSync(new Uint8Array([230, 150, 135])); // 文 lineEquals(0, 'foobar文'); }); it('write - bytes (UTF8) with callback', async () => { let result: string | undefined; await new Promise<void>(r => { term.write(new Uint8Array([102, 111, 111]), () => { result = 'A'; }); // foo term.write(new Uint8Array([98, 97, 114]), () => { result += 'B'; }); // bar term.write(new Uint8Array([230, 150, 135]), () => { // 文 result += 'C'; r(); }); }); lineEquals(0, 'foobar文'); strictEqual(result, 'ABC'); }); it('writeln', async () => { await writelnSync('foo'); await writelnSync('bar'); await writelnSync('文'); lineEquals(0, 'foo'); lineEquals(1, 'bar'); lineEquals(2, '文'); }); it('writeln with callback', async () => { let result: string | undefined; await new Promise<void>(r => { term.writeln('foo', () => { result = '1'; }); term.writeln('bar', () => { result += '2'; }); term.writeln('文', () => { result += '3'; r(); }); }); lineEquals(0, 'foo'); lineEquals(1, 'bar'); lineEquals(2, '文'); strictEqual(result, '123'); }); it('writeln - bytes (UTF8)', async () => { await writelnSync(new Uint8Array([102, 111, 111])); await writelnSync(new Uint8Array([98, 97, 114])); await writelnSync(new Uint8Array([230, 150, 135])); lineEquals(0, 'foo'); lineEquals(1, 'bar'); lineEquals(2, '文'); }); it('clear', async () => { term = new Terminal({ rows: 5 }); for (let i = 0; i < 10; i++) { await writeSync('\n\rtest' + i); } term.clear(); strictEqual(term.buffer.active.length, 5); lineEquals(0, 'test9'); for (let i = 1; i < 5; i++) { lineEquals(i, ''); } }); it('getOption, setOption', async () => { strictEqual(term.getOption('scrollback'), 1000); term.setOption('scrollback', 50); strictEqual(term.getOption('scrollback'), 50); }); describe('loadAddon', () => { it('constructor', async () => { term = new Terminal({ cols: 5 }); let cols = 0; term.loadAddon({ activate: (t) => cols = t.cols, dispose: () => {} }); strictEqual(cols, 5); }); it('dispose (addon)', async () => { let disposeCalled = false; const addon = { activate: () => {}, dispose: () => disposeCalled = true }; term.loadAddon(addon); strictEqual(disposeCalled, false); addon.dispose(); strictEqual(disposeCalled, true); }); it('dispose (terminal)', async () => { let disposeCalled = false; term.loadAddon({ activate: () => {}, dispose: () => disposeCalled = true }); strictEqual(disposeCalled, false); term.dispose(); strictEqual(disposeCalled, true); }); }); describe('Events', () => { it('onCursorMove', async () => { let callCount = 0; term.onCursorMove(e => callCount++); await writeSync('foo'); strictEqual(callCount, 1); await writeSync('bar'); strictEqual(callCount, 2); }); it('onData', async () => { const calls: string[] = []; term.onData(e => calls.push(e)); await writeSync('\x1b[5n'); // DSR Status Report deepStrictEqual(calls, ['\x1b[0n']); }); it('onLineFeed', async () => { let callCount = 0; term.onLineFeed(() => callCount++); await writelnSync('foo'); strictEqual(callCount, 1); await writelnSync('bar'); strictEqual(callCount, 2); }); it('onScroll', async () => { term = new Terminal({ rows: 5 }); const calls: number[] = []; term.onScroll(e => calls.push(e)); for (let i = 0; i < 4; i++) { await writelnSync('foo'); } deepStrictEqual(calls, []); await writelnSync('bar'); deepStrictEqual(calls, [1]); await writelnSync('baz'); deepStrictEqual(calls, [1, 2]); }); it('onResize', async () => { const calls: [number, number][] = []; term.onResize(e => calls.push([e.cols, e.rows])); deepStrictEqual(calls, []); term.resize(10, 5); deepStrictEqual(calls, [[10, 5]]); term.resize(20, 15); deepStrictEqual(calls, [[10, 5], [20, 15]]); }); it('onTitleChange', async () => { const calls: string[] = []; term.onTitleChange(e => calls.push(e)); deepStrictEqual(calls, []); await writeSync('\x1b]2;foo\x9c'); deepStrictEqual(calls, ['foo']); }); it('onBell', async () => { const calls: boolean[] = []; term.onBell(() => calls.push(true)); deepStrictEqual(calls, []); await writeSync('\x07'); deepStrictEqual(calls, [true]); }); }); describe('buffer', () => { it('cursorX, cursorY', async () => { term = new Terminal({ rows: 5, cols: 5 }); strictEqual(term.buffer.active.cursorX, 0); strictEqual(term.buffer.active.cursorY, 0); await writeSync('foo'); strictEqual(term.buffer.active.cursorX, 3); strictEqual(term.buffer.active.cursorY, 0); await writeSync('\n'); strictEqual(term.buffer.active.cursorX, 3); strictEqual(term.buffer.active.cursorY, 1); await writeSync('\r'); strictEqual(term.buffer.active.cursorX, 0); strictEqual(term.buffer.active.cursorY, 1); await writeSync('abcde'); strictEqual(term.buffer.active.cursorX, 5); strictEqual(term.buffer.active.cursorY, 1); await writeSync('\n\r\n\n\n\n\n'); strictEqual(term.buffer.active.cursorX, 0); strictEqual(term.buffer.active.cursorY, 4); }); it('viewportY', async () => { term = new Terminal({ rows: 5 }); strictEqual(term.buffer.active.viewportY, 0); await writeSync('\n\n\n\n'); strictEqual(term.buffer.active.viewportY, 0); await writeSync('\n'); strictEqual(term.buffer.active.viewportY, 1); await writeSync('\n\n\n\n'); strictEqual(term.buffer.active.viewportY, 5); term.scrollLines(-1); strictEqual(term.buffer.active.viewportY, 4); term.scrollToTop(); strictEqual(term.buffer.active.viewportY, 0); }); it('baseY', async () => { term = new Terminal({ rows: 5 }); strictEqual(term.buffer.active.baseY, 0); await writeSync('\n\n\n\n'); strictEqual(term.buffer.active.baseY, 0); await writeSync('\n'); strictEqual(term.buffer.active.baseY, 1); await writeSync('\n\n\n\n'); strictEqual(term.buffer.active.baseY, 5); term.scrollLines(-1); strictEqual(term.buffer.active.baseY, 5); term.scrollToTop(); strictEqual(term.buffer.active.baseY, 5); }); it('length', async () => { term = new Terminal({ rows: 5 }); strictEqual(term.buffer.active.length, 5); await writeSync('\n\n\n\n'); strictEqual(term.buffer.active.length, 5); await writeSync('\n'); strictEqual(term.buffer.active.length, 6); await writeSync('\n\n\n\n'); strictEqual(term.buffer.active.length, 10); }); describe('getLine', () => { it('invalid index', async () => { term = new Terminal({ rows: 5 }); strictEqual(term.buffer.active.getLine(-1), undefined); strictEqual(term.buffer.active.getLine(5), undefined); }); it('isWrapped', async () => { term = new Terminal({ cols: 5 }); strictEqual(term.buffer.active.getLine(0)!.isWrapped, false); strictEqual(term.buffer.active.getLine(1)!.isWrapped, false); await writeSync('abcde'); strictEqual(term.buffer.active.getLine(0)!.isWrapped, false); strictEqual(term.buffer.active.getLine(1)!.isWrapped, false); await writeSync('f'); strictEqual(term.buffer.active.getLine(0)!.isWrapped, false); strictEqual(term.buffer.active.getLine(1)!.isWrapped, true); }); it('translateToString', async () => { term = new Terminal({ cols: 5 }); strictEqual(term.buffer.active.getLine(0)!.translateToString(), ' '); strictEqual(term.buffer.active.getLine(0)!.translateToString(true), ''); await writeSync('foo'); strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'foo '); strictEqual(term.buffer.active.getLine(0)!.translateToString(true), 'foo'); await writeSync('bar'); strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'fooba'); strictEqual(term.buffer.active.getLine(0)!.translateToString(true), 'fooba'); strictEqual(term.buffer.active.getLine(1)!.translateToString(true), 'r'); strictEqual(term.buffer.active.getLine(0)!.translateToString(false, 1), 'ooba'); strictEqual(term.buffer.active.getLine(0)!.translateToString(false, 1, 3), 'oo'); }); it('getCell', async () => { term = new Terminal({ cols: 5 }); strictEqual(term.buffer.active.getLine(0)!.getCell(-1), undefined); strictEqual(term.buffer.active.getLine(0)!.getCell(5), undefined); strictEqual(term.buffer.active.getLine(0)!.getCell(0)!.getChars(), ''); strictEqual(term.buffer.active.getLine(0)!.getCell(0)!.getWidth(), 1); await writeSync('a文'); strictEqual(term.buffer.active.getLine(0)!.getCell(0)!.getChars(), 'a'); strictEqual(term.buffer.active.getLine(0)!.getCell(0)!.getWidth(), 1); strictEqual(term.buffer.active.getLine(0)!.getCell(1)!.getChars(), '文'); strictEqual(term.buffer.active.getLine(0)!.getCell(1)!.getWidth(), 2); strictEqual(term.buffer.active.getLine(0)!.getCell(2)!.getChars(), ''); strictEqual(term.buffer.active.getLine(0)!.getCell(2)!.getWidth(), 0); }); }); it('active, normal, alternate', async () => { term = new Terminal({ cols: 5 }); strictEqual(term.buffer.active.type, 'normal'); strictEqual(term.buffer.normal.type, 'normal'); strictEqual(term.buffer.alternate.type, 'alternate'); await writeSync('norm '); strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'norm '); strictEqual(term.buffer.normal.getLine(0)!.translateToString(), 'norm '); strictEqual(term.buffer.alternate.getLine(0), undefined); await writeSync('\x1b[?47h\r'); // use alternate screen buffer strictEqual(term.buffer.active.type, 'alternate'); strictEqual(term.buffer.normal.type, 'normal'); strictEqual(term.buffer.alternate.type, 'alternate'); strictEqual(term.buffer.active.getLine(0)!.translateToString(), ' '); await writeSync('alt '); strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'alt '); strictEqual(term.buffer.normal.getLine(0)!.translateToString(), 'norm '); strictEqual(term.buffer.alternate.getLine(0)!.translateToString(), 'alt '); await writeSync('\x1b[?47l\r'); // use normal screen buffer strictEqual(term.buffer.active.type, 'normal'); strictEqual(term.buffer.normal.type, 'normal'); strictEqual(term.buffer.alternate.type, 'alternate'); strictEqual(term.buffer.active.getLine(0)!.translateToString(), 'norm '); strictEqual(term.buffer.normal.getLine(0)!.translateToString(), 'norm '); strictEqual(term.buffer.alternate.getLine(0), undefined); }); }); describe('modes', () => { it('defaults', () => { deepStrictEqual(term.modes, { applicationCursorKeysMode: false, applicationKeypadMode: false, bracketedPasteMode: false, insertMode: false, mouseTrackingMode: 'none', originMode: false, reverseWraparoundMode: false, sendFocusMode: false, wraparoundMode: true }); }); it('applicationCursorKeysMode', async () => { await writeSync('\x1b[?1h'); strictEqual(term.modes.applicationCursorKeysMode, true); await writeSync('\x1b[?1l'); strictEqual(term.modes.applicationCursorKeysMode, false); }); it('applicationKeypadMode', async () => { await writeSync('\x1b[?66h'); strictEqual(term.modes.applicationKeypadMode, true); await writeSync('\x1b[?66l'); strictEqual(term.modes.applicationKeypadMode, false); }); it('bracketedPasteMode', async () => { await writeSync('\x1b[?2004h'); strictEqual(term.modes.bracketedPasteMode, true); await writeSync('\x1b[?2004l'); strictEqual(term.modes.bracketedPasteMode, false); }); it('insertMode', async () => { await writeSync('\x1b[4h'); strictEqual(term.modes.insertMode, true); await writeSync('\x1b[4l'); strictEqual(term.modes.insertMode, false); }); it('mouseTrackingMode', async () => { await writeSync('\x1b[?9h'); strictEqual(term.modes.mouseTrackingMode, 'x10'); await writeSync('\x1b[?9l'); strictEqual(term.modes.mouseTrackingMode, 'none'); await writeSync('\x1b[?1000h'); strictEqual(term.modes.mouseTrackingMode, 'vt200'); await writeSync('\x1b[?1000l'); strictEqual(term.modes.mouseTrackingMode, 'none'); await writeSync('\x1b[?1002h'); strictEqual(term.modes.mouseTrackingMode, 'drag'); await writeSync('\x1b[?1002l'); strictEqual(term.modes.mouseTrackingMode, 'none'); await writeSync('\x1b[?1003h'); strictEqual(term.modes.mouseTrackingMode, 'any'); await writeSync('\x1b[?1003l'); strictEqual(term.modes.mouseTrackingMode, 'none'); }); it('originMode', async () => { await writeSync('\x1b[?6h'); strictEqual(term.modes.originMode, true); await writeSync('\x1b[?6l'); strictEqual(term.modes.originMode, false); }); it('reverseWraparoundMode', async () => { await writeSync('\x1b[?45h'); strictEqual(term.modes.reverseWraparoundMode, true); await writeSync('\x1b[?45l'); strictEqual(term.modes.reverseWraparoundMode, false); }); it('sendFocusMode', async () => { await writeSync('\x1b[?1004h'); strictEqual(term.modes.sendFocusMode, true); await writeSync('\x1b[?1004l'); strictEqual(term.modes.sendFocusMode, false); }); it('wraparoundMode', async () => { await writeSync('\x1b[?7h'); strictEqual(term.modes.wraparoundMode, true); await writeSync('\x1b[?7l'); strictEqual(term.modes.wraparoundMode, false); }); }); it('dispose', async () => { term.dispose(); strictEqual((term as any)._core._isDisposed, true); }); }); function writeSync(text: string | Uint8Array): Promise<void> { return new Promise<void>(r => term.write(text, r)); } function writelnSync(text: string | Uint8Array): Promise<void> { return new Promise<void>(r => term.writeln(text, r)); } function lineEquals(index: number, text: string): void { strictEqual(term.buffer.active.getLine(index)!.translateToString(true), text); }
the_stack
import { all, DI, IContainer, ignore, IRegistry, optional, Registration } from './di.js'; import { bound, toLookup } from './functions.js'; import { Class, Constructable } from './interfaces.js'; import { getAnnotationKeyFor } from './resource.js'; import { Metadata } from '@aurelia/metadata'; import { IPlatform } from './platform.js'; import { defineMetadata, isFunction } from './utilities.js'; export const enum LogLevel { /** * The most detailed information about internal app state. * * Disabled by default and should never be enabled in a production environment. */ trace = 0, /** * Information that is useful for debugging during development and has no long-term value. */ debug = 1, /** * Information about the general flow of the application that has long-term value. */ info = 2, /** * Unexpected circumstances that require attention but do not otherwise cause the current flow of execution to stop. */ warn = 3, /** * Unexpected circumstances that cause the flow of execution in the current activity to stop but do not cause an app-wide failure. */ error = 4, /** * Unexpected circumstances that cause an app-wide failure or otherwise require immediate attention. */ fatal = 5, /** * No messages should be written. */ none = 6, } /** * Flags to enable/disable color usage in the logging output. */ export const enum ColorOptions { /** * Do not use ASCII color codes in logging output. */ noColors = 0, /** * Use ASCII color codes in logging output. By default, timestamps and the TRC and DBG prefix are colored grey. INF white, WRN yellow, and ERR and FTL red. */ colors = 1, } /** * The global logger configuration. * * Properties on this object can be changed during runtime and will affect logging of all components that are housed under the same root DI container as the logger. */ export interface ILogConfig { /** * The global color options. */ colorOptions: ColorOptions; /** * The global log level. Only log calls with the same level or higher are emitted. */ level: LogLevel; } interface ILoggingConfigurationOptions extends ILogConfig { $console: IConsoleLike; sinks: (Class<ISink> | IRegistry)[]; } /** * Component that creates log event objects based on raw inputs sent to `ILogger`. * * To customize what data is sent to the sinks, replace the implementation for this interface with your own. * * @example * * ```ts * export class MyLogEventFactory { * public createLogEvent(logger: ILogger, logLevel: LogLevel, message: string, optionalParams: unknown[]): ILogEvent { * return { * logLevel, * optionalParams, * toString() { * return `[${logger.scope.join('.')}] ${message} ${optionalParams.join(', ')}`; * } * }; * } * } * * container.register(Registration.singleton(ILogEventFactory, MyLogEventFactory)); * ``` */ export interface ILogEventFactory { /** * Create a log event object based on the input parameters sent to `ILogger`. * * @param logger - The `ILogger` that received the message. * @param logLevel - The `LogLevel` associated with the `ILogger` method that the message was passed into. E.g. `logger.debug` will result in `LogLevel.debug` * @param message - The message (first parameter) that was passed into the logger. If a function was passed into the logger, this will be the return value of that function. * @param optionalParams - Additional optional parameters there were passed into the logger, if any. * * @returns An `ILogEvent` object that, by default, only has a `.toString()` method. * * This is called by the default console sink to get the message to emit to the console. * It could be any object of any shape, as long as the registered sinks understand that shape. */ createLogEvent(logger: ILogger, logLevel: LogLevel, message: string, optionalParams: unknown[]): ILogEvent; } /** * A logging sink that emits `ILogEvent` objects to any kind of output. This can be the console, a database, a web api, a file, etc. * * Multiple sinks can be registered, and all events will be emitted to all of them. * * @example * // A buffered file sink that writes once per second: * * ```ts * export class BufferedFileSink { * private readonly buffer: ILogEvent[] = []; * * constructor() { * setInterval(() => { * const events = this.buffer.splice(0); * if (events.length > 0) { * fs.appendFileSync('my-log.txt', events.map(e => e.toString()).join('\n')); * } * }, 1000); * } * * public emit(event: ILogEvent): void { * this.buffer.push(event); * } * } * * container.register(Registration.singleton(ISink, BufferedFileSink)); * ``` */ export interface ISink { /** * Handle the provided `ILogEvent` to the output interface wrapped by this sink. * * @param event - The event object to emit. Built-in sinks will call `.toString()` on the event object but custom sinks can do anything they like with the event. */ handleEvent(event: ILogEvent): void; } /** * The main interface to the logging API. * * Inject this as a dependency in your components to add centralized, configurable logging capabilities to your application. */ export interface ILogger extends DefaultLogger {} export const ILogConfig = DI.createInterface<ILogConfig>('ILogConfig', x => x.instance(new LogConfig(ColorOptions.noColors, LogLevel.warn))); export const ISink = DI.createInterface<ISink>('ISink'); export const ILogEventFactory = DI.createInterface<ILogEventFactory>('ILogEventFactory', x => x.singleton(DefaultLogEventFactory)); export const ILogger = DI.createInterface<ILogger>('ILogger', x => x.singleton(DefaultLogger)); export const ILogScopes = DI.createInterface<string[]>('ILogScope'); interface SinkDefinition { handles: Exclude<LogLevel, LogLevel.none>[]; } export const LoggerSink = Object.freeze({ key: getAnnotationKeyFor('logger-sink-handles'), define<TSink extends ISink>(target: Constructable<TSink>, definition: SinkDefinition) { defineMetadata(this.key, definition.handles, target.prototype); return target; }, getHandles<TSink extends ISink>(target: Constructable<TSink> | TSink) { return Metadata.get(this.key, target) as LogLevel[] | undefined; }, }); export function sink(definition: SinkDefinition) { return function <TSink extends ISink>(target: Constructable<TSink>): Constructable<TSink> { return LoggerSink.define(target, definition); }; } export interface IConsoleLike { debug(message: string, ...optionalParams: unknown[]): void; info(message: string, ...optionalParams: unknown[]): void; warn(message: string, ...optionalParams: unknown[]): void; error(message: string, ...optionalParams: unknown[]): void; } // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics export const format = toLookup({ red<T extends string>(str: T): T { return `\u001b[31m${str}\u001b[39m` as T; }, green<T extends string>(str: T): T { return `\u001b[32m${str}\u001b[39m` as T; }, yellow<T extends string>(str: T): T { return `\u001b[33m${str}\u001b[39m` as T; }, blue<T extends string>(str: T): T { return `\u001b[34m${str}\u001b[39m` as T; }, magenta<T extends string>(str: T): T { return `\u001b[35m${str}\u001b[39m` as T; }, cyan<T extends string>(str: T): T { return `\u001b[36m${str}\u001b[39m` as T; }, white<T extends string>(str: T): T { return `\u001b[37m${str}\u001b[39m` as T; }, grey<T extends string>(str: T): T { return `\u001b[90m${str}\u001b[39m` as T; }, } as const); export interface ILogEvent { readonly severity: LogLevel; readonly optionalParams?: readonly unknown[]; toString(): string; } export class LogConfig implements ILogConfig { public constructor( public readonly colorOptions: ColorOptions, public readonly level: LogLevel, ) {} } const getLogLevelString = (function () { const logLevelString = [ toLookup({ TRC: 'TRC', DBG: 'DBG', INF: 'INF', WRN: 'WRN', ERR: 'ERR', FTL: 'FTL', QQQ: '???', } as const), toLookup({ TRC: format.grey('TRC'), DBG: format.grey('DBG'), INF: format.white('INF'), WRN: format.yellow('WRN'), ERR: format.red('ERR'), FTL: format.red('FTL'), QQQ: format.grey('???'), } as const), ] as const; return function (level: LogLevel, colorOptions: ColorOptions): string { if (level <= LogLevel.trace) { return logLevelString[colorOptions].TRC; } if (level <= LogLevel.debug) { return logLevelString[colorOptions].DBG; } if (level <= LogLevel.info) { return logLevelString[colorOptions].INF; } if (level <= LogLevel.warn) { return logLevelString[colorOptions].WRN; } if (level <= LogLevel.error) { return logLevelString[colorOptions].ERR; } if (level <= LogLevel.fatal) { return logLevelString[colorOptions].FTL; } return logLevelString[colorOptions].QQQ; }; })(); function getScopeString(scope: readonly string[], colorOptions: ColorOptions): string { if (colorOptions === ColorOptions.noColors) { return scope.join('.'); } return scope.map(format.cyan).join('.'); } function getIsoString(timestamp: number, colorOptions: ColorOptions): string { if (colorOptions === ColorOptions.noColors) { return new Date(timestamp).toISOString(); } return format.grey(new Date(timestamp).toISOString()); } export class DefaultLogEvent implements ILogEvent { public constructor( public readonly severity: LogLevel, public readonly message: string, public readonly optionalParams: unknown[], public readonly scope: readonly string[], public readonly colorOptions: ColorOptions, public readonly timestamp: number, ) {} public toString(): string { const { severity, message, scope, colorOptions, timestamp } = this; if (scope.length === 0) { return `${getIsoString(timestamp, colorOptions)} [${getLogLevelString(severity, colorOptions)}] ${message}`; } return `${getIsoString(timestamp, colorOptions)} [${getLogLevelString(severity, colorOptions)} ${getScopeString(scope, colorOptions)}] ${message}`; } } export class DefaultLogEventFactory implements ILogEventFactory { public constructor( @ILogConfig public readonly config: ILogConfig, ) {} public createLogEvent(logger: ILogger, level: LogLevel, message: string, optionalParams: unknown[]): ILogEvent { return new DefaultLogEvent(level, message, optionalParams, logger.scope, this.config.colorOptions, Date.now()); } } export class ConsoleSink implements ISink { public static register(container: IContainer) { Registration.singleton(ISink, ConsoleSink).register(container); } public readonly handleEvent: (event: ILogEvent) => void; public constructor( @IPlatform p: IPlatform, ) { const $console = p.console as { debug(...args: unknown[]): void; info(...args: unknown[]): void; warn(...args: unknown[]): void; error(...args: unknown[]): void; }; this.handleEvent = function emit(event: ILogEvent): void { const optionalParams = event.optionalParams; if (optionalParams === void 0 || optionalParams.length === 0) { const msg = event.toString(); switch (event.severity) { case LogLevel.trace: case LogLevel.debug: return $console.debug(msg); case LogLevel.info: return $console.info(msg); case LogLevel.warn: return $console.warn(msg); case LogLevel.error: case LogLevel.fatal: return $console.error(msg); } } else { let msg = event.toString(); let offset = 0; // console.log in chrome doesn't call .toString() on object inputs (https://bugs.chromium.org/p/chromium/issues/detail?id=1146817) while (msg.includes('%s')) { msg = msg.replace('%s', String(optionalParams[offset++])); } switch (event.severity) { case LogLevel.trace: case LogLevel.debug: return $console.debug(msg, ...optionalParams.slice(offset)); case LogLevel.info: return $console.info(msg, ...optionalParams.slice(offset)); case LogLevel.warn: return $console.warn(msg, ...optionalParams.slice(offset)); case LogLevel.error: case LogLevel.fatal: return $console.error(msg, ...optionalParams.slice(offset)); } } }; } } export class DefaultLogger { /** * The root `ILogger` instance. On the root logger itself, this property circularly references the root. It is never null. * * When using `.scopeTo`, a new `ILogger` is created. That new logger will have the `root` property set to the global (non-scoped) logger. */ public readonly root: ILogger; /** * The parent `ILogger` instance. On the root logger itself, this property circularly references the root. It is never null. * * When using `.scopeTo`, a new `ILogger` is created. That new logger will have the `parent` property set to the logger that it was created from. */ public readonly parent: ILogger; /** @internal */ public readonly traceSinks: ISink[]; /** @internal */ public readonly debugSinks: ISink[]; /** @internal */ public readonly infoSinks: ISink[]; /** @internal */ public readonly warnSinks: ISink[]; /** @internal */ public readonly errorSinks: ISink[]; /** @internal */ public readonly fatalSinks: ISink[]; private readonly scopedLoggers: { [key: string]: ILogger | undefined } = Object.create(null); public constructor( /** * The global logger configuration. */ @ILogConfig public readonly config: ILogConfig, @ILogEventFactory private readonly factory: ILogEventFactory, @all(ISink) sinks: readonly ISink[], /** * The scopes that this logger was created for, if any. */ @optional(ILogScopes) public readonly scope: string[] = [], @ignore parent: DefaultLogger | null = null, ) { let traceSinks: ISink[]; let debugSinks: ISink[]; let infoSinks: ISink[]; let warnSinks: ISink[]; let errorSinks: ISink[]; let fatalSinks: ISink[]; if (parent === null) { this.root = this; this.parent = this; traceSinks = this.traceSinks = []; debugSinks = this.debugSinks = []; infoSinks = this.infoSinks = []; warnSinks = this.warnSinks = []; errorSinks = this.errorSinks = []; fatalSinks = this.fatalSinks = []; for (const $sink of sinks) { const handles = LoggerSink.getHandles($sink); if (handles?.includes(LogLevel.trace) ?? true) { traceSinks.push($sink); } if (handles?.includes(LogLevel.debug) ?? true) { debugSinks.push($sink); } if (handles?.includes(LogLevel.info) ?? true) { infoSinks.push($sink); } if (handles?.includes(LogLevel.warn) ?? true) { warnSinks.push($sink); } if (handles?.includes(LogLevel.error) ?? true) { errorSinks.push($sink); } if (handles?.includes(LogLevel.fatal) ?? true) { fatalSinks.push($sink); } } } else { this.root = parent.root; this.parent = parent; traceSinks = this.traceSinks = parent.traceSinks; debugSinks = this.debugSinks = parent.debugSinks; infoSinks = this.infoSinks = parent.infoSinks; warnSinks = this.warnSinks = parent.warnSinks; errorSinks = this.errorSinks = parent.errorSinks; fatalSinks = this.fatalSinks = parent.fatalSinks; } } /** * Write to TRC output, if the configured `LogLevel` is set to `trace`. * * Intended for the most detailed information about internal app state. * * @param getMessage - A function to build the message to pass to the `ILogEventFactory`. * Only called if the configured `LogLevel` dictates that these messages be emitted. * Use this when creating the log message is potentially expensive and should only be done if the log is actually emitted. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public trace(getMessage: () => unknown, ...optionalParams: unknown[]): void; /** * Write to TRC output, if the configured `LogLevel` is set to `trace`. * * Intended for the most detailed information about internal app state. * * @param message - The message to pass to the `ILogEventFactory`. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public trace(message: unknown, ...optionalParams: unknown[]): void; @bound public trace(messageOrGetMessage: unknown, ...optionalParams: unknown[]): void { if (this.config.level <= LogLevel.trace) { this.emit(this.traceSinks, LogLevel.trace, messageOrGetMessage, optionalParams); } } /** * Write to DBG output, if the configured `LogLevel` is set to `debug` or lower. * * Intended for information that is useful for debugging during development and has no long-term value. * * @param getMessage - A function to build the message to pass to the `ILogEventFactory`. * Only called if the configured `LogLevel` dictates that these messages be emitted. * Use this when creating the log message is potentially expensive and should only be done if the log is actually emitted. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public debug(getMessage: () => unknown, ...optionalParams: unknown[]): void; /** * Write to DBG output, if the configured `LogLevel` is set to `debug` or lower. * * Intended for information that is useful for debugging during development and has no long-term value. * * @param message - The message to pass to the `ILogEventFactory`. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public debug(message: unknown, ...optionalParams: unknown[]): void; @bound public debug(messageOrGetMessage: unknown, ...optionalParams: unknown[]): void { if (this.config.level <= LogLevel.debug) { this.emit(this.debugSinks, LogLevel.debug, messageOrGetMessage, optionalParams); } } /** * Write to trace UBF, if the configured `LogLevel` is set to `info` or lower. * * Intended for information about the general flow of the application that has long-term value. * * @param getMessage - A function to build the message to pass to the `ILogEventFactory`. * Only called if the configured `LogLevel` dictates that these messages be emitted. * Use this when creating the log message is potentially expensive and should only be done if the log is actually emitted. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public info(getMessage: () => unknown, ...optionalParams: unknown[]): void; /** * Write to trace UBF, if the configured `LogLevel` is set to `info` or lower. * * Intended for information about the general flow of the application that has long-term value. * * @param message - The message to pass to the `ILogEventFactory`. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public info(message: unknown, ...optionalParams: unknown[]): void; @bound public info(messageOrGetMessage: unknown, ...optionalParams: unknown[]): void { if (this.config.level <= LogLevel.info) { this.emit(this.infoSinks, LogLevel.info, messageOrGetMessage, optionalParams); } } /** * Write to WRN output, if the configured `LogLevel` is set to `warn` or lower. * * Intended for unexpected circumstances that require attention but do not otherwise cause the current flow of execution to stop. * * @param getMessage - A function to build the message to pass to the `ILogEventFactory`. * Only called if the configured `LogLevel` dictates that these messages be emitted. * Use this when creating the log message is potentially expensive and should only be done if the log is actually emitted. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public warn(getMessage: () => unknown, ...optionalParams: unknown[]): void; /** * Write to WRN output, if the configured `LogLevel` is set to `warn` or lower. * * Intended for unexpected circumstances that require attention but do not otherwise cause the current flow of execution to stop. * * @param message - The message to pass to the `ILogEventFactory`. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public warn(message: unknown, ...optionalParams: unknown[]): void; @bound public warn(messageOrGetMessage: unknown, ...optionalParams: unknown[]): void { if (this.config.level <= LogLevel.warn) { this.emit(this.warnSinks, LogLevel.warn, messageOrGetMessage, optionalParams); } } /** * Write to ERR output, if the configured `LogLevel` is set to `error` or lower. * * Intended for unexpected circumstances that cause the flow of execution in the current activity to stop but do not cause an app-wide failure. * * @param getMessage - A function to build the message to pass to the `ILogEventFactory`. * Only called if the configured `LogLevel` dictates that these messages be emitted. * Use this when creating the log message is potentially expensive and should only be done if the log is actually emitted. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public error(getMessage: () => unknown, ...optionalParams: unknown[]): void; /** * Write to ERR output, if the configured `LogLevel` is set to `error` or lower. * * Intended for unexpected circumstances that cause the flow of execution in the current activity to stop but do not cause an app-wide failure. * * @param message - The message to pass to the `ILogEventFactory`. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public error(message: unknown, ...optionalParams: unknown[]): void; @bound public error(messageOrGetMessage: unknown, ...optionalParams: unknown[]): void { if (this.config.level <= LogLevel.error) { this.emit(this.errorSinks, LogLevel.error, messageOrGetMessage, optionalParams); } } /** * Write to FTL output, if the configured `LogLevel` is set to `fatal` or lower. * * Intended for unexpected circumstances that cause an app-wide failure or otherwise require immediate attention. * * @param getMessage - A function to build the message to pass to the `ILogEventFactory`. * Only called if the configured `LogLevel` dictates that these messages be emitted. * Use this when creating the log message is potentially expensive and should only be done if the log is actually emitted. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public fatal(getMessage: () => unknown, ...optionalParams: unknown[]): void; /** * Write to FTL output, if the configured `LogLevel` is set to `fatal` or lower. * * Intended for unexpected circumstances that cause an app-wide failure or otherwise require immediate attention. * * @param message - The message to pass to the `ILogEventFactory`. * @param optionalParams - Any additional, optional params that should be passed to the `ILogEventFactory` */ public fatal(message: unknown, ...optionalParams: unknown[]): void; @bound public fatal(messageOrGetMessage: unknown, ...optionalParams: unknown[]): void { if (this.config.level <= LogLevel.fatal) { this.emit(this.fatalSinks, LogLevel.fatal, messageOrGetMessage, optionalParams); } } /** * Create a new logger with an additional permanent prefix added to the logging outputs. * When chained, multiple scopes are separated by a dot. * * This is preliminary API and subject to change before alpha release. * * @example * * ```ts * export class MyComponent { * constructor(@ILogger private logger: ILogger) { * this.logger.debug('before scoping'); * // console output: '[DBG] before scoping' * this.logger = logger.scopeTo('MyComponent'); * this.logger.debug('after scoping'); * // console output: '[DBG MyComponent] after scoping' * } * * public doStuff(): void { * const logger = this.logger.scopeTo('doStuff()'); * logger.debug('doing stuff'); * // console output: '[DBG MyComponent.doStuff()] doing stuff' * } * } * ``` */ public scopeTo(name: string): ILogger { const scopedLoggers = this.scopedLoggers; let scopedLogger = scopedLoggers[name]; if (scopedLogger === void 0) { scopedLogger = scopedLoggers[name] = new DefaultLogger(this.config, this.factory, (void 0)!, this.scope.concat(name), this); } return scopedLogger; } private emit(sinks: ISink[], level: LogLevel, msgOrGetMsg: unknown, optionalParams: unknown[]): void { const message = isFunction(msgOrGetMsg) ? msgOrGetMsg() : msgOrGetMsg; const event = this.factory.createLogEvent(this, level, message, optionalParams); for (let i = 0, ii = sinks.length; i < ii; ++i) { sinks[i].handleEvent(event); } } } /** * A basic `ILogger` configuration that configures a single `console` sink based on provided options. * * NOTE: You *must* register the return value of `.create` with the container / au instance, not this `LoggerConfiguration` object itself. * * @example * ```ts * container.register(LoggerConfiguration.create()); * * container.register(LoggerConfiguration.create({sinks: [ConsoleSink]})) * * container.register(LoggerConfiguration.create({sinks: [ConsoleSink], level: LogLevel.debug})) * * ``` */ export const LoggerConfiguration = toLookup({ /** * @param $console - The `console` object to use. Can be the native `window.console` / `global.console`, but can also be a wrapper or mock that implements the same interface. * @param level - The global `LogLevel` to configure. Defaults to `warn` or higher. * @param colorOptions - Whether to use colors or not. Defaults to `noColors`. Colors are especially nice in nodejs environments but don't necessarily work (well) in all environments, such as browsers. */ create( { level = LogLevel.warn, colorOptions = ColorOptions.noColors, sinks = [], }: Partial<ILoggingConfigurationOptions> = {} ): IRegistry { return toLookup({ register(container: IContainer): IContainer { container.register( Registration.instance(ILogConfig, new LogConfig(colorOptions, level)), ); for (const $sink of sinks) { if (isFunction($sink)) { container.register(Registration.singleton(ISink, $sink)); } else { container.register($sink); } } return container; }, }); }, });
the_stack
* @fileoverview Unit tests for ThumbnailUploaderComponent. */ import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NO_ERRORS_SCHEMA, SimpleChanges } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { of } from 'rxjs'; import { AlertsService } from 'services/alerts.service'; import { AssetsBackendApiService } from 'services/assets-backend-api.service'; import { ContextService } from 'services/context.service'; import { ImageLocalStorageService } from 'services/image-local-storage.service'; import { ImageUploadHelperService } from 'services/image-upload-helper.service'; import { MockTranslatePipe } from 'tests/unit-test-utils'; import { EditThumbnailModalComponent } from './edit-thumbnail-modal.component'; import { ThumbnailUploaderComponent } from './thumbnail-uploader.component'; describe('ThumbnailUploaderComponent', () => { let fixture: ComponentFixture<ThumbnailUploaderComponent>; let component: ThumbnailUploaderComponent; let contextService: ContextService; let imageUploadHelperService: ImageUploadHelperService; let assetsBackendApiService: AssetsBackendApiService; let imageLocalStorageService: ImageLocalStorageService; let alertsService: AlertsService; let ngbModal: NgbModal; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], declarations: [ ThumbnailUploaderComponent, EditThumbnailModalComponent, MockTranslatePipe ], providers: [ImageUploadHelperService], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ThumbnailUploaderComponent); component = fixture.componentInstance; contextService = TestBed.inject(ContextService); imageUploadHelperService = TestBed.inject(ImageUploadHelperService); assetsBackendApiService = TestBed.inject(AssetsBackendApiService); imageLocalStorageService = TestBed.inject(ImageLocalStorageService); alertsService = TestBed.inject(AlertsService); ngbModal = TestBed.inject(NgbModal); spyOn(contextService, 'getEntityType').and.returnValue('exploration'); spyOn(contextService, 'getEntityId').and.returnValue('expId'); }); it('should set uploaded and editable thumbnail on initialization', () => { component.filename = 'thumbnail-1'; expect(component.editableThumbnailDataUrl).toBe(undefined); expect(component.uploadedImage).toBe(undefined); component.ngOnInit(); expect(component.editableThumbnailDataUrl) .toBe('/assetsdevhandler/exploration/expId/assets/thumbnail/thumbnail-1'); expect(component.uploadedImage) .toBe('/assetsdevhandler/exploration/expId/assets/thumbnail/thumbnail-1'); }); it('should update the thumbnail image when thumbnail filename' + ' changes', () => { component.filename = 'thumbnail-1'; let changes: SimpleChanges = { filename: { currentValue: 'thumbnail-2', previousValue: 'thumbnail-1', firstChange: false, isFirstChange: () => false } }; component.ngOnInit(); expect(component.editableThumbnailDataUrl) .toBe('/assetsdevhandler/exploration/expId/assets/thumbnail/thumbnail-1'); component.ngOnChanges(changes); expect(component.editableThumbnailDataUrl) .toBe('/assetsdevhandler/exploration/expId/assets/thumbnail/thumbnail-2'); }); it('should not update the thumbnail image when new thumbnail is same as' + ' the old one', () => { spyOn( imageUploadHelperService, 'getTrustedResourceUrlForThumbnailFilename'); component.filename = 'thumbnail-1'; let changes: SimpleChanges = { filename: { currentValue: 'thumbnail-1', previousValue: 'thumbnail-1', firstChange: true, isFirstChange: () => true } }; expect(component.editableThumbnailDataUrl).toBe(undefined); component.ngOnChanges(changes); expect(component.editableThumbnailDataUrl).toBe(undefined); expect(imageUploadHelperService.getTrustedResourceUrlForThumbnailFilename) .not.toHaveBeenCalled(); }); it('should not show edit thumbnail modal if editing thumbnail is' + ' disabled', () => { component.disabled = true; spyOn(ngbModal, 'open'); expect(component.openInUploadMode).toBe(undefined); component.showEditThumbnailModal(); // Here, openInUpload mode is not set as which means, showEditThumbnailModal // returned as soon as the first check was executed. expect(component.openInUploadMode).toBe(undefined); expect(ngbModal.open).not.toHaveBeenCalled(); }); it('should show edit thumbnail modal when user clicks on edit button and' + ' post thumbnail to server if local storage is not used and modal is' + ' opened in upload mode', fakeAsync(() => { class MockNgbModalRef { result = Promise.resolve({ dimensions: { height: 50, width: 50 }, openInUploadMode: true, newThumbnailDataUrl: 'data:image/png;base64,xyz', newBgColor: '#newcol' }); componentInstance = { bgColor: null, allowedBgColors: null, aspectRatio: null, dimensions: null, previewDescription: null, previewDescriptionBgColor: null, previewFooter: null, previewTitle: null, uploadedImage: null, uploadedImageMimeType: null, tempBgColor: null, }; } let ngbModalRef = new MockNgbModalRef(); // Set useLocalStorage as false to trigger fetching. component.useLocalStorage = false; component.disabled = false; component.bgColor = '#ff9933'; let promise = of({ filename: 'filename' }); spyOn(ngbModal, 'open').and.returnValue( ngbModalRef as NgbModalRef); spyOn(imageUploadHelperService, 'generateImageFilename').and.returnValue( 'image_file_name.svg'); spyOn(imageUploadHelperService, 'convertImageDataToImageFile') .and.returnValue(new File([''], 'filename', {type: 'image/jpeg'})); spyOn(assetsBackendApiService, 'postThumbnailFile') .and.returnValue(promise); spyOn(promise.toPromise(), 'then').and.resolveTo({filename: 'filename'}); const updateFilenameSpy = spyOn(component.updateFilename, 'emit'); const updateBgColorSpy = spyOn(component.updateBgColor, 'emit'); expect(component.tempImageName).toBe(undefined); expect(component.uploadedImage).toBe(undefined); expect(component.thumbnailIsLoading).toBe(true); component.showEditThumbnailModal(); tick(); expect(ngbModal.open).toHaveBeenCalledWith( EditThumbnailModalComponent, {backdrop: 'static'}); expect(component.tempImageName).toBe('image_file_name.svg'); expect(component.uploadedImage).toBe('data:image/png;base64,xyz'); expect(component.thumbnailIsLoading).toBe(true); expect(updateFilenameSpy).toHaveBeenCalledWith('image_file_name.svg'); expect(updateBgColorSpy).toHaveBeenCalledWith('#newcol'); })); it('should show edit thumbnail modal when user clicks on edit button and' + ' save background color if not opened in upload mode', fakeAsync(() => { // Modal is not opened in upload mode. class MockNgbModalRef { result = Promise.resolve({ dimensions: { height: 50, width: 50 }, openInUploadMode: false, newThumbnailDataUrl: 'data:image/png;base64,xyz', newBgColor: '#newcol' }); componentInstance = { bgColor: null, allowedBgColors: null, aspectRatio: null, dimensions: null, previewDescription: null, previewDescriptionBgColor: null, previewFooter: null, previewTitle: null, uploadedImage: null, uploadedImageMimeType: null, tempBgColor: null, }; } let ngbModalRef = new MockNgbModalRef(); component.useLocalStorage = false; component.disabled = false; component.bgColor = '#ff9933'; spyOn(ngbModal, 'open').and.returnValue( ngbModalRef as NgbModalRef); spyOn(imageUploadHelperService, 'convertImageDataToImageFile') .and.returnValue(new File([''], 'filename', {type: 'image/jpeg'})); const updateFilenameSpy = spyOn(component.updateFilename, 'emit'); const updateBgColorSpy = spyOn(component.updateBgColor, 'emit'); expect(component.thumbnailIsLoading).toBe(true); component.showEditThumbnailModal(); tick(); expect(ngbModal.open).toHaveBeenCalledWith( EditThumbnailModalComponent, {backdrop: 'static'}); expect(component.thumbnailIsLoading).toBe(false); expect(updateFilenameSpy).not.toHaveBeenCalled(); expect(updateBgColorSpy).toHaveBeenCalledWith('#newcol'); })); it('should show edit thumbnail modal when user clicks on edit button and' + ' save uploaded thumbnail to local storage if local storage' + ' is used', fakeAsync(() => { class MockNgbModalRef { result = Promise.resolve({ dimensions: { height: 50, width: 50 }, openInUploadMode: false, newThumbnailDataUrl: 'data:image/png;base64,xyz', newBgColor: '#newcol' }); componentInstance = { bgColor: null, allowedBgColors: null, aspectRatio: null, dimensions: null, previewDescription: null, previewDescriptionBgColor: null, previewFooter: null, previewTitle: null, uploadedImage: null, uploadedImageMimeType: null, tempBgColor: null, }; } let ngbModalRef = new MockNgbModalRef(); component.useLocalStorage = true; component.disabled = false; component.allowedBgColors = ['#ff9933']; const imageSaveSpy = spyOn(component.imageSave, 'emit'); spyOn(ngbModal, 'open').and.returnValue( ngbModalRef as NgbModalRef); spyOn(imageUploadHelperService, 'generateImageFilename').and.returnValue( 'image_file_name.svg'); spyOn(imageLocalStorageService, 'saveImage'); spyOn(imageLocalStorageService, 'setThumbnailBgColor'); expect(component.thumbnailIsLoading).toBe(true); component.showEditThumbnailModal(); tick(); expect(ngbModal.open).toHaveBeenCalledWith( EditThumbnailModalComponent, {backdrop: 'static'} ); expect(component.thumbnailIsLoading).toBe(false); expect(imageLocalStorageService.saveImage).toHaveBeenCalledWith( 'image_file_name.svg', 'data:image/png;base64,xyz'); expect(imageLocalStorageService.setThumbnailBgColor).toHaveBeenCalledWith( '#newcol'); expect(imageSaveSpy).toHaveBeenCalled(); })); it('should close edit thumbnail modal when cancel button' + ' is clicked', fakeAsync(() => { class MockNgbModalRef { componentInstance = { bgColor: null, allowedBgColors: null, aspectRatio: null, dimensions: null, previewDescription: null, previewDescriptionBgColor: null, previewFooter: null, previewTitle: null, uploadedImage: null, uploadedImageMimeType: null, tempBgColor: null, }; } let ngbModalRef = new MockNgbModalRef(); component.disabled = false; component.allowedBgColors = ['#ff9933']; spyOn(ngbModal, 'open').and.callFake((dlg, opt) => { return ({ componentInstance: ngbModalRef, result: Promise.reject('cancel') } as NgbModalRef); }); component.showEditThumbnailModal(); expect(ngbModal.open).toHaveBeenCalledWith( EditThumbnailModalComponent, {backdrop: 'static'} ); })); it('should raise an alert if an empty file is uploaded', () => { spyOn(alertsService, 'addWarning'); spyOn(imageUploadHelperService, 'convertImageDataToImageFile') .and.returnValue(null); component.saveThumbnailImageData(null, () => {}); expect(alertsService.addWarning).toHaveBeenCalledWith( 'Could not get resampled file.'); }); });
the_stack
import { ObjectMap } from '@0x/types'; import { DataItem, RevertErrorAbi } from 'ethereum-types'; import * as ethUtil from 'ethereumjs-util'; import * as _ from 'lodash'; import { inspect } from 'util'; import * as AbiEncoder from './abi_encoder'; import { BigNumber } from './configured_bignumber'; // tslint:disable: max-classes-per-file no-unnecessary-type-assertion type ArgTypes = | string | BigNumber | number | boolean | RevertError | BigNumber[] | string[] | number[] | boolean[] | Array<BigNumber | number | string>; type ValueMap = ObjectMap<ArgTypes | undefined>; type RevertErrorDecoder = (hex: string) => ValueMap; interface RevertErrorType { new (): RevertError; } interface RevertErrorRegistryItem { type: RevertErrorType; decoder: RevertErrorDecoder; } /** * Register a RevertError type so that it can be decoded by * `decodeRevertError`. * @param revertClass A class that inherits from RevertError. * @param force Allow overwriting registered types. */ export function registerRevertErrorType(revertClass: RevertErrorType, force: boolean = false): void { RevertError.registerType(revertClass, force); } /** * Decode an ABI encoded revert error. * Throws if the data cannot be decoded as a known RevertError type. * @param bytes The ABI encoded revert error. Either a hex string or a Buffer. * @param coerce Coerce unknown selectors into a `RawRevertError` type. * @return A RevertError object. */ export function decodeBytesAsRevertError(bytes: string | Buffer, coerce: boolean = false): RevertError { return RevertError.decode(bytes, coerce); } /** * Decode a thrown error. * Throws if the data cannot be decoded as a known RevertError type. * @param error Any thrown error. * @param coerce Coerce unknown selectors into a `RawRevertError` type. * @return A RevertError object. */ export function decodeThrownErrorAsRevertError(error: Error, coerce: boolean = false): RevertError { if (error instanceof RevertError) { return error; } return RevertError.decode(getThrownErrorRevertErrorBytes(error), coerce); } /** * Coerce a thrown error into a `RevertError`. Always succeeds. * @param error Any thrown error. * @return A RevertError object. */ export function coerceThrownErrorAsRevertError(error: Error): RevertError { if (error instanceof RevertError) { return error; } try { return decodeThrownErrorAsRevertError(error, true); } catch (err) { if (isGanacheTransactionRevertError(error)) { throw err; } // Handle geth transaction reverts. if (isGethTransactionRevertError(error)) { // Geth transaction reverts are opaque, meaning no useful data is returned, // so we just return an AnyRevertError type. return new AnyRevertError(); } // Coerce plain errors into a StringRevertError. return new StringRevertError(error.message); } } /** * Base type for revert errors. */ export abstract class RevertError extends Error { // Map of types registered via `registerType`. private static readonly _typeRegistry: ObjectMap<RevertErrorRegistryItem> = {}; public readonly abi?: RevertErrorAbi; public readonly values: ValueMap = {}; protected readonly _raw?: string; /** * Decode an ABI encoded revert error. * Throws if the data cannot be decoded as a known RevertError type. * @param bytes The ABI encoded revert error. Either a hex string or a Buffer. * @param coerce Whether to coerce unknown selectors into a `RawRevertError` type. * @return A RevertError object. */ public static decode(bytes: string | Buffer | RevertError, coerce: boolean = false): RevertError { if (bytes instanceof RevertError) { return bytes; } const _bytes = bytes instanceof Buffer ? ethUtil.bufferToHex(bytes) : ethUtil.addHexPrefix(bytes); // tslint:disable-next-line: custom-no-magic-numbers const selector = _bytes.slice(2, 10); if (!(selector in RevertError._typeRegistry)) { if (coerce) { return new RawRevertError(bytes); } throw new Error(`Unknown selector: ${selector}`); } const { type, decoder } = RevertError._typeRegistry[selector]; const instance = new type(); try { Object.assign(instance, { values: decoder(_bytes) }); instance.message = instance.toString(); return instance; } catch (err) { throw new Error( `Bytes ${_bytes} cannot be decoded as a revert error of type ${instance.signature}: ${err.message}`, ); } } /** * Register a RevertError type so that it can be decoded by * `RevertError.decode`. * @param revertClass A class that inherits from RevertError. * @param force Allow overwriting existing registrations. */ public static registerType(revertClass: RevertErrorType, force: boolean = false): void { const instance = new revertClass(); if (!force && instance.selector in RevertError._typeRegistry) { throw new Error(`RevertError type with signature "${instance.signature}" is already registered`); } if (_.isNil(instance.abi)) { throw new Error(`Attempting to register a RevertError class with no ABI`); } RevertError._typeRegistry[instance.selector] = { type: revertClass, decoder: createDecoder(instance.abi), }; } /** * Create a RevertError instance with optional parameter values. * Parameters that are left undefined will not be tested in equality checks. * @param declaration Function-style declaration of the revert (e.g., Error(string message)) * @param values Optional mapping of parameters to values. * @param raw Optional encoded form of the revert error. If supplied, this * instance will be treated as a `RawRevertError`, meaning it can only * match other `RawRevertError` types with the same encoded payload. */ protected constructor(name: string, declaration?: string, values?: ValueMap, raw?: string) { super(createErrorMessage(name, values)); if (declaration !== undefined) { this.abi = declarationToAbi(declaration); if (values !== undefined) { _.assign(this.values, _.cloneDeep(values)); } } this._raw = raw; // Extending Error is tricky; we need to explicitly set the prototype. Object.setPrototypeOf(this, new.target.prototype); } /** * Get the ABI name for this revert. */ get name(): string { if (!_.isNil(this.abi)) { return this.abi.name; } return `<${this.typeName}>`; } /** * Get the class name of this type. */ get typeName(): string { // tslint:disable-next-line: no-string-literal return this.constructor.name; } /** * Get the hex selector for this revert (without leading '0x'). */ get selector(): string { if (!_.isNil(this.abi)) { return toSelector(this.abi); } if (this._isRawType) { // tslint:disable-next-line: custom-no-magic-numbers return (this._raw as string).slice(2, 10); } return ''; } /** * Get the signature for this revert: e.g., 'Error(string)'. */ get signature(): string { if (!_.isNil(this.abi)) { return toSignature(this.abi); } return ''; } /** * Get the ABI arguments for this revert. */ get arguments(): DataItem[] { if (!_.isNil(this.abi)) { return this.abi.arguments || []; } return []; } get [Symbol.toStringTag](): string { return this.toString(); } /** * Compares this instance with another. * Fails if instances are not of the same type. * Only fields/values defined in both instances are compared. * @param other Either another RevertError instance, hex-encoded bytes, or a Buffer of the ABI encoded revert. * @return True if both instances match. */ public equals(other: RevertError | Buffer | string): boolean { let _other = other; if (_other instanceof Buffer) { _other = ethUtil.bufferToHex(_other); } if (typeof _other === 'string') { _other = RevertError.decode(_other); } if (!(_other instanceof RevertError)) { return false; } // If either is of the `AnyRevertError` type, always succeed. if (this._isAnyType || _other._isAnyType) { return true; } // If either are raw types, they must match their raw data. if (this._isRawType || _other._isRawType) { return this._raw === _other._raw; } // Must be of same type. if (this.constructor !== _other.constructor) { return false; } // Must share the same parameter values if defined in both instances. for (const name of Object.keys(this.values)) { const a = this.values[name]; const b = _other.values[name]; if (a === b) { continue; } if (!_.isNil(a) && !_.isNil(b)) { const { type } = this._getArgumentByName(name); if (!checkArgEquality(type, a, b)) { return false; } } } return true; } public encode(): string { if (this._raw !== undefined) { return this._raw; } if (!this._hasAllArgumentValues) { throw new Error(`Instance of ${this.typeName} does not have all its parameter values set.`); } const encoder = createEncoder(this.abi as RevertErrorAbi); return encoder(this.values); } public toString(): string { if (this._isRawType) { return `${this.constructor.name}(${this._raw})`; } const values = _.omitBy(this.values, (v: any) => _.isNil(v)); // tslint:disable-next-line: forin for (const k in values) { const { type: argType } = this._getArgumentByName(k); if (argType === 'bytes') { // Try to decode nested revert errors. try { values[k] = RevertError.decode(values[k] as any); } catch (err) {} // tslint:disable-line:no-empty } } const inner = _.isEmpty(values) ? '' : inspect(values); return `${this.constructor.name}(${inner})`; } private _getArgumentByName(name: string): DataItem { const arg = _.find(this.arguments, (a: DataItem) => a.name === name); if (_.isNil(arg)) { throw new Error(`RevertError ${this.signature} has no argument named ${name}`); } return arg; } private get _isAnyType(): boolean { return _.isNil(this.abi) && _.isNil(this._raw); } private get _isRawType(): boolean { return !_.isNil(this._raw); } private get _hasAllArgumentValues(): boolean { if (_.isNil(this.abi) || _.isNil(this.abi.arguments)) { return false; } for (const arg of this.abi.arguments) { if (_.isNil(this.values[arg.name])) { return false; } } return true; } } const PARITY_TRANSACTION_REVERT_ERROR_MESSAGE = /^VM execution error/; const GANACHE_TRANSACTION_REVERT_ERROR_MESSAGE = /^VM Exception while processing transaction: revert/; const GETH_TRANSACTION_REVERT_ERROR_MESSAGE = /always failing transaction$/; interface GanacheTransactionRevertResult { error: 'revert'; program_counter: number; return?: string; reason?: string; } interface GanacheTransactionRevertError extends Error { results: { [hash: string]: GanacheTransactionRevertResult }; hashes: string[]; } interface ParityTransactionRevertError extends Error { code: number; data: string; message: string; } /** * Try to extract the ecnoded revert error bytes from a thrown `Error`. */ export function getThrownErrorRevertErrorBytes( error: Error | GanacheTransactionRevertError | ParityTransactionRevertError, ): string { // Handle ganache transaction reverts. if (isGanacheTransactionRevertError(error)) { // Grab the first result attached. const result = error.results[error.hashes[0]]; // If a reason is provided, just wrap it in a StringRevertError if (result.reason !== undefined) { return new StringRevertError(result.reason).encode(); } if (result.return !== undefined && result.return !== '0x') { return result.return; } } else if (isParityTransactionRevertError(error)) { // Parity returns { data: 'Reverted 0xa6bcde47...', ... } const { data } = error; const hexDataIndex = data.indexOf('0x'); if (hexDataIndex !== -1) { return data.slice(hexDataIndex); } } else { // Handle geth transaction reverts. if (isGethTransactionRevertError(error)) { // Geth transaction reverts are opaque, meaning no useful data is returned, // so we do nothing. } } throw new Error(`Cannot decode thrown Error "${error.message}" as a RevertError`); } function isParityTransactionRevertError( error: Error | ParityTransactionRevertError, ): error is ParityTransactionRevertError { if (PARITY_TRANSACTION_REVERT_ERROR_MESSAGE.test(error.message) && 'code' in error && 'data' in error) { return true; } return false; } function isGanacheTransactionRevertError( error: Error | GanacheTransactionRevertError, ): error is GanacheTransactionRevertError { if (GANACHE_TRANSACTION_REVERT_ERROR_MESSAGE.test(error.message) && 'hashes' in error && 'results' in error) { return true; } return false; } function isGethTransactionRevertError(error: Error | GanacheTransactionRevertError): boolean { return GETH_TRANSACTION_REVERT_ERROR_MESSAGE.test(error.message); } /** * RevertError type for standard string reverts. */ export class StringRevertError extends RevertError { constructor(message?: string) { super('StringRevertError', 'Error(string message)', { message }); } } /** * Special RevertError type that matches with any other RevertError instance. */ export class AnyRevertError extends RevertError { constructor() { super('AnyRevertError'); } } /** * Special RevertError type that is not decoded. */ export class RawRevertError extends RevertError { constructor(encoded: string | Buffer) { super( 'RawRevertError', undefined, undefined, typeof encoded === 'string' ? encoded : ethUtil.bufferToHex(encoded), ); } } /** * Create an error message for a RevertError. * @param name The name of the RevertError. * @param values The values for the RevertError. */ function createErrorMessage(name: string, values?: ValueMap): string { if (values === undefined) { return `${name}()`; } const _values = _.omitBy(values, (v: any) => _.isNil(v)); const inner = _.isEmpty(_values) ? '' : inspect(_values); return `${name}(${inner})`; } /** * Parse a solidity function declaration into a RevertErrorAbi object. * @param declaration Function declaration (e.g., 'foo(uint256 bar)'). * @return A RevertErrorAbi object. */ function declarationToAbi(declaration: string): RevertErrorAbi { let m = /^\s*([_a-z][a-z0-9_]*)\((.*)\)\s*$/i.exec(declaration); if (!m) { throw new Error(`Invalid Revert Error signature: "${declaration}"`); } const [name, args] = m.slice(1); const argList: string[] = _.filter(args.split(',')); const argData: DataItem[] = _.map(argList, (a: string) => { // Match a function parameter in the format 'TYPE ID', where 'TYPE' may be // an array type. m = /^\s*(([_a-z][a-z0-9_]*)(\[\d*\])*)\s+([_a-z][a-z0-9_]*)\s*$/i.exec(a); if (!m) { throw new Error(`Invalid Revert Error signature: "${declaration}"`); } // tslint:disable: custom-no-magic-numbers return { name: m[4], type: m[1], }; // tslint:enable: custom-no-magic-numbers }); const r: RevertErrorAbi = { type: 'error', name, arguments: _.isEmpty(argData) ? [] : argData, }; return r; } function checkArgEquality(type: string, lhs: ArgTypes, rhs: ArgTypes): boolean { // Try to compare as decoded revert errors first. try { return RevertError.decode(lhs as any).equals(RevertError.decode(rhs as any)); } catch (err) { // no-op } if (type === 'address') { return normalizeAddress(lhs as string) === normalizeAddress(rhs as string); } else if (type === 'bytes' || /^bytes(\d+)$/.test(type)) { return normalizeBytes(lhs as string) === normalizeBytes(rhs as string); } else if (type === 'string') { return lhs === rhs; } else if (/\[\d*\]$/.test(type)) { // An array type. // tslint:disable: custom-no-magic-numbers // Arguments must be arrays and have the same dimensions. if ((lhs as any[]).length !== (rhs as any[]).length) { return false; } const m = /^(.+)\[(\d*)\]$/.exec(type) as string[]; const baseType = m[1]; const isFixedLength = m[2].length !== 0; if (isFixedLength) { const length = parseInt(m[2], 10); // Fixed-size arrays have a fixed dimension. if ((lhs as any[]).length !== length) { return false; } } // Recurse into sub-elements. for (const [slhs, srhs] of _.zip(lhs as any[], rhs as any[])) { if (!checkArgEquality(baseType, slhs, srhs)) { return false; } } return true; // tslint:enable: no-magic-numbers } // tslint:disable-next-line return new BigNumber((lhs as any) || 0).eq(rhs as any); } function normalizeAddress(addr: string): string { const ADDRESS_SIZE = 20; return ethUtil.bufferToHex(ethUtil.setLengthLeft(ethUtil.toBuffer(ethUtil.addHexPrefix(addr)), ADDRESS_SIZE)); } function normalizeBytes(bytes: string): string { return ethUtil.addHexPrefix(bytes).toLowerCase(); } function createEncoder(abi: RevertErrorAbi): (values: ObjectMap<any>) => string { const encoder = AbiEncoder.createMethod(abi.name, abi.arguments || []); return (values: ObjectMap<any>): string => { const valuesArray = _.map(abi.arguments, (arg: DataItem) => values[arg.name]); return encoder.encode(valuesArray); }; } function createDecoder(abi: RevertErrorAbi): (hex: string) => ValueMap { const encoder = AbiEncoder.createMethod(abi.name, abi.arguments || []); return (hex: string): ValueMap => { return encoder.decode(hex) as ValueMap; }; } function toSignature(abi: RevertErrorAbi): string { const argTypes = _.map(abi.arguments, (a: DataItem) => a.type); const args = argTypes.join(','); return `${abi.name}(${args})`; } function toSelector(abi: RevertErrorAbi): string { return ( ethUtil .keccak256(Buffer.from(toSignature(abi))) // tslint:disable-next-line: custom-no-magic-numbers .slice(0, 4) .toString('hex') ); } // Register StringRevertError RevertError.registerType(StringRevertError); // tslint:disable-next-line max-file-line-count
the_stack
import express, { NextFunction, Request, Response } from 'express'; import { ConduitCommons, ConduitRoute } from '@conduitplatform/commons'; import { GraphQlParser, ParseResult } from './GraphQlParser'; import { findPopulation } from './utils/TypeUtils'; import { GraphQLJSONObject } from 'graphql-type-json'; import { GraphQLScalarType, Kind } from 'graphql'; import 'apollo-cache-control'; import { createHashKey, extractCachingGql } from '../cache.utils'; import moment from 'moment'; import { processParams } from './utils/SimpleTypeParamUtils'; import { ConduitRouter } from '../Router'; import { errorHandler } from './utils/Request.utils'; import { ConduitModel, ConduitRouteActions, ConduitRouteOption, ConduitRouteOptions, Indexable, TYPE, } from '@conduitplatform/grpc-sdk'; const { parseResolveInfo } = require('graphql-parse-resolve-info'); const { ApolloServer } = require('apollo-server-express'); const cookiePlugin = require('./utils/cookie.plugin'); export class GraphQLController extends ConduitRouter { typeDefs!: string; types!: string; queries!: string; mutations!: string; resolvers: any; private _apollo?: express.Router; private _relationTypes: string[] = []; private _apolloRefreshTimeout: NodeJS.Timeout | null = null; private _parser: GraphQlParser; constructor(commons: ConduitCommons) { super(commons); this.initialize(); this._parser = new GraphQlParser(); } refreshGQLServer() { const server = new ApolloServer({ typeDefs: this.typeDefs, resolvers: this.resolvers, plugins: [cookiePlugin], context: ({ req, res }: Indexable) => { const context = req.conduit || {}; let headers = req.headers; return { context, headers, setCookie: [], removeCookie: [], res }; }, }); this._apollo = server.getMiddleware(); } generateType(name: string, fields: ConduitModel | ConduitRouteOption | string) { if (this.typeDefs.includes('type ' + name + ' ')) { return; } const self = this; let parseResult: ParseResult = this._parser.extractTypes(name, fields, false); this.types += parseResult.typeString; parseResult.relationTypes.forEach((type: string) => { if (self._relationTypes.indexOf(type) === -1) { self._relationTypes.push(type); } }); if ( this.types.includes('JSONObject') && this.types.indexOf('scalar JSONObject') === -1 ) { this.types += '\n scalar JSONObject \n'; this.resolvers['JSONObject'] = GraphQLJSONObject; } for (let resolveGroup in parseResult.parentResolve) { if (!parseResult.parentResolve.hasOwnProperty(resolveGroup)) continue; if (!self.resolvers[resolveGroup]) { self.resolvers[resolveGroup] = {}; } for (let resolverFunction in parseResult.parentResolve[resolveGroup]) { if (!parseResult.parentResolve[resolveGroup].hasOwnProperty(resolverFunction)) continue; if (!self.resolvers[resolveGroup][resolverFunction]) { self.resolvers[resolveGroup][resolverFunction] = parseResult.parentResolve[resolveGroup][resolverFunction]; } } } } generateAction(input: ConduitRouteOptions, returnType: string) { // todo refine this, simply replacing : with empty is too dumb let cleanPath: string = input.path; while (cleanPath.indexOf('-') !== -1) { cleanPath = cleanPath.replace('-', ''); } while (cleanPath.indexOf(':') !== -1) { cleanPath = cleanPath.replace(':', ''); } let pathName: string[] = cleanPath.split('/'); if ( pathName[pathName.length - 1].length === 0 || pathName[pathName.length - 1] === '' ) { pathName = pathName.slice(0, pathName.length - 1); } else { pathName = pathName.slice(0, pathName.length); } let uniqueName: string = ''; pathName.forEach(r => { uniqueName += r.slice(0, 1).toUpperCase() + r.slice(1); }); let name = input.name ? input.name : input.action.toLowerCase() + uniqueName; let params = ''; if (input.bodyParams || input.queryParams || input.urlParams) { if (input.bodyParams) { let parseResult: ParseResult = this._parser.extractTypes( name + 'Request', input.bodyParams, true, ); this.types += parseResult.typeString; params += (params.length > 1 ? ',' : '') + 'params' + ':'; params += name + 'Request'; } if (input.queryParams) { params = processParams(input.queryParams, params); } if (input.urlParams) { params = processParams(input.urlParams, params); } params = '(' + params + ')'; } let description = ''; if (input.description) { description = `""" ${input.description} """ `; } let finalName = description + name + params + ':' + returnType; if (input.action === ConduitRouteActions.GET && !this.queries.includes(finalName)) { this.queries += ' ' + finalName; } else if ( input.action !== ConduitRouteActions.GET && !this.mutations.includes(finalName) ) { this.mutations += ' ' + finalName; } return name; } generateQuerySchema() { if (this.queries.length > 1) { return 'type Query { ' + this.queries + ' }'; } return ''; } generateMutationSchema() { if (this.mutations.length > 1) { return 'type Mutation { ' + this.mutations + ' }'; } else { return ''; } } generateSchema() { this.typeDefs = this.types + ' ' + this.generateQuerySchema() + ' ' + this.generateMutationSchema(); } shouldPopulate(args: Indexable, info: Indexable) { let resolveInfo = parseResolveInfo(info); let objs = resolveInfo.fieldsByTypeName; objs = objs[Object.keys(objs)[0]]; let result = findPopulation(objs, this._relationTypes); if (result) { args['populate'] = result; } return args; } registerConduitRoute(route: ConduitRoute) { const key = `${route.input.action}-${route.input.path}`; const registered = this._registeredRoutes.has(key); this._registeredRoutes.set(key, route); if (!registered) { this.addConduitRoute(route); } } protected _refreshRouter() { this.initialize(); this._registeredRoutes.forEach(route => { // we should probably implement some kind of caching for this // so it does not recalculate the types for the routes that have not changed // but it needs to be done carefully this.addConduitRoute(route); }); this.scheduleApolloRefresh(); } private initialize() { this.resolvers = { Date: new GraphQLScalarType({ name: 'Date', description: 'Date custom scalar type', parseValue(value) { return new Date(value); // value from the client }, serialize(value) { return value; // value sent to the client }, parseLiteral(ast) { if (ast.kind === Kind.INT) { return new Date(ast.value); // ast value is always in string format } else if (ast.kind === Kind.STRING) { return moment(ast.value).toDate(); } return null; }, }), Number: new GraphQLScalarType({ name: 'Number', description: 'Number custom scalar type, is either int or float', parseValue(value) { // maybe wrong if (typeof value === 'string') { if (Number.isInteger(value)) { return Number.parseInt(value); } else if (!Number.isNaN(value)) { return Number.parseFloat(value); } } else { return value; } }, serialize(value) { if (typeof value === 'string') { if (Number.isInteger(value)) { return Number.parseInt(value); } else if (!Number.isNaN(value)) { return Number.parseFloat(value); } } else { return value; } }, parseLiteral(ast) { if (ast.kind === Kind.INT || ast.kind === Kind.FLOAT) { return ast.value; } else if (ast.kind == Kind.STRING) { if (Number.isInteger(ast.value)) { return Number.parseInt(ast.value); } else if (!Number.isNaN(ast.value)) { return Number.parseFloat(ast.value); } } return null; }, }), }; this.typeDefs = ` `; this.types = 'scalar Date\nscalar Number\n'; this.queries = ''; this.mutations = ''; const self = this; this._expressRouter.use('/', (req: Request, res: Response, next: NextFunction) => { if (self._apollo) { self._apollo(req, res, next); } else { next(); } }); } private extractResult(returnTypeFields: String, result: Indexable | string) { switch (returnTypeFields) { case TYPE.JSON: return JSON.parse(result as string); default: return result; } } private constructQuery(actionName: string, route: ConduitRoute) { if (!this.resolvers['Query']) { this.resolvers['Query'] = {}; } const self = this; this.resolvers['Query'][actionName] = ( parent: Indexable, args: Indexable, context: any, info: Indexable, ) => { let { caching, cacheAge, scope } = extractCachingGql( route, context.headers['Cache-Control'], ); if (caching) { info.cacheControl.setCacheHint({ maxAge: cacheAge, scope }); } args = self.shouldPopulate(args, info); context.path = route.input.path; let hashKey: string; return self .checkMiddlewares(context, route.input.middlewares) .then(r => { Object.assign(context.context, r); let params = Object.assign(args, args.params); delete params.params; if (caching) { hashKey = createHashKey(context.path, context.context, params); } if (caching) { return self .findInCache(hashKey) .then((r: string | null) => { if (r) { return { fromCache: true, data: JSON.parse(r) }; } else { return route.executeRequest.bind(route)({ ...context, params }); } }) .catch(() => { return route.executeRequest.bind(route)({ ...context, params }); }); } else { return route.executeRequest.bind(route)({ ...context, params }); } }) .then(r => { let result; if (r.fromCache) { return r.data; } else { result = r.result ? r.result : r; } if (r.result && !(typeof route.returnTypeFields === 'string')) { result = JSON.parse(result); } else { result = { result: self.extractResult(route.returnTypeFields as string, result), }; } if (caching) { this.storeInCache(hashKey, result, cacheAge!); } return result; }) .catch(errorHandler); }; } private constructMutation(actionName: string, route: ConduitRoute) { if (!this.resolvers['Mutation']) { this.resolvers['Mutation'] = {}; } const self = this; this.resolvers['Mutation'][actionName] = ( parent: Indexable, args: Indexable, context: any, info: Indexable, ) => { args = self.shouldPopulate(args, info); context.path = route.input.path; return self .checkMiddlewares(context, route.input.middlewares) .then(r => { Object.assign(context.context, r); let params = Object.assign(args, args.params); delete params.params; return route.executeRequest.bind(route)({ ...context, params: args }); }) .then(r => { let result = r.result ? r.result : r; if (r.setCookies) { context.setCookie = r.setCookies; } if (r.removeCookies) { context.removeCookie = r.removeCookies; } if (r.result && !(typeof route.returnTypeFields === 'string')) { result = JSON.parse(result); } else { result = { result: self.extractResult(route.returnTypeFields as string, result), }; } return result; }) .catch(errorHandler); }; } private addConduitRoute(route: ConduitRoute) { this.generateType(route.returnTypeName, route.returnTypeFields); let actionName = this.generateAction(route.input, route.returnTypeName); this.generateSchema(); if (route.input.action === ConduitRouteActions.GET) { this.constructQuery(actionName, route); } else { this.constructMutation(actionName, route); } } private scheduleApolloRefresh() { if (this._apolloRefreshTimeout) { clearTimeout(this._apolloRefreshTimeout); this._apolloRefreshTimeout = null; } this._apolloRefreshTimeout = setTimeout(() => { try { this.refreshGQLServer(); } catch (err) { console.error(err); } this._apolloRefreshTimeout = null; }, 3000); } }
the_stack
import { EOL } from 'os' import { Message, RECORD_ACTION, PRESENCE_ACTION, EVENT_ACTION, RPC_ACTION, RecordData, TOPIC, RecordWriteMessage } from '../../../constants' import { PermissionCallback, ValveConfig, SocketWrapper, DeepstreamConfig, DeepstreamServices, NamespacedLogger, EVENT } from '@deepstream/types' import { recordRequest } from '../../../handlers/record/record-request' import RecordHandler from '../../../handlers/record/record-handler' import { setValue } from '../../../utils/json-path' const OPEN = 'open' const LOADING = 'loading' const ERROR = 'error' const UNDEFINED = 'undefined' const STRING = 'string' interface RuleApplicationParams { userId: string serverData: any path: string ruleSpecification: any message: Message action: RECORD_ACTION | PRESENCE_ACTION | EVENT_ACTION | RPC_ACTION regexp: RegExp rule: any name: string permissionOptions: ValveConfig logger: NamespacedLogger recordHandler: RecordHandler socketWrapper: SocketWrapper config: DeepstreamConfig services: DeepstreamServices, callback: PermissionCallback, passItOn: any, } export default class RuleApplication { private isDestroyed: boolean = false private runScheduled: boolean = false private pathVars: any private user: any private readonly maxIterationCount: number private readonly recordsData = new Map<string, RecordData | string>() private iterations: number /** * This class handles the evaluation of a single rule. It creates * the required variables, injects them into the rule function and * runs the function recoursively until either all cross-references, * references to old or new data is loaded, it errors or the maxIterationCount * limit is exceeded */ constructor (private params: RuleApplicationParams) { this.maxIterationCount = this.params.permissionOptions.maxRuleIterations this.run = this.run.bind(this) this.crossReference = this.crossReference.bind(this) this.createNewRecordRequest = this.createNewRecordRequest.bind(this) this.pathVars = this.getPathVars() this.user = this.getUser() this.iterations = 0 this.run() } /** * Runs the rule function. This method is initially called when this class * is constructed and recoursively from thereon whenever the loading of a record * is completed */ private run (): void { this.runScheduled = false this.iterations++ if (this.isDestroyed) { return } if (this.iterations > this.maxIterationCount) { this.onRuleError('Exceeded max iteration count') return } if (this.isDestroyed) { return } const args = this.getArguments() let result try { result = this.params.rule.fn.apply({}, args) } catch (error) { if (this.isReady()) { this.onRuleError(error) return } } if (this.isReady()) { this.params.callback(this.params.socketWrapper, this.params.message, this.params.passItOn, null, result) this.destroy() } } /** * Callback if a rule has irrecoverably errored. Rule errors due to unresolved * crossreferences are allowed as long as a loading step is in progress */ private onRuleError (error: string): void { if (this.isDestroyed === true) { return } const errorMsg = `error when executing ${this.params.rule.fn.toString()}${EOL}for ${this.params.name}: ${error.toString()}` this.params.logger.warn(EVENT_ACTION[EVENT_ACTION.MESSAGE_PERMISSION_ERROR], errorMsg, { recordName: this.params.name }) this.params.callback(this.params.socketWrapper, this.params.message, this.params.passItOn, EVENT_ACTION.MESSAGE_PERMISSION_ERROR, false) this.destroy() } /** * Called either asynchronously when data is successfully retrieved from the * cache or synchronously if its already present */ private onLoadComplete (recordName: string, version: number, data: any): void { this.recordsData.set(recordName, data) if (this.isReady()) { this.runScheduled = true process.nextTick(this.run) } } /** * Called whenever a storage or cache retrieval fails. Any kind of error during the * permission process is treated as a denied permission */ private onLoadError (event: any, errorMessage: string, recordName: string, socket: SocketWrapper | null) { this.recordsData.set(recordName, ERROR) const errorMsg = `failed to load record ${this.params.name} for permissioning:${errorMessage}` this.params.logger.error(RECORD_ACTION[RECORD_ACTION.RECORD_LOAD_ERROR], errorMsg, { recordName, socketWrapper: socket }) this.params.callback(this.params.socketWrapper, this.params.message, this.params.passItOn, RECORD_ACTION.RECORD_LOAD_ERROR, false) this.destroy() } /** * Destroys this class and nulls down values to avoid * memory leaks */ private destroy () { this.params.recordHandler.removeRecordRequest(this.params.name) this.isDestroyed = true this.runScheduled = false this.recordsData.clear() // this.params = null // this.crossReference = null // this.currentData = null this.pathVars = null this.user = null } /** * If data.someValue is used in the rule, this method retrieves or loads the * current data. This can mean different things, depending on the type of message * * the data arguments is supported for record read & write, * event publish and rpc request * * for event publish, record update and rpc request, the data is already provided * in the message and doesn't need to be loaded * * for record.patch, only a delta is part of the message. For the full data, the current value * is loaded and the patch applied on top */ private getCurrentData (): any { if (this.params.rule.hasData === false) { return null } const msg = this.params.message let result: any = false if ( (msg.topic === TOPIC.RPC) || (msg.topic === TOPIC.EVENT && msg.data) || (msg.topic === TOPIC.RECORD && msg.action === RECORD_ACTION.UPDATE) ) { result = this.params.socketWrapper.parseData(msg) if (result instanceof Error) { this.onRuleError(`error when converting message data ${result.toString()}`) } else { return msg.parsedData } } else if (msg.topic === TOPIC.RECORD && msg.action === RECORD_ACTION.PATCH) { result = this.getRecordPatchData(msg as RecordWriteMessage) if (result instanceof Error) { this.onRuleError(`error when converting message data ${result.toString()}`) } else { return result } } } /** * Loads the records current data and applies the patch data onto it * to avoid users having to distuinguish between patches and updates */ private getRecordPatchData (msg: RecordWriteMessage): any { if (!this.recordsData) { return } if (!msg.path) { this.params.logger.error(EVENT.ERROR, `Missing path for record patch ${msg.name}`, { message: msg }) return } const currentData = this.recordsData.get(this.params.name) const parseResult = this.params.socketWrapper.parseData(msg) let data if (parseResult instanceof Error) { return parseResult } if (currentData === null) { return new Error(`Tried to apply patch to non-existant record ${msg.name}`) } if (typeof currentData !== UNDEFINED && currentData !== LOADING) { data = JSON.parse(JSON.stringify(currentData)) setValue(data, msg.path, msg.parsedData) return data } this.loadRecord(this.params.name) } /** * Returns or loads the record's previous value. Only supported for record * write and read operations * * If getData encounters an error, the rule application might already be destroyed * at this point */ private getOldData (): any { if (this.isDestroyed === true || this.params.rule.hasOldData === false) { return } if (this.recordsData.has(this.params.name)) { return this.recordsData.get(this.params.name) } this.loadRecord(this.params.name) } /** * Compile the list of arguments that will be injected * into the permission function. This method is called * everytime the permission is run. This allows it to merge * patches and update the now timestamp */ private getArguments (): any[] { return [ this.crossReference, this.user, this.getCurrentData(), this.getOldData(), Date.now(), this.params ? this.params.action : null, this.params ? this.params.name : null ].concat(this.pathVars) } /** * Returns the data for the user variable. This is only done once * per rule as the user is not expected to change */ private getUser (): any { return { isAuthenticated: this.params.userId !== OPEN, id: this.params.userId, data: this.params.serverData, } } /** * Applies the compiled regexp for the path and extracts * the variables that will be made available as $variableName * within the rule * * This is only done once per rule as the path is not expected * to change */ private getPathVars (): string[] { if (!this.params.name) { return [] } const matches = this.params.name.match(this.params.regexp) if (matches) { return matches.slice(1) } else { return [] } } /** * Returns true if all loading operations that are in progress have finished * and no run has been scheduled yet */ private isReady (): boolean { let isLoading = false // @ts-ignore for (const [key, value] of this.recordsData) { if (value === LOADING) { isLoading = true break } } return isLoading === false && this.runScheduled === false } /** * Loads a record with a given name. This will either result in * a onLoadComplete or onLoadError call. This method should only * be called if the record is not already being loaded or present, * but I'll leave the additional safeguards in until absolutely sure. */ private loadRecord (recordName: string): void { const recordData = this.recordsData.get(recordName) if (recordData === LOADING) { return } if (typeof recordData !== UNDEFINED) { this.onLoadComplete(recordName, -1, recordData) return } this.recordsData.set(recordName, LOADING) this.params.recordHandler.runWhenRecordStable( recordName, this.createNewRecordRequest, ) } /** * Load the record data from the cache for permissioning. This method should be * called once the record is stable – meaning there are no remaining writes * waiting to be written to the cache. */ private createNewRecordRequest (recordName: string): void { recordRequest( recordName, this.params.config, this.params.services, null, this.onLoadComplete, this.onLoadError, this ) } /** * This method is passed to the rule function as _ to allow crossReferencing * of other records. Cross-references can be nested, leading to this method * being recoursively called until the either all cross references are loaded * or the rule has finally failed */ private crossReference (recordName: string): any | null { const type = typeof recordName const recordData = this.recordsData.get(recordName) if (type !== UNDEFINED && type !== STRING) { this.onRuleError(`crossreference got unsupported type ${type}`) } else if (type === UNDEFINED || recordName.indexOf(UNDEFINED) !== -1) { return } else if (recordData === LOADING) { return } else if (recordData === null) { return null } else if (typeof recordData === UNDEFINED) { this.loadRecord(recordName) } else { return recordData } } }
the_stack
import Page = require('../../../../base/Page'); import Response = require('../../../../http/response'); import V1 = require('../../V1'); import { SerializableClass } from '../../../../interfaces'; type ParticipantConversationState = 'inactive'|'active'|'closed'; /** * Initialize the ParticipantConversationList * * @param version - Version of the resource * @param chatServiceSid - The unique ID of the Conversation Service this conversation belongs to. */ declare function ParticipantConversationList(version: V1, chatServiceSid: string): ParticipantConversationListInstance; interface ParticipantConversationListInstance { /** * Streams ParticipantConversationInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Function to process each record */ each(callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; /** * Streams ParticipantConversationInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Function to process each record */ each(opts?: ParticipantConversationListInstanceEachOptions, callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void): void; /** * Retrieve a single target page of ParticipantConversationInstance records from * the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ getPage(callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise<ParticipantConversationPage>; /** * Retrieve a single target page of ParticipantConversationInstance records from * the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param targetUrl - API-generated URL for the requested results page * @param callback - Callback to handle list of records */ getPage(targetUrl?: string, callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise<ParticipantConversationPage>; /** * Lists ParticipantConversationInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ list(callback?: (error: Error | null, items: ParticipantConversationInstance[]) => any): Promise<ParticipantConversationInstance[]>; /** * Lists ParticipantConversationInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ list(opts?: ParticipantConversationListInstanceOptions, callback?: (error: Error | null, items: ParticipantConversationInstance[]) => any): Promise<ParticipantConversationInstance[]>; /** * Retrieve a single page of ParticipantConversationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ page(callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise<ParticipantConversationPage>; /** * Retrieve a single page of ParticipantConversationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ page(opts?: ParticipantConversationListInstancePageOptions, callback?: (error: Error | null, items: ParticipantConversationPage) => any): Promise<ParticipantConversationPage>; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to each * * @property address - A unique string identifier for the conversation participant who's not a Conversation User. * @property callback - * Function to process each record. If this and a positional * callback are passed, this one will be used * @property done - Function to be called upon completion of streaming * @property identity - A unique string identifier for the conversation participant as Conversation User. * @property limit - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) */ interface ParticipantConversationListInstanceEachOptions { address?: string; callback?: (item: ParticipantConversationInstance, done: (err?: Error) => void) => void; done?: Function; identity?: string; limit?: number; pageSize?: number; } /** * Options to pass to list * * @property address - A unique string identifier for the conversation participant who's not a Conversation User. * @property identity - A unique string identifier for the conversation participant as Conversation User. * @property limit - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) */ interface ParticipantConversationListInstanceOptions { address?: string; identity?: string; limit?: number; pageSize?: number; } /** * Options to pass to page * * @property address - A unique string identifier for the conversation participant who's not a Conversation User. * @property identity - A unique string identifier for the conversation participant as Conversation User. * @property pageNumber - Page Number, this value is simply for client state * @property pageSize - Number of records to return, defaults to 50 * @property pageToken - PageToken provided by the API */ interface ParticipantConversationListInstancePageOptions { address?: string; identity?: string; pageNumber?: number; pageSize?: number; pageToken?: string; } interface ParticipantConversationPayload extends ParticipantConversationResource, Page.TwilioResponsePayload { } interface ParticipantConversationResource { account_sid: string; chat_service_sid: string; conversation_attributes: string; conversation_created_by: string; conversation_date_created: Date; conversation_date_updated: Date; conversation_friendly_name: string; conversation_sid: string; conversation_state: ParticipantConversationState; conversation_timers: object; conversation_unique_name: string; links: string; participant_identity: string; participant_messaging_binding: object; participant_sid: string; participant_user_sid: string; } interface ParticipantConversationSolution { chatServiceSid?: string; } declare class ParticipantConversationInstance extends SerializableClass { /** * Initialize the ParticipantConversationContext * * @param version - Version of the resource * @param payload - The instance payload * @param chatServiceSid - The unique ID of the Conversation Service this conversation belongs to. */ constructor(version: V1, payload: ParticipantConversationPayload, chatServiceSid: string); accountSid: string; chatServiceSid: string; conversationAttributes: string; conversationCreatedBy: string; conversationDateCreated: Date; conversationDateUpdated: Date; conversationFriendlyName: string; conversationSid: string; conversationState: ParticipantConversationState; conversationTimers: any; conversationUniqueName: string; links: string; participantIdentity: string; participantMessagingBinding: any; participantSid: string; participantUserSid: string; /** * Provide a user-friendly representation */ toJSON(): any; } declare class ParticipantConversationPage extends Page<V1, ParticipantConversationPayload, ParticipantConversationResource, ParticipantConversationInstance> { /** * Initialize the ParticipantConversationPage * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: V1, response: Response<string>, solution: ParticipantConversationSolution); /** * Build an instance of ParticipantConversationInstance * * @param payload - Payload response from the API */ getInstance(payload: ParticipantConversationPayload): ParticipantConversationInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { ParticipantConversationInstance, ParticipantConversationList, ParticipantConversationListInstance, ParticipantConversationListInstanceEachOptions, ParticipantConversationListInstanceOptions, ParticipantConversationListInstancePageOptions, ParticipantConversationPage, ParticipantConversationPayload, ParticipantConversationResource, ParticipantConversationSolution, ParticipantConversationState }
the_stack
import { LibraryInfo, MinecraftFolder, MinecraftLocation, Version as VersionJson } from "@xmcl/core"; import { parse as parseForge } from "@xmcl/forge-site-parser"; import { Task, task } from "@xmcl/task"; import { filterEntries, open, openEntryReadStream, readEntry } from "@xmcl/unzip"; import { createWriteStream } from "fs"; import { dirname, join, posix, sep } from "path"; import { Entry, ZipFile } from "yauzl"; import { DownloadTask } from "./downloadTask"; import { withAgents } from "./http/agents"; import { getAndParseIfUpdate, Timestamped } from "./http/fetch"; import { joinUrl } from "./http/utils"; import { ZipValidator } from "./http/validator"; import { LibraryOptions, resolveLibraryDownloadUrls } from "./minecraft"; import { installByProfileTask, InstallProfile, InstallProfileOption } from "./profile"; import { ensureFile, InstallOptions as InstallOptionsBase, normalizeArray, pipeline, writeFile } from "./utils"; export interface ForgeVersionList extends Timestamped { mcversion: string; versions: ForgeVersion[]; } /** * The forge version metadata to download a forge */ export interface ForgeVersion { /** * The installer info */ installer: { md5: string; sha1: string; /** * The url path to concat with forge maven */ path: string; }; universal: { md5: string; sha1: string; /** * The url path to concat with forge maven */ path: string; }; /** * The minecraft version */ mcversion: string; /** * The forge version (without minecraft version) */ version: string; type: "buggy" | "recommended" | "common" | "latest"; } /** * All the useful entries in forge installer jar */ export interface ForgeInstallerEntries { /** * maven/net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}.jar */ forgeJar?: Entry /** * maven/net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}-universal.jar */ forgeUniversalJar?: Entry /** * data/client.lzma */ clientLzma?: Entry /** * data/server.lzma */ serverLzma?: Entry /** * install_profile.json */ installProfileJson?: Entry /** * version.json */ versionJson?: Entry /** * forge-${forgeVersion}-universal.jar */ legacyUniversalJar?: Entry /** * data/run.sh */ runSh?: Entry /** * data/run.bat */ runBat?: Entry /** * data/unix_args.txt */ unixArgs?: Entry /** * data/user_jvm_args.txt */ userJvmArgs?: Entry /** * data/win_args.txt */ winArgs?: Entry } export type ForgeInstallerEntriesPattern = ForgeInstallerEntries & Required<Pick<ForgeInstallerEntries, "versionJson" | "installProfileJson">>; export type ForgeLegacyInstallerEntriesPattern = Required<Pick<ForgeInstallerEntries, "installProfileJson" | "legacyUniversalJar">>; type RequiredVersion = { /** * The installer info. * * If this is not presented, it will genreate from mcversion and forge version. */ installer?: { sha1?: string; /** * The url path to concat with forge maven */ path: string; }; /** * The minecraft version */ mcversion: string; /** * The forge version (without minecraft version) */ version: string; } export const DEFAULT_FORGE_MAVEN = "http://files.minecraftforge.net/maven"; /** * The options to install forge. */ export interface InstallForgeOptions extends LibraryOptions, InstallOptionsBase, InstallProfileOption { } export class DownloadForgeInstallerTask extends DownloadTask { readonly installJarPath: string constructor(forgeVersion: string, installer: RequiredVersion["installer"], minecraft: MinecraftFolder, options: InstallForgeOptions) { const path = installer ? installer.path : `net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}-installer.jar`; const forgeMavenPath = path.replace("/maven", "").replace("maven", ""); const library = VersionJson.resolveLibrary({ name: `net.minecraftforge:forge:${forgeVersion}:installer`, downloads: { artifact: { url: joinUrl(DEFAULT_FORGE_MAVEN, forgeMavenPath), path: `net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}-installer.jar`, size: -1, sha1: installer?.sha1 || "", } } })!; const mavenHost = options.mavenHost ? [...normalizeArray(options.mavenHost), DEFAULT_FORGE_MAVEN] : [DEFAULT_FORGE_MAVEN]; const urls = resolveLibraryDownloadUrls(library, { ...options, mavenHost }); const installJarPath = minecraft.getLibraryByPath(library.path); super({ url: urls, destination: installJarPath, validator: installer?.sha1 ? { hash: installer.sha1, algorithm: "sha1", } : new ZipValidator(), agents: options.agents, segmentPolicy: options.segmentPolicy, retryHandler: options.retryHandler, }); this.installJarPath = installJarPath; this.name = "downloadInstaller"; this.param = { version: forgeVersion }; } } function getLibraryPathWithoutMaven(mc: MinecraftFolder, name: string) { // remove the maven/ prefix return mc.getLibraryByPath(name.substring(name.indexOf("/") + 1)); } function extractEntryTo(zip: ZipFile, e: Entry, dest: string) { return openEntryReadStream(zip, e).then((stream) => pipeline(stream, createWriteStream(dest))); } async function installLegacyForgeFromZip(zip: ZipFile, entries: ForgeLegacyInstallerEntriesPattern, profile: InstallProfile, mc: MinecraftFolder, options: InstallForgeOptions) { const versionJson = profile.versionInfo!; // apply override for inheritsFrom versionJson.id = options.versionId || versionJson.id; versionJson.inheritsFrom = options.inheritsFrom || versionJson.inheritsFrom; const rootPath = mc.getVersionRoot(versionJson.id); const versionJsonPath = join(rootPath, `${versionJson.id}.json`); await ensureFile(versionJsonPath); const library = LibraryInfo.resolve(versionJson.libraries.find((l) => l.name.startsWith("net.minecraftforge:forge"))!); await Promise.all([ writeFile(versionJsonPath, JSON.stringify(versionJson, undefined, 4)), extractEntryTo(zip, entries.legacyUniversalJar, mc.getLibraryByPath(library.path)), ]); return versionJson.id; } /** * Unpack forge installer jar file content to the version library artifact directory. * @param zip The forge jar file * @param entries The entries * @param forgeVersion The expected version of forge * @param profile The forge install profile * @param mc The minecraft location * @returns The installed version id */ async function unpackForgeInstaller(zip: ZipFile, entries: ForgeInstallerEntriesPattern, forgeVersion: string, profile: InstallProfile, mc: MinecraftFolder, jarPath: string, options: InstallForgeOptions) { const versionJson: VersionJson = await readEntry(zip, entries.versionJson).then((b) => b.toString()).then(JSON.parse); // apply override for inheritsFrom versionJson.id = options.versionId || versionJson.id; versionJson.inheritsFrom = options.inheritsFrom || versionJson.inheritsFrom; // resolve all the required paths const rootPath = mc.getVersionRoot(versionJson.id); const versionJsonPath = join(rootPath, `${versionJson.id}.json`); const installJsonPath = join(rootPath, "install_profile.json"); const dataRoot = dirname(jarPath); const unpackData = (entry: Entry) => { promises.push(extractEntryTo(zip, entry, join(dataRoot, entry.fileName.substring("data/".length)))); } await ensureFile(versionJsonPath); const promises: Promise<void>[] = []; if (entries.forgeUniversalJar) { promises.push(extractEntryTo(zip, entries.forgeUniversalJar, getLibraryPathWithoutMaven(mc, entries.forgeUniversalJar.fileName))); } if (!profile.data) { profile.data = {}; } const installerMaven = `net.minecraftforge:forge:${forgeVersion}:installer` profile.data.INSTALLER = { client: `[${installerMaven}]`, server: `[${installerMaven}]`, } if (entries.serverLzma) { // forge version and mavens, compatible with twitch api const serverMaven = `net.minecraftforge:forge:${forgeVersion}:serverdata@lzma`; // override forge bin patch location profile.data.BINPATCH.server = `[${serverMaven}]`; const serverBinPath = mc.getLibraryByPath(LibraryInfo.resolve(serverMaven).path); await ensureFile(serverBinPath); promises.push(extractEntryTo(zip, entries.serverLzma, serverBinPath)); } if (entries.clientLzma) { // forge version and mavens, compatible with twitch api const clientMaven = `net.minecraftforge:forge:${forgeVersion}:clientdata@lzma`; // override forge bin patch location profile.data.BINPATCH.client = `[${clientMaven}]`; const clientBinPath = mc.getLibraryByPath(LibraryInfo.resolve(clientMaven).path); await ensureFile(clientBinPath); promises.push(extractEntryTo(zip, entries.clientLzma, clientBinPath)); } if (entries.forgeJar) { promises.push(extractEntryTo(zip, entries.forgeJar, getLibraryPathWithoutMaven(mc, entries.forgeJar.fileName))); } if (entries.runBat) { unpackData(entries.runBat) } if (entries.runSh) { unpackData(entries.runSh) } if (entries.winArgs) { unpackData(entries.winArgs) } if (entries.unixArgs) { unpackData(entries.unixArgs) } if (entries.userJvmArgs) { unpackData(entries.userJvmArgs) } promises.push( writeFile(installJsonPath, JSON.stringify(profile)), writeFile(versionJsonPath, JSON.stringify(versionJson)), ); await Promise.all(promises); return versionJson.id; } export function isLegacyForgeInstallerEntries(entries: ForgeInstallerEntries): entries is ForgeLegacyInstallerEntriesPattern { return !!entries.legacyUniversalJar && !!entries.installProfileJson; } export function isForgeInstallerEntries(entries: ForgeInstallerEntries): entries is ForgeInstallerEntriesPattern { return !!entries.installProfileJson && !!entries.versionJson; } /** * Walk the forge installer file to find key entries * @param zip THe forge instal * @param forgeVersion Forge version to install */ export async function walkForgeInstallerEntries(zip: ZipFile, forgeVersion: string): Promise<ForgeInstallerEntries> { const [forgeJar, forgeUniversalJar, clientLzma, serverLzma, installProfileJson, versionJson, legacyUniversalJar, runSh, runBat, unixArgs, userJvmArgs, winArgs] = await filterEntries(zip, [ `maven/net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}.jar`, `maven/net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}-universal.jar`, "data/client.lzma", "data/server.lzma", "install_profile.json", "version.json", `forge-${forgeVersion}-universal.jar`, // legacy installer format "data/run.sh", "data/run.bat", "data/unix_args.txt", "data/user_jvm_args.txt", "data/win_args.txt", ]); return { forgeJar, forgeUniversalJar, clientLzma, serverLzma, installProfileJson, versionJson, legacyUniversalJar, runSh, runBat, unixArgs, userJvmArgs, winArgs, }; } export class BadForgeInstallerJarError extends Error { error = "BadForgeInstallerJar" constructor( public jarPath: string, /** * What entry in jar is missing */ public entry?: string) { super(entry ? `Missing entry ${entry} in forge installer jar: ${jarPath}` : `Bad forge installer: ${jarPath}`); } } function installByInstallerTask(version: RequiredVersion, minecraft: MinecraftLocation, options: InstallForgeOptions) { return task("installForge", async function () { function getForgeArtifactVersion() { let [_, minor] = version.mcversion.split("."); let minorVersion = Number.parseInt(minor); if (minorVersion >= 7 && minorVersion <= 8) { return `${version.mcversion}-${version.version}-${version.mcversion}`; } return `${version.mcversion}-${version.version}`; } const forgeVersion = getForgeArtifactVersion(); const mc = MinecraftFolder.from(minecraft); return withAgents(options, async (options) => { const jarPath = await this.yield(new DownloadForgeInstallerTask(forgeVersion, version.installer, mc, options) .map(function () { return this.installJarPath })); const zip = await open(jarPath, { lazyEntries: true, autoClose: false }); const entries = await walkForgeInstallerEntries(zip, forgeVersion); if (!entries.installProfileJson) { throw new BadForgeInstallerJarError(jarPath, "install_profile.json"); } const profile: InstallProfile = await readEntry(zip, entries.installProfileJson).then((b) => b.toString()).then(JSON.parse); if (isForgeInstallerEntries(entries)) { // new forge const versionId = await unpackForgeInstaller(zip, entries, forgeVersion, profile, mc, jarPath, options); await this.concat(installByProfileTask(profile, minecraft, options)); return versionId; } else if (isLegacyForgeInstallerEntries(entries)) { // legacy forge return installLegacyForgeFromZip(zip, entries, profile, mc, options); } else { // bad forge throw new BadForgeInstallerJarError(jarPath); } }); }); } /** * Install forge to target location. * Installation task for forge with mcversion >= 1.13 requires java installed on your pc. * @param version The forge version meta * @returns The installed version name. * @throws {@link BadForgeInstallerJarError} */ export function installForge(version: RequiredVersion, minecraft: MinecraftLocation, options?: InstallForgeOptions) { return installForgeTask(version, minecraft, options).startAndWait(); } /** * Install forge to target location. * Installation task for forge with mcversion >= 1.13 requires java installed on your pc. * @param version The forge version meta * @returns The task to install the forge * @throws {@link BadForgeInstallerJarError} */ export function installForgeTask(version: RequiredVersion, minecraft: MinecraftLocation, options: InstallForgeOptions = {}): Task<string> { return installByInstallerTask(version, minecraft, options); } /** * Query the webpage content from files.minecraftforge.net. * * You can put the last query result to the fallback option. It will check if your old result is up-to-date. * It will request a new page only when the fallback option is outdated. * * @param option The option can control querying minecraft version, and page caching. */ export async function getForgeVersionList(option: { /** * The minecraft version you are requesting */ mcversion?: string; /** * If this presents, it will send request with the original list timestamp. * * If the server believes there is no modification after the original one, * it will directly return the orignal one. */ original?: ForgeVersionList; } = {}): Promise<ForgeVersionList> { const mcversion = option.mcversion || ""; const url = mcversion === "" ? "http://files.minecraftforge.net/maven/net/minecraftforge/forge/index.html" : `http://files.minecraftforge.net/maven/net/minecraftforge/forge/index_${mcversion}.html`; return getAndParseIfUpdate(url, parseForge, option.original); }
the_stack
'use strict'; import { Logger, LogLevel } from 'chord/platform/log/common/log'; import { filenameToNodeName } from 'chord/platform/utils/common/paths'; const loggerWarning = new Logger(filenameToNodeName(__filename), LogLevel.Warning); import { sleep } from 'chord/base/common/time'; import { ok } from 'chord/base/common/assert'; import { querystringify } from 'chord/base/node/url'; import { IAudio } from 'chord/music/api/audio'; import { ISong } from 'chord/music/api/song'; import { ILyric } from 'chord/music/api/lyric'; import { IAlbum } from 'chord/music/api/album'; import { IArtist } from 'chord/music/api/artist'; import { ICollection } from 'chord/music/api/collection'; import { TMusicItems } from 'chord/music/api/items'; import { IAccount } from 'chord/music/api/user'; import { ESize, resizeImageUrl } from 'chord/music/common/size'; import { makeCookieJar, CookieJar } from 'chord/base/node/cookies'; import { request, IRequestOptions } from 'chord/base/node/_request'; import { encrypt } from 'chord/music/migu/crypto'; import { makeAudios, makeSong, makeSongs, makeLyric, makeAlbum, makeAlbums, makeCollection, makeCollections, makeArtist, makeArtists, extractArtistSongIds, makeArtistAlbums, extractCollectionSongIds, } from 'chord/music/migu/parser'; export class MiguMusicApi { static readonly HEADERS_AUDIO = { 'Connection': 'keep-alive', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36', 'Referer': 'http://music.migu.cn/v3/music/player/audio', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6,ja;q=0.5', }; static readonly HEADERS_h5 = { 'Connection': 'keep-alive', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Mobile Safari/537.36', 'Referer': 'http://m.music.migu.cn/v3', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6,ja;q=0.5', 'Content-Type': 'application/json; charset=utf-8', }; static readonly HEADERS_WEB = { 'Connection': 'keep-alive', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36', 'Referer': 'http://music.migu.cn/v3/', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6,ja;q=0.5', }; static readonly BASICURL = 'http://music.migu.cn/'; static readonly BASICURL_H5 = 'http://m.music.migu.cn/'; static readonly NODE_MAP = { audio: 'v3/api/music/audioPlayer/getPlayInfo', song: 'v3/api/music/audioPlayer/songs', song_h5: 'migu/remoting/cms_detail_tag', album: 'migu/remoting/cms_album_detail_tag', albumSongs: 'v3/api/music/audioPlayer/songs', collection: 'migu/remoting/playlist_query_tag', collectionSongs: 'v3/music/playlist', // From web artist: 'migu/remoting/cms_artist_detail_tag', artistSongs: 'v3/music/artist', // From web artistAlbums: 'v3/music/artist', // From web search: 'migu/remoting/scr_search_tag', } private account: IAccount; private cookieJar: CookieJar; constructor() { if (!this.cookieJar) { let cookieJar = makeCookieJar(); // initiateCookies().forEach(cookie => { // let domain = cookie.domain; // cookieJar.setCookie(cookie, domain.startsWith('http') ? domain : 'http://' + domain); // }); this.cookieJar = cookieJar; } } public async request(node: string, params: any, to_enc: boolean = false, domain?: string, to_json: boolean = true): Promise<any> { let url = (domain || MiguMusicApi.BASICURL) + node; let headers; switch (domain) { case MiguMusicApi.BASICURL_H5: headers = MiguMusicApi.HEADERS_h5; break; case MiguMusicApi.BASICURL: headers = MiguMusicApi.HEADERS_WEB; break; default: headers = MiguMusicApi.HEADERS_WEB; } if (node == MiguMusicApi.NODE_MAP.audio) { headers = MiguMusicApi.HEADERS_AUDIO; } if (to_enc) { let { secKey, encBuf } = encrypt(JSON.stringify(params)); params = { dataType: 2, data: encBuf, secKey, } } if (params) { url = url + '?' + querystringify(params); } let options: IRequestOptions = { method: 'GET', url: url, jar: this.cookieJar || null, headers: headers, gzip: true, json: to_json, resolveWithFullResponse: false, }; let result = await request(options); ok(result, `[ERROR] [MiguMusicApi.request]: url: ${url}, result is ${result}`); let is_ok = true; if (to_json) { is_ok = ((result['returnCode'] || result['code']) == '000000') || !!result['data'] || !!result['result'] || !!result['success']; } if (!is_ok) { loggerWarning.warning(`[ERROR] [MiguMusicApi.request]: url: ${url}, result is ${JSON.stringify(result)}`); let message = result['msg']; throw new Error(message); } return result; } // flac: type = 3 // 320kbps: type = 2 // 40kbps: type = 1 public async audios(songId: string, supKbps?: number): Promise<Array<IAudio>> { let audios = []; while (true) { let tp = 2; if (supKbps > 320) { tp = 3; } let node = MiguMusicApi.NODE_MAP.audio; let params = { copyrightId: songId, auditionsFlag: 0, type: tp, }; let json = await this.request(node, params, true); audios = makeAudios(json['data']); // if the audio is not flac, changing to 320kbps if (audios.length > 0 && tp == 3) { if (audios[0].kbps < 320) { supKbps = 320; continue; } } break; } return audios; } // WARN: songId is a copyrightId of migu music public async song(songId: string): Promise<ISong> { let node = MiguMusicApi.NODE_MAP.song_h5; let params: any = { cpid: songId, // or cpid: songMid // cid、cpid和pid至少填写一个 }; let json = await this.request(node, params, false, MiguMusicApi.BASICURL_H5); let song = makeSong(json.data); // Get album info node = MiguMusicApi.NODE_MAP.song; params = { type: 1, copyrightId: songId, }; json = await this.request(node, params); let song_ = makeSong(json.items && json.items[0]); song.duration = song_.duration; song.albumId = song_.albumId; song.albumOriginalId = song_.albumOriginalId; song.albumName = song_.albumName; song.artistId = song_.artistId; song.artistOriginalId = song_.artistOriginalId; song.artistName = song_.artistName; return song; } public async songs(songIds: Array<string>): Promise<Array<ISong>> { // Get album info let node = MiguMusicApi.NODE_MAP.song; let params = { type: 1, copyrightId: songIds.join(','), }; let json = await this.request(node, params); return makeSongs(json.items); } public async lyric(songId: string): Promise<ILyric> { let node = MiguMusicApi.NODE_MAP.song_h5; let params = { cpid: songId, // or cpid: songMid // cid、cpid和pid至少填写一个 }; let json = await this.request(node, params, false, MiguMusicApi.BASICURL_H5); let lyricInfo = json.data.lyricLrc; let transInfo = null; return makeLyric(songId, lyricInfo, transInfo); } public async album(albumId: string): Promise<IAlbum> { let node = MiguMusicApi.NODE_MAP.album; let params: any = { albumId, }; let json = await this.request(node, params, false, MiguMusicApi.BASICURL_H5); let album = makeAlbum(json.data); node = MiguMusicApi.NODE_MAP.albumSongs; params = { albumId, type: 2, }; json = await this.request(node, params, false); let songs = makeSongs(json.items).map(song => { song.albumCoverUrl = album.albumCoverUrl; return song; }); if (songs.length > 0) { let song = songs[0]; album.artistOriginalId = song.artistOriginalId; album.artistId = song.artistId; album.artistName = song.artistName; } album.songs = songs; return album; } public async artist(artistId: string): Promise<IArtist> { let node = MiguMusicApi.NODE_MAP.artist; let params = { artistId, }; let json = await this.request(node, params, false, MiguMusicApi.BASICURL_H5); return makeArtist(json.data); } /** * There gets an artist's top 50 songs * It can't be more */ public async artistSongs(artistId: string, page: number = 1, size: number = 20): Promise<Array<ISong>> { let node = MiguMusicApi.NODE_MAP.artistSongs + '/' + artistId + '/song'; let params = { page, }; let html = await this.request(node, params, false, MiguMusicApi.BASICURL, false); let songIds = extractArtistSongIds(html); return this.songs(songIds); } public async artistAlbums(artistId: string, page: number = 1, size: number = 30): Promise<Array<IAlbum>> { let node = MiguMusicApi.NODE_MAP.artistAlbums + '/' + artistId + '/album'; let params = { page, }; let html = await this.request(node, params, false, MiguMusicApi.BASICURL, false); return makeArtistAlbums(html); } public async collection(collectionId: string, size: number = 10000): Promise<ICollection> { let node = MiguMusicApi.NODE_MAP.collection; let params: any = { onLine: 1, queryChannel: 0, createUserId: '221acca8-9179-4ba7-ac3f-2b0fdffed356', contentCountMin: 5, playListId: collectionId, }; let json = await this.request(node, params, false, MiguMusicApi.BASICURL_H5); let collection = makeCollection(json.playlist[0]); let pages = Math.ceil(collection.songCount / 20); let songs = []; for (let page of [...Array(pages).keys()]) { while (true) { let node = MiguMusicApi.NODE_MAP.collectionSongs + '/' + collectionId; let params = { page: page + 1, }; let html; try { html = await this.request(node, params, false, MiguMusicApi.BASICURL, false); } catch (e) { await sleep(1); continue; } let songIds = extractCollectionSongIds(html); let songs_; try { songs_ = await this.songs(songIds); } catch (e) { await sleep(1); continue; } songs = [...songs, ...songs_]; break; } }; collection.songs = songs; return collection; } /** * Search * * data params: * @type: * 2: song * 1: artist * 4: album * 5: mv * 6: collection */ public async search(type: number, keyword: string, page: number = 1, size: number = 10): Promise<any> { let node = MiguMusicApi.NODE_MAP.search; let params: any = { rows: size, type, keyword, pgc: page, }; let json = await this.request(node, params, false, MiguMusicApi.BASICURL_H5); return json; } /** * Search songs * * type = 2 */ public async searchSongs(keyword: string, page: number = 1, size: number = 10): Promise<Array<ISong>> { let json = await this.search(2, keyword, page, size); if (!json['musics']) { return []; } return makeSongs(json['musics'] || []); } /** * Search albums * type = 4 */ public async searchAlbums(keyword: string, page: number = 1, size: number = 10): Promise<Array<IAlbum>> { let json = await this.search(4, keyword, page, size); if (!json['albums']) { return []; } return makeAlbums(json['albums'] || []); } /** * Search artists * * type = 1 */ public async searchArtists(keyword: string, page: number = 1, size: number = 10): Promise<Array<IArtist>> { let json = await this.search(1, keyword, page, size); if (!json['artists']) { return []; } return makeArtists(json['artists'] || []); } /** * Search collections * type = 6 */ public async searchCollections(keyword: string, page: number = 1, size: number = 10): Promise<Array<ICollection>> { let json = await this.search(6, keyword, page, size); if (!json['songLists']) { return []; } return makeCollections(json['songLists'] || []); } public async playLog(songId: string, seek: number): Promise<boolean> { return false; } public resizeImageUrl(url: string, size: ESize | number): string { return resizeImageUrl(url, size, (url, size) => `${url}?${size}x${size}`); } public async fromURL(input: string): Promise<Array<TMusicItems>> { let chunks = input.split(' '); let items = []; for (let chunk of chunks) { let m; let originId; let type; let matchList = [ // song [/song\/([\da-zA-Z]+)/, 'song'], // artist [/artist\/(\d+)/, 'artist'], // album [/album\/(\d+)/, 'album'], // playlist [/playlist\/(\d+)/, 'collection'], ]; for (let [re, tp] of matchList) { m = (re as RegExp).exec(chunk); if (m) { originId = m[1]; type = tp; break; } } if (originId) { let item; switch (type) { case 'song': item = await this.song(originId); items.push(item); break; case 'artist': item = await this.artist(originId); items.push(item); break; case 'album': item = await this.album(originId); items.push(item); break; case 'collection': item = await this.collection(originId); items.push(item); break; default: break; } } } return items; } }
the_stack
import * as React from 'react'; import styles from './AllLinks.module.scss'; import { IAllLinksProps } from './IAllLinksProps'; import { IAllLinksState, Link, User, LinkType, ILink, ICategory } from './IAllLinksState'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; import { Button, DefaultButton } from 'office-ui-fabric-react/lib/Button'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar'; import { Spinner, SpinnerSize, SpinnerType } from 'office-ui-fabric-react/lib/Spinner'; import { Modal } from 'office-ui-fabric-react/lib/Modal'; import * as strings from 'AllLinksWebPartStrings'; import "@pnp/polyfill-ie11"; import { sp } from "@pnp/sp"; import { find, isEqual, findIndex } from '@microsoft/sp-lodash-subset'; import { Text } from 'office-ui-fabric-react/lib/Text'; import { stringIsNullOrEmpty } from '@pnp/common'; import { add } from 'lodash'; enum CategoryOperation {add,remove} export default class AllLinks extends React.Component<IAllLinksProps, IAllLinksState> { public constructor(props) { super(props); this.state = { mandatoryLinks: undefined, editorLinks: undefined, categoryLinks: undefined, favouriteLinks: [], showModal: false, saveButtonDisabled: true, isLoading: true }; } public render(): React.ReactElement<IAllLinksProps> { if (this.state.isLoading) { return ( <Spinner type={SpinnerType.large} /> ); } else { let mandatoryLinks = this.state.mandatoryLinks ? this.generateMandatoryLinkComponents(this.state.mandatoryLinks) : null; let editorLinks = this.state.editorLinks ? this.generateEditorLinkComponents(this.state.editorLinks) : null; let favouriteLinks = this.state.favouriteLinks ? this.generateFavouriteLinkComponents(this.state.favouriteLinks) : null; let newLinkModal = this.state.showModal ? this.generateNewLinkModal() : null; let categoryLinks = this.generateLinks(this.state.categoryLinks); let errorMessage = this.state.showErrorMessage ? <MessageBar messageBarType={MessageBarType.error} onDismiss={() => this.setState({ showErrorMessage: false })}>{strings.component_SaveErrorLabel}</MessageBar> : null; //let successMessage = this.state.showSuccessMessage ? <MessageBar messageBarType={MessageBarType.success} onDismiss={() => this.setState({ showSuccessMessage: false })} >{strings.component_SaveOkLabel}</MessageBar> : null; let loadingSpinner = this.state.showLoadingSpinner ? <Spinner style={{position:'absolute',right:10,top:-10}} className={styles.spinner} size={SpinnerSize.small} /> : null; let linkListing = this.props.listingByCategory ? <div className={styles.allLinks}> <div className={styles.webpartHeader}> <span>{this.props.listingByCategoryTitle}</span> </div> <div className={styles.linkGrid}> {categoryLinks} </div> </div> : <div> <div className={styles.webpartHeading} >{stringIsNullOrEmpty(this.props.mandatoryLinksTitle) ? strings.component_MandatoryLinksLabel : this.props.mandatoryLinksTitle}</div> <div className={styles.editorLinksContainer}>{mandatoryLinks}</div> <hr /> <div className={styles.webpartHeading} >{stringIsNullOrEmpty(this.props.reccomendedLinksTitle) ? strings.component_PromotedLinksLabel : this.props.reccomendedLinksTitle}</div> <div className={styles.editorLinksContainer}>{editorLinks}</div> </div>; let myLinks = <div> <div className={styles.webpartHeading}>{stringIsNullOrEmpty(this.props.myLinksTitle) ? strings.component_YourLinksLabel : this.props.myLinksTitle}</div> <div className={styles.editorLinksContainer}>{favouriteLinks}</div> <div className={styles.buttonRow} > {/* <Button onClick={() => this.saveData()} text={strings.component_SaveYourLinksLabel} disabled={this.state.saveButtonDisabled} /> */} <Button onClick={() => this.openNewItemModal()} text={strings.component_NewLinkLabel} iconProps={{ iconName: 'Add' }} /> </div> </div>; return ( <div className={styles.allLinks}> {errorMessage} {loadingSpinner} {newLinkModal} {(this.props.mylinksOnTop) ? <div> {myLinks} <hr /> {linkListing} </div> : <div> {linkListing} <hr /> {myLinks} </div> } </div> ); } } public componentWillMount() { this.fetchData(); } private openNewItemModal() { let emptyLink: Link = { id: -1, displayText: "", url: "", icon: this.props.defaultIcon, priority: "1000", mandatory: 0, linkType: LinkType.favouriteLinks }; this.setState({ showModal: true, modalData: emptyLink }); } private appendToFavourites(link: Link) { let newFavourites = this.state.favouriteLinks.slice(); newFavourites.push(link); let newEditorLinks = this.state.editorLinks.slice(); newEditorLinks.splice(newEditorLinks.indexOf(link), 1); let categoryLinks = this.state.categoryLinks; categoryLinks = this.updateCategoryLinks(CategoryOperation.remove, link as ILink, categoryLinks); this.setState({ favouriteLinks: newFavourites, editorLinks: newEditorLinks, saveButtonDisabled: false },()=>this.saveData()); } private removeFromFavourites(link: Link) { let newEditorLinks = this.state.editorLinks.slice(); newEditorLinks.push(link); let newFavourites = this.state.favouriteLinks.slice(); newFavourites.splice(newFavourites.indexOf(link), 1); let categoryLinks = this.state.categoryLinks; categoryLinks = this.updateCategoryLinks(CategoryOperation.add, link as ILink, categoryLinks); this.setState({ favouriteLinks: newFavourites, editorLinks: newEditorLinks, categoryLinks: categoryLinks, saveButtonDisabled: false },()=>this.saveData()); } private updateCategoryLinks(operation: CategoryOperation, link: ILink, categoryLinks: ICategory[]) { if (this.props.listingByCategory) { categoryLinks = categoryLinks.map(category => { if (category.displayText === link['category']) { if(operation === CategoryOperation.remove ){ category.links = category.links.filter(clink => link.url !== clink.url); } else { category.links.push(link); } } return category; }); } return categoryLinks; } private removeCustomFromFavourites(link: Link) { let newFavourites = this.state.favouriteLinks.slice(); newFavourites.splice(newFavourites.indexOf(link), 1); this.setState({ favouriteLinks: newFavourites, saveButtonDisabled: false }); } private generateEditorLinkComponents(links: Array<Link>) { return links.map(link => { return ( <div className={styles.linkParent}> <Text className={styles.linkContainer} onClick={() => window.open(link.url, "_blank")}> <Icon iconName={(link.icon) ? link.icon : this.props.defaultIcon} className={styles.icon} /> <span title={link.displayText}>{link.displayText}</span> </Text> <Icon className={styles.actionIcon} iconName='CirclePlus' onClick={() => this.appendToFavourites(link)} /> </div> ); }); } private generateMandatoryLinkComponents(links: Array<Link>) { return links.map(link => { return ( <div className={styles.linkParent}> <Text className={styles.linkContainer} onClick={() => window.open(link.url, "_blank")}> <Icon iconName={(link.icon) ? link.icon : this.props.defaultIcon} className={styles.icon} /> <span>{link.displayText}</span> </Text> </div> ); }); } private generateFavouriteLinkComponents(links: Array<Link>) { return links.map(link => { let linkIcon = <Icon iconName={(link.icon) ? link.icon : this.props.defaultIcon} className={styles.icon} />; let removeLinkButton = link.linkType === LinkType.editorLink ? <Icon className={styles.actionIcon} iconName='SkypeCircleMinus' onClick={() => this.removeFromFavourites(link)} /> : <Icon className={styles.actionIcon} iconName='SkypeCircleMinus' onClick={() => this.removeCustomFromFavourites(link)} />; return ( <div className={styles.linkParent}> <Text className={styles.linkContainer} onClick={() => window.open(link.url, "_blank")}> {linkIcon} <div>{link.displayText}</div> </Text> {removeLinkButton} </div> ); }); } private generateNewLinkModal() { return ( <Modal isOpen={this.state.showModal} isBlocking={false} containerClassName={styles.newLinkModal} onDismiss={() => this.setState({ modalData: null, showModal: false })}> <div className={styles.modalHeader}>{strings.component_NewLinkLabel}</div> <div className={styles.modalBody}> <TextField label='Url' onChanged={(newVal) => this.onModalValueChanged('url', newVal)} value={this.state.modalData['url']} onGetErrorMessage={(value) => this.getUrlErrorMessage(value)} /> <TextField label={strings.component_TitleLabel} onChanged={(newVal) => this.onModalValueChanged('displayText', newVal)} value={this.state.modalData['displayText']} /> <DefaultButton text={strings.component_AddLabel} onClick={() => this.addNewLink()} /> <Button text={strings.component_CancelLabel} onClick={() => { this.setState({ modalData: null, showModal: false }); }} /> </div> </Modal> ); } private addNewLink() { let newFavourites = this.state.favouriteLinks.slice(); newFavourites.push(this.state.modalData); this.setState({ favouriteLinks: newFavourites, modalData: null, showModal: false, saveButtonDisabled: false },()=>this.saveData()); } private onModalValueChanged(field, newVal) { let newModalData: Link = { ...this.state.modalData }; newModalData[field] = newVal; this.setState({ modalData: newModalData }); } private getUrlErrorMessage(value: any): string { if (value.length > 0) { let urlRegex = /(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/; return value.match(urlRegex) === null ? strings.component_UrlValidationLabel : ''; } else { return ''; } } private generateLinks(categories: Array<ICategory>) { return categories.map(cat => { let linkItems = cat.links.map(link => { let linkIcon = <Icon iconName={(link.icon) ? link.icon : this.props.defaultIcon} className={styles.icon} />; let linkStyle = { width: this.props.maxLinkLength }; let linkTarget = link.openInSameTab ? '_self' : '_blank'; return ( <div className={styles.linkGridColumn}> <a className={styles.linkContainer} data-interception="off" href={link.url} title={link.displayText} target={linkTarget}> {linkIcon} <span style={linkStyle}>{link.displayText}</span> </a> {(link.mandatory) ? <Icon className={styles.icon} iconName='Lock' title={strings.component_action_removeMandatory} /> : <Icon className={styles.actionIcon} iconName='CirclePlus' onClick={() => this.appendToFavourites(link)} /> } </div> ); }); if (this.props.listingByCategory) { return <div className={styles.categorySection}><div className={styles.linkCategoryHeading}>{cat.displayText}</div>{linkItems}</div>; } return <div>{linkItems}</div>; }); } private async fetchData() { try { let searchString = `AuthorId eq '${this.props.currentUserId}'`; let favouriteLinkListItem = await sp.web.getList(this.props.webServerRelativeUrl + "/Lists/FavouriteLinks").items.select("Id", "AuthorId", "PzlPersonalLinks").filter(searchString).get(); let favouriteItemsIds: Array<number>; let favouriteItems: Array<Link> = []; if (favouriteLinkListItem.length > 0 && favouriteLinkListItem[0]["PzlPersonalLinks"] !== null) { favouriteItems = JSON.parse(favouriteLinkListItem[0]["PzlPersonalLinks"]); favouriteItemsIds = favouriteItems.map(link => link.id); this.setState({ favouriteLinks: favouriteItems }); } else { favouriteItemsIds = []; this.setState({ isFirstUpdate: true, }); } let editorLinks = await sp.web.getList(this.props.webServerRelativeUrl + "/Lists/EditorLinks").items.filter("PzlLinkActive eq 1").get(); let mappedLinks: Array<Link> = editorLinks.map(link => { return { id: link.Id, displayText: link.Title, url: link.PzlUrl, icon: link.PzlOfficeUIFabricIcon, priority: link.PzlPriority, mandatory: link.PzlLinkMandatory, linkType: LinkType.editorLink }; }); let mandatorymappedLinks = mappedLinks.filter(mandatory => mandatory.mandatory == 1); let promotedmappedLinks = mappedLinks.filter(mandatory => mandatory.mandatory == 0); let prunedLinks: Array<Link> = promotedmappedLinks.filter(link => { return favouriteItemsIds.indexOf(link.id) === -1; }); if (favouriteLinkListItem.length > 0 && favouriteItems !== null && favouriteItems.length > 0) { let favoriteLinks = await this.checkForUpdatedLinks(favouriteItems, promotedmappedLinks); favouriteItemsIds = favoriteLinks.map(item => item.id); } let linkFieldId = favouriteLinkListItem.length > 0 ? favouriteLinkListItem[0].Id : null; let currentUser: User = { id: this.props.currentUserId, linkFieldId: linkFieldId }; let displayLinks = editorLinks.map(link => { return { displayText: link.Title, url: link.PzlUrl, icon: link.PzlOfficeUIFabricIcon || "Link", priority: link.PzlLinkPriority || "0", category: link.PzlLinkCategory || "Ingen kategori", mandatory: link.PzlLinkMandatory, linkType: LinkType.editorLink }; }); let categories: Array<ICategory> = [{ displayText: strings.component_NoCategoryLabel, links: displayLinks }]; if (this.props.listingByCategory) { let categoryNames: string[] = displayLinks.map(lnk => { return lnk.category; }).sort(); categoryNames = categoryNames.filter((item, index) => { return categoryNames.indexOf(item) == index; }); categories = categoryNames.map(catName => { return { displayText: catName, links: displayLinks.filter(lnk => { return lnk.category === catName; }) }; }); } this.setState({ currentUser: currentUser, editorLinks: prunedLinks, mandatoryLinks: mandatorymappedLinks, categoryLinks: categories, isLoading: false, }); } catch (err) { console.log(err); this.setState({ isLoading: false, }); } } private async saveData() { this.setState({ showLoadingSpinner: true, saveButtonDisabled: true, }); try { let linksAsString = JSON.stringify(this.state.favouriteLinks); if (this.state.isFirstUpdate) { let result = await sp.web.getList(this.props.webServerRelativeUrl + "/Lists/FavouriteLinks").items.add({ 'PzlPersonalLinks': linksAsString, 'Title': this.props.currentUserName, }); let currentUser: User = { id: this.state.currentUser.id, linkFieldId: result.data.Id, }; this.setState({ isFirstUpdate: false, saveButtonDisabled: true, currentUser: currentUser, showSuccessMessage: true, showLoadingSpinner: false, }); setTimeout(() => this.setState({ showSuccessMessage: false }), 5000); } else { let result = await sp.web.getList(this.props.webServerRelativeUrl + "/Lists/FavouriteLinks").items.getById(+this.state.currentUser.linkFieldId).update({ 'PzlPersonalLinks': linksAsString, }); this.setState({ saveButtonDisabled: true, showSuccessMessage: true, showLoadingSpinner: false, }); setTimeout(() => this.setState({ showSuccessMessage: false }), 5000); } } catch (err) { this.setState({ showErrorMessage: true, showLoadingSpinner: false, saveButtonDisabled: false, }); setTimeout(() => this.setState({ showErrorMessage: false }), 5000); } } private async checkForUpdatedLinks(userFavoriteLinks: any[], allFavoriteLinks: any[]) { let personalLinks = new Array<Link>(); let shouldUpdate = false; userFavoriteLinks.forEach(userLink => { let linkMatch = find(allFavoriteLinks, (favoriteLink => favoriteLink.id === userLink.id)); if (linkMatch && (!isEqual(linkMatch.url, userLink.url) || !isEqual(linkMatch.displayText, userLink.displayText) || !isEqual(linkMatch.icon, userLink.icon))) { shouldUpdate = true; personalLinks.push(linkMatch); } else { personalLinks.push(userLink); } }); if (shouldUpdate) { this.setState({ favouriteLinks: personalLinks }); } return personalLinks; } }
the_stack
import { BATCH_READ_ITEMS_LIMIT, BATCH_WRITE_ITEMS_LIMIT, InvalidBatchWriteItemError, TRANSFORM_BATCH_TYPE, } from '@typedorm/common'; import {DocumentClient} from 'aws-sdk/clients/dynamodb'; import {v4} from 'uuid'; import {getHashedIdForInput} from '../../helpers/get-hashed-id-for-input'; import {ReadBatch, ReadBatchItem} from '../batch/read-batch'; import {isBatchAddCreateItem, isBatchAddDeleteItem} from '../batch/type-guards'; import {WriteBatchItem, WriteBatch} from '../batch/write-batch'; import {Connection} from '../connection/connection'; import {isWriteTransactionItemList} from '../transaction/type-guards'; import {MetadataOptions} from './base-transformer'; import { isLazyTransactionWriteItemListLoader, LazyTransactionWriteItemListLoader, } from './is-lazy-transaction-write-item-list-loader'; import {LowOrderTransformers} from './low-order-transformers'; export type WriteRequestWithMeta = { tableName: string; writeRequest: DocumentClient.WriteRequest; }; export type ReadRequestWithMeta = { tableName: string; readRequest: DocumentClient.Key; }; export type BatchWriteItemTransform<Transformed> = { rawInput: any; transformedInput: Transformed; }; export type BatchWriteItemRequestMapTransform<Transformed> = { [key: string]: BatchWriteItemTransform<Transformed>[]; }; export class DocumentClientBatchTransformer extends LowOrderTransformers { constructor(connection: Connection) { super(connection); } toDynamoWriteBatchItems( writeBatch: WriteBatch, metadataOptions?: MetadataOptions ): { batchWriteRequestMapItems: DocumentClient.BatchWriteItemRequestMap[]; transactionListItems: BatchWriteItemTransform< DocumentClient.TransactWriteItemList >[]; lazyTransactionWriteItemListLoaderItems: BatchWriteItemTransform< LazyTransactionWriteItemListLoader >[]; metadata: { namespaceId: string; itemTransformHashMap: Map<string, WriteBatchItem<any, any>>; }; } { const {items} = writeBatch; this.connection.logger.logTransformBatch({ requestId: metadataOptions?.requestId, operation: TRANSFORM_BATCH_TYPE.BATCH_WRITE, prefix: 'Before', body: items, }); const { lazyTransactionWriteItemListLoaderItems, simpleBatchRequestItems, transactionListItems, metadata, } = this.innerTransformBatchWriteItems(items, metadataOptions); // organize all requests in "tableName - requestItem" format const sorted = this.getWriteRequestsSortedByTable(simpleBatchRequestItems); // divide sorted requests in multiple batch items requests, as there are max // 25 items are allowed in a single batch operation const batchWriteRequestItems = this.mapTableWriteItemsToBatchWriteItems( sorted ); const transformed = { batchWriteRequestMapItems: batchWriteRequestItems, transactionListItems, lazyTransactionWriteItemListLoaderItems, metadata, }; this.connection.logger.logTransformBatch({ requestId: metadataOptions?.requestId, operation: TRANSFORM_BATCH_TYPE.BATCH_WRITE, prefix: 'After', body: transformed, }); return transformed; } toDynamoReadBatchItems( readBatch: ReadBatch, metadataOptions?: MetadataOptions ): { batchRequestItemsList: DocumentClient.BatchGetRequestMap[]; metadata: { namespaceId: string; itemTransformHashMap: Map<string, ReadBatchItem<any, any>>; }; } { const {items} = readBatch; this.connection.logger.logTransformBatch({ requestId: metadataOptions?.requestId, operation: TRANSFORM_BATCH_TYPE.BATCH_READ, prefix: 'Before', body: items, }); const {metadata, batchReadRequestItems} = this.transformBatchReadItems( items ); // organize all requests in "tableName - requestItem" format const sortedByTableName = this.getReadRequestsSortedByTable( batchReadRequestItems ); // divide sorted requests in multiple batch items requests, as there are max // 100 items are allowed in a single batch read operation const batchRequestItemsList = this.mapTableReadItemsToBatchReadItems( sortedByTableName ); const transformed = { batchRequestItemsList, metadata, }; this.connection.logger.logTransformBatch({ requestId: metadataOptions?.requestId, operation: TRANSFORM_BATCH_TYPE.BATCH_READ, prefix: 'After', body: transformed, }); return transformed; } mapTableWriteItemsToBatchWriteItems( requestsSortedByTable: DocumentClient.BatchWriteItemRequestMap ) { let currentFillingIndex = 0; let totalItemsAtCurrentFillingIndex = 0; const multiBatchItems = Object.entries(requestsSortedByTable).reduce( (acc, [tableName, perTableItems]) => { // separate requests into multiple batch items, if there are more than allowed items to process in batch while (perTableItems.length) { if (!acc[currentFillingIndex]) { acc[currentFillingIndex] = {}; } if (!acc[currentFillingIndex][tableName]) { acc[currentFillingIndex][tableName] = []; } acc[currentFillingIndex][tableName].push(perTableItems.shift()!); ++totalItemsAtCurrentFillingIndex; // batch write request has limit of 25 items per batch so once we hit that limit, // separate remaining items as new batch request if (totalItemsAtCurrentFillingIndex === BATCH_WRITE_ITEMS_LIMIT) { ++currentFillingIndex; totalItemsAtCurrentFillingIndex = 0; } } return acc; }, [] as DocumentClient.BatchWriteItemRequestMap[] ); return multiBatchItems; } mapTableReadItemsToBatchReadItems( requestsSortedByTable: DocumentClient.BatchGetRequestMap ) { let currentFillingIndex = 0; let totalItemsAtCurrentFillingIndex = 0; const multiBatchItems = Object.entries(requestsSortedByTable).reduce( (acc, [tableName, perTableItems]) => { // separate requests into multiple batch items, if there are more than allowed items to process in batch while (perTableItems.Keys.length) { if (!acc[currentFillingIndex]) { acc[currentFillingIndex] = {}; } if (!acc[currentFillingIndex][tableName]) { acc[currentFillingIndex][tableName] = { Keys: [], }; } acc[currentFillingIndex][tableName].Keys.push( perTableItems.Keys.shift()! ); ++totalItemsAtCurrentFillingIndex; // batch read request has limit of max 100 items per batch so once we hit that limit, // separate remaining items as new batch request if (totalItemsAtCurrentFillingIndex === BATCH_READ_ITEMS_LIMIT) { ++currentFillingIndex; totalItemsAtCurrentFillingIndex = 0; } } return acc; }, [] as DocumentClient.BatchGetRequestMap[] ); return multiBatchItems; } /** * Reverse transforms batch write item request to write batch item */ toWriteBatchInputList( requestMap: DocumentClient.BatchWriteItemRequestMap, { namespaceId, itemTransformHashMap, }: { namespaceId: string; itemTransformHashMap: Map<string, WriteBatchItem<any, any>>; } ) { return Object.entries(requestMap).flatMap(([, writeRequests]) => { return this.toRawBatchInputItem< DocumentClient.WriteRequest, WriteBatchItem<any, any> >(writeRequests, { namespaceId, itemTransformHashMap, }); }); } /** * Reverse transforms batch read item request to read batch item */ toReadBatchInputList( requestMap: DocumentClient.BatchGetRequestMap, { namespaceId, itemTransformHashMap, }: { namespaceId: string; itemTransformHashMap: Map<string, ReadBatchItem<any, any>>; } ) { return Object.entries(requestMap).flatMap(([, readRequests]) => { return this.toRawBatchInputItem< DocumentClient.Key, ReadBatchItem<any, any> >(readRequests.Keys, { namespaceId, itemTransformHashMap, }); }); } /** * Converts batch item input to pre transformed item input */ private toRawBatchInputItem<Input, Output>( transformedItems: Input[], { namespaceId, itemTransformHashMap, }: { namespaceId: string; itemTransformHashMap: Map<string, Output>; } ): Output[] { return transformedItems.map(transformedItem => { const hashId = getHashedIdForInput(namespaceId, transformedItem); const originalItem = itemTransformHashMap.get(hashId); return originalItem!; }); } /** * Parse each item in the request to be in one of the following collections * - simpleBatchRequestItems: simple items that can be processed in batch (i.e no uniques) * - transactionListItems: items that must be processed in a transaction instead of batch (i.e items with unique attributes) * - LazyTransactionWriteItemListLoaderItems: items that are must be processed in transaction but also requires other requests to be made first (i.e delete of unique items) */ private innerTransformBatchWriteItems( batchItems: WriteBatchItem<any, any>[], metadataOptions?: MetadataOptions ) { const namespaceId = v4(); const itemTransformHashMap = new Map<string, WriteBatchItem<any, any>>(); return batchItems.reduce( (acc, batchItem) => { // is create if (isBatchAddCreateItem(batchItem)) { // transform put item const dynamoPutItem = this.toDynamoPutItem( batchItem.create.item, undefined, metadataOptions ); if (!isWriteTransactionItemList(dynamoPutItem)) { const transformedWriteRequest = { PutRequest: { Item: dynamoPutItem.Item, }, }; acc.simpleBatchRequestItems.push({ writeRequest: transformedWriteRequest, tableName: dynamoPutItem.TableName, }); // store transformed and original items as hash key/value const itemHashId = getHashedIdForInput( namespaceId, transformedWriteRequest ); itemTransformHashMap.set(itemHashId, batchItem); } else { acc.transactionListItems.push({ rawInput: batchItem, transformedInput: dynamoPutItem, }); } // is delete } else if (isBatchAddDeleteItem(batchItem)) { const { delete: {item, primaryKey}, } = batchItem; // transform delete item const itemToRemove = this.toDynamoDeleteItem( item, primaryKey, undefined, metadataOptions ); if (!isLazyTransactionWriteItemListLoader(itemToRemove)) { const transformedItemRequest = { DeleteRequest: { Key: itemToRemove.Key, }, }; acc.simpleBatchRequestItems.push({ writeRequest: transformedItemRequest, tableName: itemToRemove.TableName, }); // store transformed and original items as hash key/value const itemHashId = getHashedIdForInput( namespaceId, transformedItemRequest ); itemTransformHashMap.set(itemHashId, batchItem); } else { acc.lazyTransactionWriteItemListLoaderItems.push({ rawInput: batchItem, transformedInput: itemToRemove, }); } } else { throw new InvalidBatchWriteItemError(batchItem); } return acc; }, { simpleBatchRequestItems: [] as WriteRequestWithMeta[], transactionListItems: [] as BatchWriteItemTransform< DocumentClient.TransactWriteItemList >[], lazyTransactionWriteItemListLoaderItems: [] as BatchWriteItemTransform< LazyTransactionWriteItemListLoader >[], metadata: { namespaceId, itemTransformHashMap, }, } ); } private transformBatchReadItems( batchItems: ReadBatchItem<any, any>[], metadataOptions?: MetadataOptions ) { const namespaceId = v4(); const itemTransformHashMap = new Map<string, ReadBatchItem<any, any>>(); return batchItems.reduce( (acc, batchItem) => { const {item, primaryKey} = batchItem; // TODO: add read options support const itemToGet = this.toDynamoGetItem( item, primaryKey, undefined, metadataOptions ); acc.batchReadRequestItems.push({ readRequest: itemToGet.Key, tableName: itemToGet.TableName, }); // store batch item input and it's transform in map, for reverse transform later const transformedItemHashId = getHashedIdForInput( namespaceId, itemToGet.Key ); itemTransformHashMap.set(transformedItemHashId, batchItem); return acc; }, { batchReadRequestItems: [] as ReadRequestWithMeta[], metadata: { namespaceId, itemTransformHashMap, }, } ); } private getWriteRequestsSortedByTable( allRequestItems: WriteRequestWithMeta[] ) { return allRequestItems.reduce((acc, requestItemWithMeta) => { if (!acc[requestItemWithMeta.tableName]) { acc[requestItemWithMeta.tableName] = []; } acc[requestItemWithMeta.tableName].push(requestItemWithMeta.writeRequest); return acc; }, {} as DocumentClient.BatchWriteItemRequestMap); } private getReadRequestsSortedByTable(allRequestItems: ReadRequestWithMeta[]) { return allRequestItems.reduce((acc, requestItemWithMeta) => { if (!acc[requestItemWithMeta.tableName]) { acc[requestItemWithMeta.tableName] = { Keys: [], }; } acc[requestItemWithMeta.tableName].Keys.push( requestItemWithMeta.readRequest ); return acc; }, {} as DocumentClient.BatchGetRequestMap); } }
the_stack
import { taskEither, TaskEither } from "fp-ts/lib/TaskEither" import { right } from "fp-ts/lib/Either" import { LeftType } from "./rfsTaskEither" import { types } from "util" export const isString = (x: any): x is string => typeof x === "string" export const isNumber = (x: any): x is number => typeof x === "number" export const pick = <T, K extends keyof T>(name: K) => (x: T): T[K] => x[name] export const flat = <T>(a: T[][]): T[] => a.reduce((res, current) => [...res, ...current], []) export const flatMap = <T1, T2>( arr: T1[], cb: (c: T1, idx?: number, arrref?: T1[]) => T2[] ) => flat(arr.map(cb)) // given an array of objects returns a map indexed by a property // only works if the property is an unique key export function ArrayToMap<T>(name: keyof T) { return (arr: T[]): Map<string, T> => { return arr.reduce((_map, current: T) => { _map.set(current[name], current) return _map }, new Map()) } } // returns a function that gets the given property from a map export const selectMap = <T1, K extends keyof T1, T2>( _map: Map<string, T1>, property: K, defval: T2 ): ((index: string) => T2) => (index: string): T2 => { const record = _map && _map.get(index) return ((record && record[property]) || defval) as T2 } // tslint:disable-next-line: ban-types export const isFn = (f: any): f is Function => { return typeof f === "function" } export const isStr = (f: any): f is string => { return typeof f === "string" } export const mapGet = <T1, T2>( _map: Map<T1, T2>, key: T1, init: (() => T2) | T2 ): T2 => { let result = _map.get(key) if (!result) { result = isFn(init) ? init() : init _map.set(key, result) } return result } export const stringOrder = (s1: any, s2: any) => { if (s1 > s2) return 1 return s2 > s1 ? -1 : 0 } export const fieldOrder = <T>(fieldName: keyof T, inverse: boolean = false) => ( a1: T, a2: T ) => stringOrder(a1[fieldName], a2[fieldName]) * (inverse ? -1 : 1) export function parts(whole: any, pattern: RegExp): string[] { if (!isString(whole)) return [] const match = whole.match(pattern) return match ? match.slice(1) : [] } export function toInt(raw: any): number { if (isNaN(raw)) return 0 if (isNumber(raw)) return Math.floor(raw) if (!raw && !isString(raw)) return 0 const n = Number.parseInt(raw, 10) if (isNaN(n)) return 0 return n } export const isUnDefined = (x: any): x is undefined => typeof x === "undefined" export const isDefined = <T>(x: T | undefined): x is T => typeof x !== "undefined" export const eatPromiseException = async <T>(p: Promise<T>) => { try { return await p } catch (error) { // ignore } } export const eatException = (cb: (...args: any[]) => any) => ( ...args: any[] ) => { try { return cb(...args) } catch (e) { return } } // synchronous. awaiting would defeat the purpose export const createMutex = () => { const m: Map<string, Promise<any>> = new Map() return (key: string, cb: any) => { const prom = (m.get(key) || Promise.resolve()).then(cb) m.set(key, eatPromiseException(prom)) return prom } } export interface Cache<TK, TP> extends Iterable<TP> { get: (x: TK) => TP size: number } /** * Given a constructor function returns an enumerable cache of objects * Optionally accepts a key conversion method as second parameter * Automates the pattern of returning an object from a map, or create and insert it if not found * * @param {(k:TMAPKEY)=>TRESULT} creator * @param {(k:TGETKEY)=>TMAPKEY=(x:any} KeyTranslator (optional) */ export function cache<TGETKEY, TRESULT, TMAPKEY>( creator: (k: TGETKEY) => TRESULT, keyTranslator: (k: TGETKEY) => TMAPKEY = (x: any) => x ): Cache<TGETKEY, TRESULT> { const values = new Map<TMAPKEY, TRESULT>() return { get: (key: TGETKEY) => { const mapKey = keyTranslator(key) let cur = values.get(mapKey) if (!cur) { cur = creator(key) values.set(mapKey, cur) } return cur }, get size() { return values.size }, *[Symbol.iterator]() { const v = values.values() let r = v.next() while (!r.done) { yield r.value r = v.next() } } } } export interface AsyncCache<TK, TP> extends Iterable<TP> { get: (x: TK, refresh?: boolean) => Promise<TP> getSync: (x: TK) => TP | undefined size: number } export const asyncCache = <TK, TP, TAK>( creator: (k: TK) => Promise<TP>, keyTran: (k: TK) => TAK = (x: any) => x ): AsyncCache<TK, TP> => { const values = new Map<TAK, TP>() const pending = new Map<TAK, Promise<TP>>() const attempt = async (mapKey: TAK, key: TK, refresh: boolean) => { let cur = values.get(mapKey) if (refresh || !cur) { cur = await creator(key) values.set(mapKey, cur) } return cur } function get(key: TK, refresh = false) { const mapKey = keyTran(key) let curP = pending.get(mapKey) if (!curP) { curP = attempt(mapKey, key, refresh) pending.set(mapKey, curP) eatPromiseException(curP).then(() => pending.delete(mapKey)) } return curP } return { get, getSync: (k: TK) => values.get(keyTran(k)), get size() { return values.size }, *[Symbol.iterator]() { const v = values.values() let r = v.next() while (!r.done) { yield r.value r = v.next() } } } } export const promiseQueue = <T>(initial: T) => { let current = Promise.resolve(initial) let last = initial return (cb?: (c: T) => Promise<T>, onErr?: (e: Error) => void) => { // must guarantee current will always resolve! if (cb) current = current.then(async cur => { try { const newres = await cb(cur) last = newres return newres } catch (e) { if (onErr) eatException(onErr)(e) return last } }) return current } } export const rememberFor = <T, K>( ms: number, f: (x: K) => T ): ((x: K) => T) => { const storage = new Map<K, { value: T; time: number }>() return (k: K) => { const time = new Date().getTime() let last = storage.get(k) if (!last || time - last.time > ms) { last = { time, value: f(k) } storage.set(k, last) } return last.value } } export const debounce = <K, R>(frequency: number, cb: (x: K) => R) => { const calls = new Map<K, Promise<R>>() return (key: K) => { const p = calls.get(key) || new Promise(resolve => { setTimeout(() => { calls.delete(key) resolve(cb(key)) }, frequency) }) calls.set(key, p) return p } } export const after = (time: number) => new Promise(resolve => setTimeout(resolve, time)) export const isNonNullable = <T>(x: T): x is NonNullable<T> => !(isUnDefined(x) || x === null) export function fieldReplacer<T1>( field: keyof T1, inputTask: TaskEither<LeftType, T1[keyof T1]>, shouldReplace?: (x: T1) => boolean ): <T2 extends T1>(x: T2) => TaskEither<LeftType, T2> export function fieldReplacer<T1, T2 extends T1>( field: keyof T1, inputTask: TaskEither<LeftType, T1[keyof T1]>, shouldReplace: (x: T1) => boolean, data: T2 ): TaskEither<LeftType, T2> export function fieldReplacer<T1, T2 extends T1>( field: keyof T1, inputTask: TaskEither<LeftType, T1[keyof T1]>, data: T2 ): TaskEither<LeftType, T2> export function fieldReplacer<T1, T2 extends string, T3 extends Record<T2, T1>>( field: T2, inputTask: TaskEither<LeftType, T1>, data?: T3 | ((x: T3) => boolean), data2?: T3 ) { const createTask = (prev: T3): TaskEither<LeftType, T3> => { if (isFn(data) && !data(prev)) return async () => right(prev) return taskEither.chain(inputTask, iop => async () => { return right({ ...prev, [field]: iop }) }) } const actualData = isFn(data) ? data2 : data return actualData ? createTask(actualData) : createTask } export function dependFieldReplacer<T1>( field: keyof T1, input: (data: T1, field: keyof T1) => TaskEither<LeftType, T1[keyof T1]>, shouldReplace?: (x: T1) => boolean ): <T2 extends T1>(x: T2) => TaskEither<LeftType, T2> export function dependFieldReplacer< T1, T2 extends string, T3 extends Record<T2, T1> >( field: T2, input: (data: T3, field: T2) => TaskEither<LeftType, T1[keyof T1]>, shouldReplace: (x: T3) => boolean, data: T3 ): TaskEither<LeftType, T3> export function dependFieldReplacer< T1, T2 extends string, T3 extends Record<T2, T1> >( field: T2, input: (data: T3, field: T2) => TaskEither<LeftType, T1[keyof T1]>, data: T3 ): TaskEither<LeftType, T3> export function dependFieldReplacer< T1, T2 extends string, T3 extends Record<T2, T1> >( field: T2, input: (data: T3, field: T2) => TaskEither<LeftType, T1[keyof T1]>, data?: T3 | ((x: T3) => boolean), data2?: T3 ) { const createTask = (prev: T3): TaskEither<LeftType, T3> => { return taskEither.chain(input(prev, field), iop => async () => { if (isFn(data) && !data(prev)) return right(prev) return right({ ...prev, [field]: iop }) }) } const actualData = isFn(data) ? data2 : data return actualData ? createTask(actualData) : createTask } export const btoa = (s: string) => Buffer.from(s).toString("base64") export const atob = (s: string) => Buffer.from(s, "base64").toString() export const NSSLASH = "\u2215" // used to be hardcoded as "/", aka "\uFF0F" export const convertSlash = (x: string) => x && x.replace(/\//g, NSSLASH) export const asyncFilter = async <T>( x: Iterable<T>, filter: (x: T) => any ): Promise<T[]> => { const res: T[] = [] for (const i of x) if (await filter(i)) res.push(i) return res } interface AdtUriPartsInternal { path: string type?: string name?: string start?: { line: number; character: number } end?: { line: number; character: number } } const splitPos = (pos: string) => { const [line = "0", char = "0"] = pos?.split(",") return { line: toInt(line), character: toInt(char) } } export const splitAdtUriInternal = (uri: string) => { const uriParts: AdtUriPartsInternal = { path: uri } const uparts = uri.match(/^([\w]+:\/\/)?([^#\?]+\/?)(?:\?([^#]*))?(?:#(.*))?/) if (uparts) { uriParts.path = uparts[2] const query = uparts[3] ? decodeURIComponent(uparts[3]) : "" const fragment = uparts[4] ? decodeURIComponent(uparts[4]) : "" if (query) { for (const part of query.split("&")) { const [name, value] = part.split("=") if (name === "start" || name === "end") uriParts[name] = splitPos(value) } } if (fragment) { for (const part of fragment.split(";")) { const [name, value] = part.split("=") if (name === "name" || name === "type") uriParts[name] = value if (name === "start" || name === "end") uriParts[name] = splitPos(value) } } } return uriParts } export const caughtToString = (e: any, defaultMsg: string = "") => { if (types.isNativeError(e)) return e.message if (typeof e === "object" && typeof e.toString === "function") return e.toString() if (typeof e === "object" && typeof e.message === "string") return e.message return defaultMsg || `${e}` }
the_stack
// clang-format off import 'chrome://settings/lazy_load.js'; import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {SecureDnsInputElement, SettingsSecureDnsElement} from 'chrome://settings/lazy_load.js'; import {PrivacyPageBrowserProxyImpl, ResolverOption, SecureDnsMode, SecureDnsUiManagementMode} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks} from 'chrome://webui-test/test_util.js'; import {TestPrivacyPageBrowserProxy} from './test_privacy_page_browser_proxy.js'; // clang-format on suite('SettingsSecureDnsInput', function() { let testBrowserProxy: TestPrivacyPageBrowserProxy; let testElement: SecureDnsInputElement; // Possible error messages const invalidFormat = 'invalid format description'; const probeFail = 'probe fail description'; const invalidEntry = 'invalid_entry'; const validFailEntry = 'https://example.server/dns-query'; const validSuccessEntry = 'https://example.server.another/dns-query'; suiteSetup(function() { loadTimeData.overrideValues({ secureDnsCustomFormatError: invalidFormat, secureDnsCustomConnectionError: probeFail, }); }); setup(function() { testBrowserProxy = new TestPrivacyPageBrowserProxy(); PrivacyPageBrowserProxyImpl.setInstance(testBrowserProxy); document.body.innerHTML = ''; testElement = document.createElement('secure-dns-input'); document.body.appendChild(testElement); flush(); assertFalse(testElement.$.input.invalid); assertEquals('', testElement.value); }); teardown(function() { testElement.remove(); }); test('SecureDnsInputEmpty', async function() { // Trigger validation on an empty input. testBrowserProxy.setParsedEntry([]); testElement.validate(); assertEquals('', await testBrowserProxy.whenCalled('parseCustomDnsEntry')); assertFalse(testElement.$.input.invalid); assertFalse(testElement.isInvalid()); }); test('SecureDnsInputValidFormatAndProbeFail', async function() { // Enter a valid server that fails the test query. testElement.value = validFailEntry; testBrowserProxy.setParsedEntry([validFailEntry]); testBrowserProxy.setProbeResults({[validFailEntry]: false}); testElement.validate(); assertEquals( validFailEntry, await testBrowserProxy.whenCalled('parseCustomDnsEntry')); assertEquals( validFailEntry, await testBrowserProxy.whenCalled('probeCustomDnsTemplate')); assertTrue(testElement.$.input.invalid); assertTrue(testElement.isInvalid()); assertEquals(probeFail, testElement.$.input.errorMessage); }); test('SecureDnsInputValidFormatAndProbeSuccess', async function() { // Enter a valid input and make the test query succeed. testElement.value = validSuccessEntry; testBrowserProxy.setParsedEntry([validSuccessEntry]); testBrowserProxy.setProbeResults({[validSuccessEntry]: true}); testElement.validate(); assertEquals( validSuccessEntry, await testBrowserProxy.whenCalled('parseCustomDnsEntry')); assertEquals( validSuccessEntry, await testBrowserProxy.whenCalled('probeCustomDnsTemplate')); assertFalse(testElement.$.input.invalid); assertFalse(testElement.isInvalid()); }); test('SecureDnsInputValidFormatAndProbeTwice', async function() { // Enter two valid servers but make the first one fail the test query. testElement.value = `${validFailEntry} ${validSuccessEntry}`; testBrowserProxy.setParsedEntry([validFailEntry, validSuccessEntry]); testBrowserProxy.setProbeResults({ [validFailEntry]: false, [validSuccessEntry]: true, }); testElement.validate(); assertEquals( `${validFailEntry} ${validSuccessEntry}`, await testBrowserProxy.whenCalled('parseCustomDnsEntry')); await flushTasks(); assertEquals(2, testBrowserProxy.getCallCount('probeCustomDnsTemplate')); assertFalse(testElement.$.input.invalid); assertFalse(testElement.isInvalid()); }); test('SecureDnsInputInvalid', async function() { // Enter an invalid input and trigger validation. testElement.value = invalidEntry; testBrowserProxy.setParsedEntry([]); testElement.validate(); assertEquals( invalidEntry, await testBrowserProxy.whenCalled('parseCustomDnsEntry')); assertTrue(testElement.$.input.invalid); assertTrue(testElement.isInvalid()); assertEquals(invalidFormat, testElement.$.input.errorMessage); // Trigger an input event and check that the error clears. testElement.$.input.fire('input'); assertFalse(testElement.$.input.invalid); assertFalse(testElement.isInvalid()); assertEquals(invalidEntry, testElement.value); }); }); suite('SettingsSecureDns', function() { let testBrowserProxy: TestPrivacyPageBrowserProxy; let testElement: SettingsSecureDnsElement; const resolverList: ResolverOption[] = [ {name: 'Custom', value: 'custom', policy: ''}, ]; // Possible subtitle overrides. const defaultDescription = 'default description'; const managedEnvironmentDescription = 'disabled for managed environment description'; const parentalControlDescription = 'disabled for parental control description'; /** * Checks that the radio buttons are shown and the toggle is properly * configured for showing the radio buttons. */ function assertRadioButtonsShown() { assertTrue(testElement.$.secureDnsToggle.hasAttribute('checked')); assertFalse(testElement.$.secureDnsToggle.$.control.disabled); assertFalse(testElement.$.secureDnsRadioGroup.hidden); } suiteSetup(function() { loadTimeData.overrideValues({ showSecureDnsSetting: true, secureDnsDescription: defaultDescription, secureDnsDisabledForManagedEnvironment: managedEnvironmentDescription, secureDnsDisabledForParentalControl: parentalControlDescription, }); }); setup(async function() { testBrowserProxy = new TestPrivacyPageBrowserProxy(); testBrowserProxy.setResolverList(resolverList); PrivacyPageBrowserProxyImpl.setInstance(testBrowserProxy); document.body.innerHTML = ''; testElement = document.createElement('settings-secure-dns'); testElement.prefs = { dns_over_https: {mode: {value: SecureDnsMode.AUTOMATIC}, templates: {value: ''}}, }; document.body.appendChild(testElement); await testBrowserProxy.whenCalled('getSecureDnsSetting'); await flushTasks(); assertRadioButtonsShown(); assertEquals( testBrowserProxy.secureDnsSetting.mode, testElement.$.secureDnsRadioGroup.selected); }); teardown(function() { testElement.remove(); }); test('SecureDnsOff', function() { webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.OFF, templates: [], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertFalse(testElement.$.secureDnsToggle.hasAttribute('checked')); assertFalse(testElement.$.secureDnsToggle.$.control.disabled); assertTrue(testElement.$.secureDnsRadioGroup.hidden); assertEquals(defaultDescription, testElement.$.secureDnsToggle.subLabel); assertFalse(!!testElement.$.secureDnsToggle.shadowRoot!.querySelector( 'cr-policy-pref-indicator')); }); test('SecureDnsAutomatic', function() { webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.AUTOMATIC, templates: [], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertRadioButtonsShown(); assertEquals(defaultDescription, testElement.$.secureDnsToggle.subLabel); assertFalse(!!testElement.$.secureDnsToggle.shadowRoot!.querySelector( 'cr-policy-pref-indicator')); assertEquals( SecureDnsMode.AUTOMATIC, testElement.$.secureDnsRadioGroup.selected); }); test('SecureDnsSecure', function() { webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.SECURE, templates: [], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertRadioButtonsShown(); assertEquals(defaultDescription, testElement.$.secureDnsToggle.subLabel); assertFalse(!!testElement.$.secureDnsToggle.shadowRoot!.querySelector( 'cr-policy-pref-indicator')); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); }); test('SecureDnsManagedEnvironment', function() { webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.OFF, templates: [], managementMode: SecureDnsUiManagementMode.DISABLED_MANAGED, }); flush(); assertFalse(testElement.$.secureDnsToggle.hasAttribute('checked')); assertTrue(testElement.$.secureDnsToggle.$.control.disabled); assertTrue(testElement.$.secureDnsRadioGroup.hidden); assertEquals( managedEnvironmentDescription, testElement.$.secureDnsToggle.subLabel); assertTrue(!!testElement.$.secureDnsToggle.shadowRoot!.querySelector( 'cr-policy-pref-indicator')); assertTrue(testElement.$.secureDnsToggle.shadowRoot! .querySelector('cr-policy-pref-indicator')!.shadowRoot! .querySelector('cr-tooltip-icon')!.hidden); }); test('SecureDnsParentalControl', function() { webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.OFF, templates: [], managementMode: SecureDnsUiManagementMode.DISABLED_PARENTAL_CONTROLS, }); flush(); assertFalse(testElement.$.secureDnsToggle.hasAttribute('checked')); assertTrue(testElement.$.secureDnsToggle.$.control.disabled); assertTrue(testElement.$.secureDnsRadioGroup.hidden); assertEquals( parentalControlDescription, testElement.$.secureDnsToggle.subLabel); assertTrue(!!testElement.$.secureDnsToggle.shadowRoot!.querySelector( 'cr-policy-pref-indicator')); assertTrue(testElement.$.secureDnsToggle.shadowRoot! .querySelector('cr-policy-pref-indicator')!.shadowRoot! .querySelector('cr-tooltip-icon')!.hidden); }); test('SecureDnsManaged', function() { testElement.prefs.dns_over_https.mode.enforcement = chrome.settingsPrivate.Enforcement.ENFORCED; testElement.prefs.dns_over_https.mode.controlledBy = chrome.settingsPrivate.ControlledBy.DEVICE_POLICY; webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.AUTOMATIC, templates: [], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertTrue(testElement.$.secureDnsToggle.hasAttribute('checked')); assertTrue(testElement.$.secureDnsToggle.$.control.disabled); assertTrue(testElement.$.secureDnsRadioGroup.hidden); assertEquals(defaultDescription, testElement.$.secureDnsToggle.subLabel); assertTrue(!!testElement.$.secureDnsToggle.shadowRoot!.querySelector( 'cr-policy-pref-indicator')); assertFalse(testElement.$.secureDnsToggle.shadowRoot! .querySelector('cr-policy-pref-indicator')!.shadowRoot! .querySelector('cr-tooltip-icon')!.hidden); }); });
the_stack
import * as protos from '../../protos/locations'; import * as assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it} from 'mocha'; import {LocationsClient} from '../../src/locationService'; import {GrpcClient} from '../../src/grpc'; import * as protobuf from 'protobufjs'; function generateSampleMessage<T extends object>(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message<T>, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject ) as T; } function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) { return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); } function stubSimpleCallWithCallback<ResponseType>( response?: ResponseType, error?: Error ) { return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); } function stubAsyncIterationCall<ResponseType>( responses?: ResponseType[], error?: Error ) { let counter = 0; const asyncIterable = { [Symbol.asyncIterator]() { return { async next() { if (error) { return Promise.reject(error); } if (counter >= responses!.length) { return Promise.resolve({done: true, value: undefined}); } return Promise.resolve({done: false, value: responses![counter++]}); }, }; }, }; return sinon.stub().returns(asyncIterable); } describe('LocationsClient', () => { describe('getLocation', () => { it('invokes getLocation without error', async () => { const grpcClient = new GrpcClient(); const client = new LocationsClient(grpcClient, { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.location.GetLocationRequest() ); request.name = ''; const expectedHeaderRequestParams = 'name='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.location.Location() ); client.innerApiCalls.getLocation = stubSimpleCall(expectedResponse); const response = await client.getLocation(request, expectedOptions); assert.deepStrictEqual(response, [expectedResponse]); assert( (client.innerApiCalls.getLocation as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes getLocation without error using callback', async () => { const grpcClient = new GrpcClient(); const client = new LocationsClient(grpcClient, { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.location.GetLocationRequest() ); request.name = ''; const expectedHeaderRequestParams = 'name='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.location.Location() ); client.innerApiCalls.getLocation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.getLocation( request, ( err?: Error | null, result?: protos.google.cloud.location.ILocation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.getLocation as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes getLocation with error', async () => { const grpcClient = new GrpcClient(); const client = new LocationsClient(grpcClient, { projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.location.GetLocationRequest() ); request.name = ''; const expectedHeaderRequestParams = 'name='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.getLocation = stubSimpleCall( undefined, expectedError ); await assert.rejects( client.getLocation(request, expectedOptions), expectedError ); assert( (client.innerApiCalls.getLocation as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('listLocations', () => { it('invokes listLocations without error', async () => { const grpcClient = new GrpcClient(); const client = new LocationsClient(grpcClient, { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest() ); request.name = ''; const expectedHeaderRequestParams = 'name='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage(new protos.google.cloud.location.Location()), generateSampleMessage(new protos.google.cloud.location.Location()), generateSampleMessage(new protos.google.cloud.location.Location()), ]; client.innerApiCalls.listLocations = stubSimpleCall(expectedResponse); const [response] = await client.listLocations(request, expectedOptions); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listLocations as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listLocations without error using callback', async () => { const grpcClient = new GrpcClient(); const client = new LocationsClient(grpcClient, { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest() ); request.name = ''; const expectedHeaderRequestParams = 'name='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage(new protos.google.cloud.location.Location()), generateSampleMessage(new protos.google.cloud.location.Location()), generateSampleMessage(new protos.google.cloud.location.Location()), ]; client.innerApiCalls.listLocations = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.listLocations( request, ( err?: Error | null, result?: protos.google.cloud.location.ILocation[] | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listLocations as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes listLocations with error', async () => { const grpcClient = new GrpcClient(); const client = new LocationsClient(grpcClient, { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest() ); request.name = ''; const expectedHeaderRequestParams = 'name='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.listLocations = stubSimpleCall( undefined, expectedError ); await assert.rejects( client.listLocations(request, expectedOptions), expectedError ); assert( (client.innerApiCalls.listLocations as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('uses async iteration with listLocations without error', async () => { const grpcClient = new GrpcClient(); const client = new LocationsClient(grpcClient, { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest() ); request.name = ''; const expectedHeaderRequestParams = 'name='; const expectedResponse = [ generateSampleMessage(new protos.google.cloud.location.Location()), generateSampleMessage(new protos.google.cloud.location.Location()), generateSampleMessage(new protos.google.cloud.location.Location()), ]; client.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(expectedResponse); const responses: protos.google.cloud.location.ILocation[] = []; const iterable = client.listLocationsAsync(request); for await (const resource of iterable) { responses.push(resource!); } assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with listLocations with error', async () => { const grpcClient = new GrpcClient(); const client = new LocationsClient(grpcClient, { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest() ); request.name = ''; const expectedHeaderRequestParams = 'name='; const expectedError = new Error('expected'); client.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); const iterable = client.listLocationsAsync(request); await assert.rejects(async () => { const responses: protos.google.cloud.location.ILocation[] = []; for await (const resource of iterable) { responses.push(resource!); } }); assert.deepStrictEqual( ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); }); });
the_stack
import { selectAllWidgetsInAreaAction, setCanvasSelectionStateAction, } from "actions/canvasSelectionActions"; import { throttle } from "lodash"; import React, { useEffect, useCallback, useRef } from "react"; import { useDispatch, useSelector } from "react-redux"; import { AppState } from "reducers"; import { APP_MODE } from "entities/App"; import { getWidget } from "sagas/selectors"; import { getAppMode } from "selectors/applicationSelectors"; import { getCurrentApplicationLayout, getCurrentPageId, } from "selectors/editorSelectors"; import styled from "styled-components"; import { getNearestParentCanvas } from "utils/generators"; import { useCanvasDragToScroll } from "utils/hooks/useCanvasDragToScroll"; import { MAIN_CONTAINER_WIDGET_ID } from "constants/WidgetConstants"; import { XYCord } from "utils/hooks/useCanvasDragging"; import { theme } from "constants/DefaultTheme"; import { commentModeSelector } from "../../selectors/commentsSelectors"; const StyledSelectionCanvas = styled.canvas` position: absolute; top: 0px; left: 0px; height: calc( 100% + ${(props) => props.id === "canvas-0" ? props.theme.canvasBottomPadding : 0}px ); width: 100%; overflow-y: auto; `; export interface SelectedArenaDimensions { top: number; left: number; width: number; height: number; } export function CanvasSelectionArena({ canExtend, parentId, snapColumnSpace, snapRows, snapRowSpace, widgetId, }: { canExtend: boolean; parentId?: string; snapColumnSpace: number; widgetId: string; snapRows: number; snapRowSpace: number; }) { const dispatch = useDispatch(); const isCommentMode = useSelector(commentModeSelector); const canvasRef = React.useRef<HTMLCanvasElement>(null); const parentWidget = useSelector((state: AppState) => getWidget(state, parentId || ""), ); const isDraggableParent = !( widgetId === MAIN_CONTAINER_WIDGET_ID || (parentWidget && parentWidget.detachFromLayout) ); const appMode = useSelector(getAppMode); const isDragging = useSelector( (state: AppState) => state.ui.widgetDragResize.isDragging, ); const isResizing = useSelector( (state: AppState) => state.ui.widgetDragResize.isResizing, ); const mainContainer = useSelector((state: AppState) => getWidget(state, widgetId), ); const currentPageId = useSelector(getCurrentPageId); const appLayout = useSelector(getCurrentApplicationLayout); const throttledWidgetSelection = useCallback( throttle( ( selectionDimensions: SelectedArenaDimensions, snapToNextColumn: boolean, snapToNextRow: boolean, isMultiSelect: boolean, ) => { dispatch( selectAllWidgetsInAreaAction( selectionDimensions, snapToNextColumn, snapToNextRow, isMultiSelect, { snapColumnSpace, snapRowSpace, }, ), ); }, 150, { leading: true, trailing: true, }, ), [widgetId, snapColumnSpace, snapRowSpace], ); const isDraggingForSelection = useSelector((state: AppState) => { return state.ui.canvasSelection.isDraggingForSelection; }); const isCurrentWidgetDrawing = useSelector((state: AppState) => { return state.ui.canvasSelection.widgetId === widgetId; }); const outOfCanvasStartPositions = useSelector((state: AppState) => { return state.ui.canvasSelection.outOfCanvasStartPositions; }); const defaultDrawOnObj = { canDraw: false, startPoints: undefined, }; const drawOnEnterObj = useRef<{ canDraw: boolean; startPoints?: XYCord; }>(defaultDrawOnObj); // start main container selection from widget editor useEffect(() => { const canDrawOnEnter = isDraggingForSelection && isCurrentWidgetDrawing && !!outOfCanvasStartPositions; drawOnEnterObj.current = { canDraw: canDrawOnEnter, startPoints: canDrawOnEnter ? outOfCanvasStartPositions : undefined, }; if (canvasRef.current && canDrawOnEnter) { canvasRef.current.style.zIndex = "2"; } }, [ isDraggingForSelection, isCurrentWidgetDrawing, outOfCanvasStartPositions, ]); useCanvasDragToScroll( canvasRef, isCurrentWidgetDrawing, isDraggingForSelection, snapRows, canExtend, ); useEffect(() => { if (appMode === APP_MODE.EDIT && !isDragging && canvasRef.current) { // ToDo: Needs a repositioning canvas window to limit the highest number of pixels rendered for an application of any height. // as of today (Pixels rendered by canvas) ∝ (Application height) so as height increases will run into to dead renders. // https://on690.codesandbox.io/ to check the number of pixels limit supported for a canvas // const { devicePixelRatio: scale = 1 } = window; const scale = 1; const scrollParent: Element | null = getNearestParentCanvas( canvasRef.current, ); const scrollObj: any = {}; let canvasCtx: any = canvasRef.current.getContext("2d"); const initRectangle = (): SelectedArenaDimensions => ({ top: 0, left: 0, width: 0, height: 0, }); let selectionRectangle: SelectedArenaDimensions = initRectangle(); let isMultiSelect = false; let isDragging = false; const getSelectionDimensions = () => { return { top: selectionRectangle.height < 0 ? selectionRectangle.top - Math.abs(selectionRectangle.height) : selectionRectangle.top, left: selectionRectangle.width < 0 ? selectionRectangle.left - Math.abs(selectionRectangle.width) : selectionRectangle.left, width: Math.abs(selectionRectangle.width), height: Math.abs(selectionRectangle.height), }; }; const selectWidgetsInit = ( selectionDimensions: SelectedArenaDimensions, isMultiSelect: boolean, ) => { if ( selectionDimensions.left && selectionDimensions.top && selectionDimensions.width && selectionDimensions.height ) { const snapToNextColumn = selectionRectangle.height < 0; const snapToNextRow = selectionRectangle.width < 0; throttledWidgetSelection( selectionDimensions, snapToNextColumn, snapToNextRow, isMultiSelect, ); } }; const drawRectangle = (selectionDimensions: SelectedArenaDimensions) => { const strokeWidth = 1; canvasCtx.setLineDash([5]); canvasCtx.strokeStyle = "rgba(125,188,255,1)"; canvasCtx.strokeRect( selectionDimensions.left - strokeWidth, selectionDimensions.top - strokeWidth, selectionDimensions.width + 2 * strokeWidth, selectionDimensions.height + 2 * strokeWidth, ); canvasCtx.fillStyle = "rgb(84, 132, 236, 0.06)"; canvasCtx.fillRect( selectionDimensions.left, selectionDimensions.top, selectionDimensions.width, selectionDimensions.height, ); }; const onMouseLeave = () => { if (widgetId === MAIN_CONTAINER_WIDGET_ID) { document.body.addEventListener("mouseup", onMouseUp, false); document.body.addEventListener("click", onClick, false); } }; const onMouseEnter = (e: any) => { if ( canvasRef.current && !isDragging && drawOnEnterObj?.current.canDraw ) { firstRender(e, true); drawOnEnterObj.current = defaultDrawOnObj; } else if (widgetId === MAIN_CONTAINER_WIDGET_ID) { document.body.removeEventListener("mouseup", onMouseUp); document.body.removeEventListener("click", onClick); } }; const onClick = (e: any) => { if ( Math.abs(selectionRectangle.height) + Math.abs(selectionRectangle.width) > 0 ) { if (!isDragging) { // cant set this in onMouseUp coz click seems to happen after onMouseUp. selectionRectangle = initRectangle(); } e.stopPropagation(); } }; const startPositionsForOutCanvasSelection = () => { const startPoints = drawOnEnterObj.current.startPoints; const startPositions = { top: 0, left: 0, }; if (canvasRef.current && startPoints) { const { height, left, top, width, } = canvasRef.current.getBoundingClientRect(); const outOfMaxBounds = { x: startPoints.x < left + width, y: startPoints.y < top + height, }; const outOfMinBounds = { x: startPoints.x > left, y: startPoints.y > top, }; const xInRange = outOfMaxBounds.x && outOfMinBounds.x; const yInRange = outOfMaxBounds.y && outOfMinBounds.y; const bufferFromBoundary = 2; startPositions.left = xInRange ? startPoints.x - left : outOfMinBounds.x ? width - bufferFromBoundary : bufferFromBoundary; startPositions.top = yInRange ? startPoints.y - top : outOfMinBounds.y ? height - bufferFromBoundary : bufferFromBoundary; } return startPositions; }; const firstRender = (e: any, fromOuterCanvas = false) => { if (canvasRef.current && !isDragging) { isMultiSelect = e.ctrlKey || e.metaKey || e.shiftKey; if (fromOuterCanvas) { const { left, top } = startPositionsForOutCanvasSelection(); selectionRectangle.left = left; selectionRectangle.top = top; } else { selectionRectangle.left = e.offsetX - canvasRef.current.offsetLeft; selectionRectangle.top = e.offsetY - canvasRef.current.offsetTop; } selectionRectangle.width = 0; selectionRectangle.height = 0; isDragging = true; // bring the canvas to the top layer canvasRef.current.style.zIndex = "2"; } }; const onMouseDown = (e: any) => { if ( canvasRef.current && (!isDraggableParent || e.ctrlKey || e.metaKey) ) { dispatch(setCanvasSelectionStateAction(true, widgetId)); firstRender(e); } }; const onMouseUp = () => { if (isDragging && canvasRef.current) { isDragging = false; canvasCtx.clearRect( 0, 0, canvasRef.current.width, canvasRef.current.height, ); canvasRef.current.style.zIndex = ""; dispatch(setCanvasSelectionStateAction(false, widgetId)); } }; const onMouseMove = (e: any) => { if (isDragging && canvasRef.current) { selectionRectangle.width = e.offsetX - canvasRef.current.offsetLeft - selectionRectangle.left; selectionRectangle.height = e.offsetY - canvasRef.current.offsetTop - selectionRectangle.top; canvasCtx.clearRect( 0, 0, canvasRef.current.width, canvasRef.current.height, ); const selectionDimensions = getSelectionDimensions(); drawRectangle(selectionDimensions); selectWidgetsInit(selectionDimensions, isMultiSelect); scrollObj.lastMouseMoveEvent = e; scrollObj.lastScrollTop = scrollParent?.scrollTop; scrollObj.lastScrollHeight = scrollParent?.scrollHeight; } }; const onScroll = () => { const { lastMouseMoveEvent, lastScrollHeight, lastScrollTop, } = scrollObj; if ( lastMouseMoveEvent && Number.isInteger(lastScrollHeight) && Number.isInteger(lastScrollTop) && scrollParent ) { const delta = scrollParent?.scrollHeight + scrollParent?.scrollTop - (lastScrollHeight + lastScrollTop); onMouseMove({ offsetX: lastMouseMoveEvent.offsetX, offsetY: lastMouseMoveEvent.offsetY + delta, }); } }; const addEventListeners = () => { canvasRef.current?.addEventListener("click", onClick, false); canvasRef.current?.addEventListener("mousedown", onMouseDown, false); canvasRef.current?.addEventListener("mouseup", onMouseUp, false); canvasRef.current?.addEventListener("mousemove", onMouseMove, false); canvasRef.current?.addEventListener("mouseleave", onMouseLeave, false); canvasRef.current?.addEventListener("mouseenter", onMouseEnter, false); scrollParent?.addEventListener("scroll", onScroll, false); }; const removeEventListeners = () => { canvasRef.current?.removeEventListener("mousedown", onMouseDown); canvasRef.current?.removeEventListener("mouseup", onMouseUp); canvasRef.current?.removeEventListener("mousemove", onMouseMove); canvasRef.current?.removeEventListener("mouseleave", onMouseLeave); canvasRef.current?.removeEventListener("mouseenter", onMouseEnter); canvasRef.current?.removeEventListener("click", onClick); }; const init = () => { if (canvasRef.current) { const { height, width } = canvasRef.current.getBoundingClientRect(); if (height && width) { canvasRef.current.width = width * scale; canvasRef.current.height = (snapRows * snapRowSpace + (widgetId === MAIN_CONTAINER_WIDGET_ID ? theme.canvasBottomPadding : 0)) * scale; } canvasCtx = canvasRef.current.getContext("2d"); canvasCtx.scale(scale, scale); removeEventListeners(); addEventListeners(); } }; if (appMode === APP_MODE.EDIT) { init(); } return () => { removeEventListeners(); }; } }, [ appLayout, currentPageId, mainContainer, isDragging, isResizing, isCommentMode, snapRows, snapColumnSpace, snapRowSpace, ]); const shouldShow = appMode === APP_MODE.EDIT && !(isDragging || isResizing || isCommentMode); return shouldShow ? ( <StyledSelectionCanvas data-testid={`canvas-${widgetId}`} id={`canvas-${widgetId}`} ref={canvasRef} /> ) : null; } CanvasSelectionArena.displayName = "CanvasSelectionArena";
the_stack
import type { Patch } from 'immer'; import { EthereumRpcError, ethErrors } from 'eth-rpc-errors'; import { nanoid } from 'nanoid'; import { BaseController, Json } from '../BaseControllerV2'; import type { RestrictedControllerMessenger } from '../ControllerMessenger'; const controllerName = 'ApprovalController'; type ApprovalPromiseResolve = (value?: unknown) => void; type ApprovalPromiseReject = (error?: Error) => void; type ApprovalRequestData = Record<string, Json> | null; type ApprovalCallbacks = { resolve: ApprovalPromiseResolve; reject: ApprovalPromiseReject; }; export type ApprovalRequest<RequestData extends ApprovalRequestData> = { /** * The ID of the approval request. */ id: string; /** * The origin of the approval request. */ origin: string; /** * The time that the request was received, per Date.now(). */ time: number; /** * The type of the approval request. */ type: string; /** * Additional data associated with the request. * TODO:TS4.4 make optional */ requestData: RequestData; }; type ShowApprovalRequest = () => void | Promise<void>; export type ApprovalControllerState = { pendingApprovals: Record<string, ApprovalRequest<Record<string, Json>>>; pendingApprovalCount: number; }; const stateMetadata = { pendingApprovals: { persist: false, anonymous: true }, pendingApprovalCount: { persist: false, anonymous: false }, }; const getAlreadyPendingMessage = (origin: string, type: string) => `Request of type '${type}' already pending for origin ${origin}. Please wait.`; const getDefaultState = (): ApprovalControllerState => { return { pendingApprovals: {}, pendingApprovalCount: 0, }; }; export type GetApprovalsState = { type: `${typeof controllerName}:getState`; handler: () => ApprovalControllerState; }; export type ClearApprovalRequests = { type: `${typeof controllerName}:clearRequests`; handler: (error: EthereumRpcError<unknown>) => void; }; type AddApprovalOptions = { id?: string; origin: string; type: string; requestData?: Record<string, Json>; }; export type AddApprovalRequest = { type: `${typeof controllerName}:addRequest`; handler: ( opts: AddApprovalOptions, shouldShowRequest: boolean, ) => ReturnType<ApprovalController['add']>; }; export type HasApprovalRequest = { type: `${typeof controllerName}:hasRequest`; handler: ApprovalController['has']; }; export type AcceptRequest = { type: `${typeof controllerName}:acceptRequest`; handler: ApprovalController['accept']; }; export type RejectRequest = { type: `${typeof controllerName}:rejectRequest`; handler: ApprovalController['reject']; }; export type ApprovalControllerActions = | GetApprovalsState | ClearApprovalRequests | AddApprovalRequest | HasApprovalRequest | AcceptRequest | RejectRequest; export type ApprovalStateChange = { type: `${typeof controllerName}:stateChange`; payload: [ApprovalControllerState, Patch[]]; }; export type ApprovalControllerEvents = ApprovalStateChange; export type ApprovalControllerMessenger = RestrictedControllerMessenger< typeof controllerName, ApprovalControllerActions, ApprovalControllerEvents, never, never >; type ApprovalControllerOptions = { messenger: ApprovalControllerMessenger; showApprovalRequest: ShowApprovalRequest; state?: Partial<ApprovalControllerState>; }; /** * Controller for managing requests that require user approval. * * Enables limiting the number of pending requests by origin and type, counting * pending requests, and more. * * Adding a request returns a promise that resolves or rejects when the request * is approved or denied, respectively. */ export class ApprovalController extends BaseController< typeof controllerName, ApprovalControllerState, ApprovalControllerMessenger > { private _approvals: Map<string, ApprovalCallbacks>; private _origins: Map<string, Set<string>>; private _showApprovalRequest: () => void; /** * Construct an Approval controller. * * @param options - The controller options. * @param options.showApprovalRequest - Function for opening the UI such that * the request can be displayed to the user. * @param options.messenger - The restricted controller messenger for the Approval controller. * @param options.state - The initial controller state. */ constructor({ messenger, showApprovalRequest, state = {}, }: ApprovalControllerOptions) { super({ name: controllerName, metadata: stateMetadata, messenger, state: { ...getDefaultState(), ...state }, }); this._approvals = new Map(); this._origins = new Map(); this._showApprovalRequest = showApprovalRequest; this.registerMessageHandlers(); } /** * Constructor helper for registering this controller's messaging system * actions. */ private registerMessageHandlers(): void { this.messagingSystem.registerActionHandler( `${controllerName}:clearRequests` as const, this.clear.bind(this), ); this.messagingSystem.registerActionHandler( `${controllerName}:addRequest` as const, (opts: AddApprovalOptions, shouldShowRequest: boolean) => { if (shouldShowRequest) { return this.addAndShowApprovalRequest(opts); } return this.add(opts); }, ); this.messagingSystem.registerActionHandler( `${controllerName}:hasRequest` as const, this.has.bind(this), ); this.messagingSystem.registerActionHandler( `${controllerName}:acceptRequest` as const, this.accept.bind(this), ); this.messagingSystem.registerActionHandler( `${controllerName}:rejectRequest` as const, this.reject.bind(this), ); } /** * Adds an approval request per the given arguments, calls the show approval * request function, and returns the associated approval promise. * * There can only be one approval per origin and type. An error is thrown if * attempting to add an invalid or duplicate request. * * @param opts - Options bag. * @param opts.id - The id of the approval request. A random id will be * generated if none is provided. * @param opts.origin - The origin of the approval request. * @param opts.type - The type associated with the approval request. * @param opts.requestData - Additional data associated with the request, * if any. * @returns The approval promise. */ addAndShowApprovalRequest(opts: AddApprovalOptions): Promise<unknown> { const promise = this._add( opts.origin, opts.type, opts.id, opts.requestData, ); this._showApprovalRequest(); return promise; } /** * Adds an approval request per the given arguments and returns the approval * promise. * * There can only be one approval per origin and type. An error is thrown if * attempting to add an invalid or duplicate request. * * @param opts - Options bag. * @param opts.id - The id of the approval request. A random id will be * generated if none is provided. * @param opts.origin - The origin of the approval request. * @param opts.type - The type associated with the approval request. * @param opts.requestData - Additional data associated with the request, * if any. * @returns The approval promise. */ add(opts: AddApprovalOptions): Promise<unknown> { return this._add(opts.origin, opts.type, opts.id, opts.requestData); } /** * Gets the info for the approval request with the given id. * * @param id - The id of the approval request. * @returns The approval request data associated with the id. */ get(id: string): ApprovalRequest<ApprovalRequestData> | undefined { return this.state.pendingApprovals[id]; } /** * Gets the number of pending approvals, by origin and/or type. * * If only `origin` is specified, all approvals for that origin will be * counted, regardless of type. * If only `type` is specified, all approvals for that type will be counted, * regardless of origin. * If both `origin` and `type` are specified, 0 or 1 will be returned. * * @param opts - The approval count options. * @param opts.origin - An approval origin. * @param opts.type - The type of the approval request. * @returns The current approval request count for the given origin and/or * type. */ getApprovalCount(opts: { origin?: string; type?: string } = {}): number { if (!opts.origin && !opts.type) { throw new Error('Must specify origin, type, or both.'); } const { origin, type: _type } = opts; if (origin && _type) { return Number(Boolean(this._origins.get(origin)?.has(_type))); } if (origin) { return this._origins.get(origin)?.size || 0; } // Only "type" was specified let count = 0; for (const approval of Object.values(this.state.pendingApprovals)) { if (approval.type === _type) { count += 1; } } return count; } /** * Get the total count of all pending approval requests for all origins. * * @returns The total pending approval request count. */ getTotalApprovalCount(): number { return this.state.pendingApprovalCount; } /** * Checks if there's a pending approval request per the given parameters. * At least one parameter must be specified. An error will be thrown if the * parameters are invalid. * * If `id` is specified, all other parameters will be ignored. * If `id` is not specified, the method will check for requests that match * all of the specified parameters. * * @param opts - Options bag. * @param opts.id - The ID to check for. * @param opts.origin - The origin to check for. * @param opts.type - The type to check for. * @returns `true` if a matching approval is found, and `false` otherwise. */ has(opts: { id?: string; origin?: string; type?: string } = {}): boolean { const { id, origin, type: _type } = opts; if (id) { if (typeof id !== 'string') { throw new Error('May not specify non-string id.'); } return this._approvals.has(id); } if (_type && typeof _type !== 'string') { throw new Error('May not specify non-string type.'); } if (origin) { if (typeof origin !== 'string') { throw new Error('May not specify non-string origin.'); } // Check origin and type pair if type also specified if (_type) { return Boolean(this._origins.get(origin)?.has(_type)); } return this._origins.has(origin); } if (_type) { for (const approval of Object.values(this.state.pendingApprovals)) { if (approval.type === _type) { return true; } } return false; } throw new Error( 'Must specify a valid combination of id, origin, and type.', ); } /** * Resolves the promise of the approval with the given id, and deletes the * approval. Throws an error if no such approval exists. * * @param id - The id of the approval request. * @param value - The value to resolve the approval promise with. */ accept(id: string, value?: unknown): void { this._deleteApprovalAndGetCallbacks(id).resolve(value); } /** * Rejects the promise of the approval with the given id, and deletes the * approval. Throws an error if no such approval exists. * * @param id - The id of the approval request. * @param error - The error to reject the approval promise with. */ reject(id: string, error: Error): void { this._deleteApprovalAndGetCallbacks(id).reject(error); } /** * Rejects and deletes all approval requests. * * @param rejectionError - The EthereumRpcError to reject the approval * requests with. */ clear(rejectionError: EthereumRpcError<unknown>): void { for (const id of this._approvals.keys()) { this.reject(id, rejectionError); } this._origins.clear(); this.update(() => getDefaultState()); } /** * Implementation of add operation. * * @param origin - The origin of the approval request. * @param type - The type associated with the approval request. * @param id - The id of the approval request. * @param requestData - The request data associated with the approval request. * @returns The approval promise. */ private _add( origin: string, type: string, id: string = nanoid(), requestData?: Record<string, Json>, ): Promise<unknown> { this._validateAddParams(id, origin, type, requestData); if (this._origins.get(origin)?.has(type)) { throw ethErrors.rpc.resourceUnavailable( getAlreadyPendingMessage(origin, type), ); } // add pending approval return new Promise((resolve, reject) => { this._approvals.set(id, { resolve, reject }); this._addPendingApprovalOrigin(origin, type); this._addToStore(id, origin, type, requestData); }); } /** * Validates parameters to the add method. * * @param id - The id of the approval request. * @param origin - The origin of the approval request. * @param type - The type associated with the approval request. * @param requestData - The request data associated with the approval request. */ private _validateAddParams( id: string, origin: string, type: string, requestData?: Record<string, Json>, ): void { let errorMessage = null; if (!id || typeof id !== 'string') { errorMessage = 'Must specify non-empty string id.'; } else if (this._approvals.has(id)) { errorMessage = `Approval request with id '${id}' already exists.`; } else if (!origin || typeof origin !== 'string') { errorMessage = 'Must specify non-empty string origin.'; } else if (!type || typeof type !== 'string') { errorMessage = 'Must specify non-empty string type.'; } else if ( requestData && (typeof requestData !== 'object' || Array.isArray(requestData)) ) { errorMessage = 'Request data must be a plain object if specified.'; } if (errorMessage) { throw ethErrors.rpc.internal(errorMessage); } } /** * Adds an entry to _origins. * Performs no validation. * * @param origin - The origin of the approval request. * @param type - The type associated with the approval request. */ private _addPendingApprovalOrigin(origin: string, type: string): void { const originSet = this._origins.get(origin) || new Set(); originSet.add(type); if (!this._origins.has(origin)) { this._origins.set(origin, originSet); } } /** * Adds an entry to the store. * Performs no validation. * * @param id - The id of the approval request. * @param origin - The origin of the approval request. * @param type - The type associated with the approval request. * @param requestData - The request data associated with the approval request. */ private _addToStore( id: string, origin: string, type: string, requestData?: Record<string, Json>, ): void { const approval: ApprovalRequest<Record<string, Json> | null> = { id, origin, type, time: Date.now(), requestData: requestData || null, }; this.update((draftState) => { // Typecast: ts(2589) draftState.pendingApprovals[id] = approval as any; draftState.pendingApprovalCount = Object.keys( draftState.pendingApprovals, ).length; }); } /** * Deletes the approval with the given id. The approval promise must be * resolved or reject before this method is called. * Deletion is an internal operation because approval state is solely * managed by this controller. * * @param id - The id of the approval request to be deleted. */ private _delete(id: string): void { this._approvals.delete(id); // This method is only called after verifying that the approval with the // specified id exists. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { origin, type } = this.state.pendingApprovals[id]!; (this._origins.get(origin) as Set<string>).delete(type); if (this._isEmptyOrigin(origin)) { this._origins.delete(origin); } this.update((draftState) => { delete draftState.pendingApprovals[id]; draftState.pendingApprovalCount = Object.keys( draftState.pendingApprovals, ).length; }); } /** * Gets the approval callbacks for the given id, deletes the entry, and then * returns the callbacks for promise resolution. * Throws an error if no approval is found for the given id. * * @param id - The id of the approval request. * @returns The promise callbacks associated with the approval request. */ private _deleteApprovalAndGetCallbacks(id: string): ApprovalCallbacks { const callbacks = this._approvals.get(id); if (!callbacks) { throw new Error(`Approval request with id '${id}' not found.`); } this._delete(id); return callbacks; } /** * Checks whether there are any approvals associated with the given * origin. * * @param origin - The origin to check. * @returns True if the origin has no approvals, false otherwise. */ private _isEmptyOrigin(origin: string): boolean { return !this._origins.get(origin)?.size; } } export default ApprovalController;
the_stack
'use strict'; import * as crypto from 'crypto'; import { SimpleCallback, StringCallback, AuthRequest, TokenRequest, OAuth2Request, AccessToken, AccessTokenCallback } from '../common/types'; import { WickedApplication, WickedClientType, WickedSubscription, KongApi, WickedApi, Callback } from 'wicked-sdk'; const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:oauth2'); const async = require('async'); import * as wicked from 'wicked-sdk'; const request = require('request'); import { utils } from '../common/utils'; import { kongUtils } from './kong-utils'; import { failOAuth } from '../common/utils-fail'; // We need this to accept self signed and Let's Encrypt certificates var https = require('https'); var agentOptions = { rejectUnauthorized: false }; var sslAgent = new https.Agent(agentOptions); // interface InputData { // grant_type?: string, // response_type?: string, // authenticated_userid: string, // auth_method: string, // api_id: string, // client_id?: string, // client_secret?: string, // refresh_token?: string, // code?: string, // scope: string[], // session_data?: string // } // interface SubscriptionInfo { // application: string, // api: string, // auth: string, // plan: string, // clientId: string, // clientSecret: string, // trusted: boolean // } // interface ApplicationInfo { // id: string, // name: string // redirectUri: string, // confidential: boolean // } interface ConsumerInfo { id: string, username: string, custom_id: string } interface KongOAuth2Config { provision_key: string, enable_client_credentials: boolean, enable_implicit_grant: boolean, enable_authorization_code: boolean, enable_password_grant: boolean } interface OAuthInfo { inputData: OAuth2Request, oauth2Config: KongOAuth2Config, provisionKey: string, subsInfo: WickedSubscription, appInfo: WickedApplication, consumer: ConsumerInfo, apiInfo: KongApi, } interface OAuthInfoCallback { (err, oauthInfo?: OAuthInfo): void } interface AuthorizeOAuthInfo extends OAuthInfo { inputData: AuthRequest, redirectUri?: string } interface TokenOAuthInfo extends OAuthInfo { inputData: TokenRequest, accessToken?: AccessToken } interface AuthorizeOAuthInfoCallback { (err, oauthInfo?: AuthorizeOAuthInfo): void } interface TokenOAuthInfoCallback { (err, oauthInfo?: TokenOAuthInfo): void } interface RedirectUri { redirect_uri: string, session_data?: string } interface RedirectUriCallback { (err, authorizeData?: RedirectUri): void } interface RequestHeaders { [name: string]: string } interface AuthorizeRequestPayload { url: string, headers: RequestHeaders, agent: any, json: boolean, body: object } interface AuthorizeRequestPayloadCallback { (err, authorizeRequest?: AuthorizeRequestPayload): void } interface TokenKongInvoker { (oauthInfo: OAuthInfo, callback: TokenOAuthInfoCallback): void } interface AuthorizeKongInvoker { (oauthInfo: OAuthInfo, callback: AuthorizeOAuthInfoCallback): void } interface TokenRequestPayload { url: string, headers: RequestHeaders, agent: any, json: boolean, body: object } interface TokenRequestPayloadCallback { (err, tokenRequest?: TokenRequestPayload): void } export const oauth2 = { authorize: function (inputData: AuthRequest, callback: RedirectUriCallback) { validateResponseType(inputData, function (err) { if (err) return callback(err); switch (inputData.response_type) { case 'token': return authorizeImplicit(inputData, callback); case 'code': return authorizeAuthorizationCode(inputData, callback); } return failOAuth(400, 'invalid_request', 'unknown error or response_type invalid.', callback); }); }, tokenAsync: function (inputData: TokenRequest): Promise<AccessToken> { const instance = this; return new Promise<AccessToken>(function (resolve, reject) { instance.token(inputData, function (err, accessToken) { err ? reject(err) : resolve(accessToken); }) }); }, token: function (inputData: TokenRequest, callback: AccessTokenCallback) { validateGrantType(inputData, function (err) { if (err) return callback(err); function appendScopeIfNeeded(err, accessToken) { if (err) return callback(err); if (inputData.scope_differs) { if (!inputData.scope) accessToken.scope = ''; else accessToken.scope = inputData.scope.join(' '); } return callback(null, accessToken); } switch (inputData.grant_type) { case 'client_credentials': return tokenClientCredentials(inputData, appendScopeIfNeeded); case 'authorization_code': return tokenAuthorizationCode(inputData, appendScopeIfNeeded); case 'refresh_token': return tokenRefreshToken(inputData, appendScopeIfNeeded); case 'password': return tokenPasswordGrant(inputData, appendScopeIfNeeded); } return failOAuth(400, 'invalid_request', 'unknown error or grant_type invalid', callback); }); } }; // ----------------------------------- function validateResponseType(inputData: AuthRequest, callback: SimpleCallback) { debug('validateResponseType()'); debug('responseType: ' + inputData.response_type); if (!inputData.response_type) return failOAuth(400, 'invalid_request', 'response_type is missing', callback); if (!inputData.auth_method) return failOAuth(400, 'invalid_request', 'auth_method is missing', callback); if (!inputData.api_id) return failOAuth(400, 'invalid_request', 'api_id is missing', callback); switch (inputData.response_type) { case "token": case "code": return callback(null); } return failOAuth(400, 'unsupported_response_type', `invalid response_type '${inputData.response_type}'`, callback); } function validateGrantType(inputData: TokenRequest, callback: SimpleCallback) { debug('validateGrantType()'); debug(`grant_type: ${inputData.grant_type}`); if (!inputData.grant_type) return failOAuth(400, 'invalid_request', 'grant_type is missing', callback); if (!inputData.auth_method) return failOAuth(400, 'invalid_request', 'auth_method is missing', callback); if (!inputData.api_id) return failOAuth(400, 'invalid_request', 'api_id is missing', callback); switch (inputData.grant_type) { case 'authorization_code': case 'client_credentials': case 'refresh_token': case 'password': return callback(null); } return failOAuth(400, 'invalid_request', `invalid grant_type ${inputData.grant_type}`, callback); } // ----------------------------------- // IMPLICIT GRANT // ----------------------------------- function authorizeImplicit(inputData: AuthRequest, callback: RedirectUriCallback) { debug('authorizeImplicit()'); // debug(inputData); async.series({ validate: function (callback) { validateImplicit(inputData, callback); }, redirectUri: function (callback) { authorizeImplicitInternal(inputData, callback); } }, function (err, results) { if (err) return callback(err); // Fetch result of authorizeImplicitInternal const returnValue = { redirect_uri: results.redirectUri, session_data: null }; // If session_data was provided, also return it if (inputData.session_data) returnValue.session_data = inputData.session_data; callback(null, returnValue); }); } function validateImplicit(inputData: AuthRequest, callback: SimpleCallback) { debug('validateImplicit()'); debug('authRequest: ' + JSON.stringify(inputData)); if (!inputData.client_id) return failOAuth(400, 'invalid_request', 'client_id is missing', callback); if (inputData.client_secret) return failOAuth(400, 'invalid_request', 'client_secret must not be passed in', callback); if (!inputData.authenticated_userid) return failOAuth(400, 'invalid_request', 'authenticated_userid is missing', callback); if (inputData.scope) { if ((typeof (inputData.scope) !== 'string') && !Array.isArray(inputData.scope)) return failOAuth(400, 'invalid_scope', 'scope has to be either a string or a string array', callback); } callback(null); } function authorizeImplicitInternal(inputData: AuthRequest, callback: StringCallback) { debug('authorizeImplicitInternal()'); return authorizeFlow(inputData, authorizeImplicitKong, callback); } function authorizeImplicitKong(oauthInfo: AuthorizeOAuthInfo, callback: AuthorizeOAuthInfoCallback) { debug('authorizeImplicitKong()'); // Check that the API is configured for implicit grant if (!oauthInfo.oauth2Config || !oauthInfo.oauth2Config.enable_implicit_grant) { return failOAuth(401, 'unauthorized_client', 'The API ' + oauthInfo.inputData.api_id + ' is not configured for the OAuth2 implicit grant', callback); } return authorizeWithKong(oauthInfo, 'token', callback); } // ----------------------------------- // AUTHORIZATION CODE GRANT - AUTHORIZE // ----------------------------------- function authorizeAuthorizationCode(inputData: AuthRequest, callback: RedirectUriCallback) { debug('authorizeAuthorizationCode()'); debug(inputData); async.series({ validate: function (callback) { validateAuthorizationCode(inputData, callback); }, redirectUri: function (callback) { authorizeAuthorizationCodeInternal(inputData, callback); } }, function (err, results) { if (err) return callback(err); // Fetch result of authorizeAuthorizationCodeInternal const returnValue = { redirect_uri: results.redirectUri, session_data: null }; // If session_data was provided, also return it if (inputData.session_data) returnValue.session_data = inputData.session_data; callback(null, returnValue); }); } function validateAuthorizationCode(inputData: AuthRequest, callback: SimpleCallback) { debug('validateAuthorizationCode()'); debug('inputData: ' + JSON.stringify(inputData)); if (!inputData.client_id) return failOAuth(400, 'invalid_request', 'client_id is missing', callback); if (inputData.client_secret) return failOAuth(400, 'invalid_request', 'client_secret must not be passed in', callback); if (!inputData.authenticated_userid) return failOAuth(400, 'invalid_request', 'authenticated_userid is missing', callback); if (inputData.scope) { if ((typeof (inputData.scope) !== 'string') && !Array.isArray(inputData.scope)) return failOAuth(400, 'invalid_scope', 'scope has to be either a string or a string array', callback); } callback(null); } function authorizeAuthorizationCodeInternal(inputData: AuthRequest, callback: StringCallback) { debug('authorizeAuthorizationCodeInternal()'); return authorizeFlow(inputData, authorizeAuthorizationCodeKong, callback); } function authorizeAuthorizationCodeKong(oauthInfo: AuthorizeOAuthInfo, callback: AuthorizeOAuthInfoCallback) { debug('authorizeAuthorizationCodeKong()'); // Check that the API is configured for authorization code grant if (!oauthInfo.oauth2Config || !oauthInfo.oauth2Config.enable_authorization_code) return failOAuth(401, 'unauthorized_client', 'The API ' + oauthInfo.inputData.api_id + ' is not configured for the OAuth2 Authorization Code grant.', callback); return authorizeWithKong(oauthInfo, 'code', callback); } function authorizeWithKong(oauthInfo: AuthorizeOAuthInfo, responseType: string, callback: AuthorizeOAuthInfoCallback) { debug('authorizeWithKong()'); async.waterfall([ callback => createAuthorizeRequest(responseType, oauthInfo, callback), (authorizeRequest, callback) => postAuthorizeRequest(authorizeRequest, callback) ], function (err, redirectUri) { if (err) return callback(err); oauthInfo.redirectUri = redirectUri; return callback(null, oauthInfo); }); } // ----------------------------------- // AUTHORIZATION CODE GRANT - TOKEN // ----------------------------------- function tokenAuthorizationCode(inputData: TokenRequest, callback: AccessTokenCallback): void { debug('tokenAuthorizationCode()'); debug(inputData); async.series({ validate: function (callback) { validateTokenAuthorizationCode(inputData, callback); }, accessToken: function (callback) { tokenAuthorizationCodeInternal(inputData, callback); } }, function (err, result) { if (err) return callback(err); return callback(null, result.accessToken); }); } function validateTokenAuthorizationCode(inputData: TokenRequest, callback: SimpleCallback): void { debug('validateTokenAuthorizationCode()'); if (!inputData.client_id) return failOAuth(400, 'invalid_request', 'client_id is missing', callback); if (!inputData.client_secret && !inputData.code_verifier) return failOAuth(400, 'invalid_request', 'client_secret or code_verifier is missing', callback); if (!inputData.code) return failOAuth(400, 'invalid_request', 'code is missing', callback); callback(null); } function tokenAuthorizationCodeInternal(inputData: TokenRequest, callback: AccessTokenCallback) { debug('tokenAuthorizationCodeInternal()'); return tokenFlow(inputData, tokenAuthorizationCodeKong, callback); } function tokenAuthorizationCodeKong(oauthInfo: TokenOAuthInfo, callback: TokenOAuthInfoCallback) { debug(oauthInfo.oauth2Config); if (!oauthInfo.oauth2Config || !oauthInfo.oauth2Config.enable_authorization_code) return failOAuth(401, 'unauthorized_client', 'The API ' + oauthInfo.inputData.api_id + ' is not configured for the OAuth2 authorization code grant.', callback); return tokenWithKong(oauthInfo, 'authorization_code', callback); } function tokenWithKong(oauthInfo: TokenOAuthInfo, grantType: string, callback: TokenOAuthInfoCallback) { async.waterfall([ callback => createTokenRequest(grantType, oauthInfo, callback), (tokenRequest, callback) => postTokenRequest(tokenRequest, callback) ], function (err, accessToken) { if (err) return callback(err); oauthInfo.accessToken = accessToken; return callback(null, oauthInfo); }); } // ----------------------------------- // CLIENT CREDENTIALS // ----------------------------------- function tokenClientCredentials(inputData: TokenRequest, callback: AccessTokenCallback) { debug('tokenClientCredentials()'); debug(inputData); async.series({ validate: function (callback: SimpleCallback) { validateClientCredentials(inputData, callback); }, accessToken: function (callback: AccessTokenCallback) { tokenClientCredentialsInternal(inputData, callback); } }, function (err, result) { if (err) return callback(err); const returnValue = result.accessToken as AccessToken; // If session_data was provided, also return it if (inputData.session_data) returnValue.session_data = inputData.session_data; return callback(null, returnValue); }); } function validateClientCredentials(inputData: TokenRequest, callback: SimpleCallback) { debug('validateClientCredentials()'); if (!inputData.client_id) return failOAuth(400, 'invalid_request', 'client_id is missing', callback); if (!inputData.client_secret) return failOAuth(400, 'invalid_request', 'client_secret is missing', callback); if (inputData.scope) { if ((typeof (inputData.scope) !== 'string') && !Array.isArray(inputData.scope)) return failOAuth(400, 'invalid_scope', 'scope has to be either a string or a string array', callback); } callback(null); } function tokenClientCredentialsInternal(inputData: TokenRequest, callback: AccessTokenCallback) { return tokenFlow(inputData, tokenClientCredentialsKong, callback); } function tokenClientCredentialsKong(oauthInfo: TokenOAuthInfo, callback: TokenOAuthInfoCallback) { debug('tokenClientCredentialsKong()'); debug(oauthInfo.oauth2Config); if (!oauthInfo.oauth2Config || !oauthInfo.oauth2Config.enable_client_credentials) return failOAuth(401, 'unauthorized_client', 'The API ' + oauthInfo.inputData.api_id + ' is not configured for the OAuth2 client credentials grant.', callback); return tokenWithKong(oauthInfo, 'client_credentials', callback); } // ----------------------------------- // RESOURCE OWNER PASSWORD GRANT // ----------------------------------- function tokenPasswordGrant(inputData: TokenRequest, callback: AccessTokenCallback) { debug('tokenPasswordGrant()'); debug(inputData); async.series({ validate: function (callback) { validatePasswordGrant(inputData, callback); }, accessToken: function (callback) { tokenPasswordGrantInternal(inputData, callback); } }, function (err, result) { if (err) return callback(err); const returnValue = result.accessToken; // If session_data was provided, also return it if (inputData.session_data) returnValue.session_data = inputData.session_data; return callback(null, returnValue); }); } function validatePasswordGrant(inputData: TokenRequest, callback: SimpleCallback) { debug('validatePasswordGrant()'); if (!inputData.client_id) return failOAuth(400, 'invalid_request', 'client_id is missing', callback); // client_secret validation is done in validateTokenClientCredentials. if (inputData.scope) { if ((typeof (inputData.scope) !== 'string') && !Array.isArray(inputData.scope)) return failOAuth(400, 'invalid_scope', 'scope has to be either a string or a string array', callback); } if (!inputData.authenticated_userid) return failOAuth(400, 'invalid_request', 'authenticated_userid is missing', callback); return callback(null); } function tokenPasswordGrantInternal(inputData: TokenRequest, callback: AccessTokenCallback) { debug('tokenAuthorizationCodeInternal()'); return tokenFlow(inputData, tokenPasswordGrantKong, callback); } function tokenPasswordGrantKong(oauthInfo: TokenOAuthInfo, callback: TokenOAuthInfoCallback) { debug(oauthInfo.oauth2Config); // HACK_PASSTHROUGH_REFRESH: Bypass this check? Refresh Token case with passthrough scopes and users. if (!oauthInfo.inputData.accept_password_grant) { if (!oauthInfo.oauth2Config || !oauthInfo.oauth2Config.enable_password_grant) return failOAuth(401, 'unauthorized_client', 'The API ' + oauthInfo.inputData.api_id + ' is not configured for the OAuth2 resource owner password grant.', callback); } return tokenWithKong(oauthInfo, 'password', callback); } // ----------------------------------- // REFRESH TOKEN // ----------------------------------- function tokenRefreshToken(inputData: TokenRequest, callback: AccessTokenCallback) { debug('tokenRefreshToken()'); debug(inputData); async.series({ validate: function (callback) { validateRefreshToken(inputData, callback); }, accessToken: function (callback) { tokenRefreshTokenInternal(inputData, callback); } }, function (err, result) { if (err) return callback(err); const returnValue = result.accessToken; // If session_data was provided, also return it if (inputData.session_data) returnValue.session_data = inputData.session_data; return callback(null, returnValue); }); } function validateRefreshToken(inputData: TokenRequest, callback: SimpleCallback) { debug('validateRefreshToken()'); if (!inputData.client_id) return failOAuth(400, 'invalid_request', 'client_id is missing', callback); // client_secret validation for confidential clients is done in validateTokenClientCredentials if (!inputData.refresh_token) return failOAuth(400, 'invalid_request', 'refresh_token is missing', callback); if (inputData.scope) { if ((typeof (inputData.scope) !== 'string') && !Array.isArray(inputData.scope)) return failOAuth(400, 'invalid_scope', 'scope has to be either a string or a string array', callback); } return callback(null); } function tokenRefreshTokenInternal(inputData: TokenRequest, callback: AccessTokenCallback) { debug('tokenRefreshTokenInternal()'); return tokenFlow(inputData, tokenRefreshTokenKong, callback); } function tokenRefreshTokenKong(oauthInfo: TokenOAuthInfo, callback: TokenOAuthInfoCallback) { debug('tokenRefreshTokenKong()'); return tokenWithKong(oauthInfo, 'refresh_token', callback); } // ----------------------------------- // AUTHORIZATION ENDPOINT HELPER METHODS // ----------------------------------- function authorizeFlow(inputData: AuthRequest, authorizeKongInvoker: AuthorizeKongInvoker, callback: StringCallback) { debug('authorizeFlow()'); // We'll add info to this thing along the way; this is how it will look: // { // inputData: { // authenticated_userid: (user custom ID, e.g. from 3rd party DB), // api_id: (API ID) // client_id: (The app's client ID, from subscription) // auth_server: (optional, which auth server is calling? Used to check that API is configured to use this auth server) // scope: [ list of wanted scopes ] (optional, depending on API definition) // } // provisionKey: ... // subsInfo: { // application: (app ID) // api: (api ID) // auth: 'oauth2', // plan: (plan ID) // clientId: (client ID) // clientSecret: (client secret) // trusted: false // ... // }, // appInfo: { // id: (app ID), // name: (Application friendly name), // redirectUri: (App's redirect URI) // confidential: false // }, // consumer: { // id: (Kong consumer ID), // username: (app id)$(api_id) // custom_id: (subscription id) // }, // apiInfo: { // strip_uri: true, // preserve_host: false, // name: "mobile", // uris : [ "/mobile/v1" ], // id: "7baec4f7-131d-44e9-a746-312352cedab1", // upstream_url: "https://upstream.url/api/v1", // created_at: 1477320419000 // } // redirectUri: (redirect URI including access token) // } const oauthInfo = { inputData: inputData } as AuthorizeOAuthInfo; async.series([ callback => lookupSubscription(oauthInfo, callback), callback => getOAuth2Config(oauthInfo, callback), //callback => lookupConsumer(oauthInfo, callback), // What was this for? callback => lookupApi(oauthInfo, callback), callback => authorizeKongInvoker(oauthInfo, callback) ], function (err, results) { debug('authorizeFlow async series returned.'); if (err) { debug('but failed.'); return callback(err); } // Oh, wow, that worked. callback(null, oauthInfo.redirectUri); }); } function createAuthorizeRequest(responseType: string, oauthInfo: AuthorizeOAuthInfo, callback: AuthorizeRequestPayloadCallback) { debug('createAuthorizeRequest()'); const { kongUrl, headers, agent } = buildKongUrl(oauthInfo.apiInfo.uris[0], '/oauth2/authorize'); const authorizeUrl = kongUrl.toString();; info(`Kong Authorize URL: ${authorizeUrl}`); let scope = null; if (oauthInfo.inputData.scope) { let s = oauthInfo.inputData.scope; if (typeof (s) === 'string') scope = s; else if (Array.isArray(s)) scope = s.join(' '); else // else: what? return failOAuth(400, 'invalid_scope', 'unknown type of scope input parameter: ' + typeof (s), callback); } debug(`requested scope: ${scope}`); debug(`requested redirect_uri: ${oauthInfo.inputData.redirect_uri}`); const oauthBody: any = { response_type: responseType, provision_key: oauthInfo.provisionKey, client_id: oauthInfo.subsInfo.clientId, redirect_uri: oauthInfo.inputData.redirect_uri, authenticated_userid: oauthInfo.inputData.authenticated_userid, }; if (scope) oauthBody.scope = scope; debug(oauthBody); const requestParameters = { url: authorizeUrl, headers: headers, agent: agent, json: true, body: oauthBody }; return callback(null, requestParameters); } function postAuthorizeRequest(authorizeRequest: AuthorizeRequestPayload, callback: StringCallback) { debug('postAuthorizeRequest()'); // Jetzt kommt der spannende Moment, wo der Frosch ins Wasser rennt request.post(authorizeRequest, function (err, res, body) { if (err) { return failOAuth(500, 'server_error', 'calling kong authorize returned an error', err, callback); } const jsonBody = utils.getJson(body); if (res.statusCode > 299) { debug('postAuthorizeRequest: Kong did not create a redirect URI, response body:'); debug(JSON.stringify(jsonBody)); // Kong _should_ return an RFC6479 compliant response; let's see const error = jsonBody.error || 'server_error'; const message = jsonBody.error_description || 'authorize for user with Kong failed: ' + utils.getText(body); const statusCode = res.statusCode || 500; return failOAuth(statusCode, error, message, callback); } debug('Kong authorize response:'); debug(body); return callback(null, jsonBody.redirect_uri); }); } // ----------------------------------- // TOKEN ENDPOINT HELPER METHODS // ----------------------------------- function tokenFlow(inputData: TokenRequest, tokenKongInvoker: TokenKongInvoker, callback: AccessTokenCallback) { debug('tokenFlow()'); const oauthInfo = { inputData: inputData } as TokenOAuthInfo; async.series([ callback => lookupSubscription(oauthInfo, callback), callback => validateTokenRequest(oauthInfo, callback), callback => getOAuth2Config(oauthInfo, callback), //callback => lookupConsumer(oauthInfo, callback), // What was this for? callback => lookupApi(oauthInfo, callback), callback => tokenKongInvoker(oauthInfo, callback), callback => checkClientTypeAndReturnValue(oauthInfo, callback) ], function (err, _) { debug('tokenFlow async series returned.'); if (err) { debug('but failed.'); return callback(err); } // Oh, wow, that worked. callback(null, oauthInfo.accessToken); }); } function checkClientTypeAndReturnValue(oauthInfo: TokenOAuthInfo, callback: TokenOAuthInfoCallback): void { debug('checkClientTypeAndReturnValue()'); if (oauthInfo.appInfo.confidential) return callback(null, oauthInfo); // We have a public client; take out the refresh token, if present, for the authorization code grant, and for client type "public_spa". if (oauthInfo.inputData.grant_type == 'authorization_code' && oauthInfo.appInfo.clientType == WickedClientType.Public_SPA) { if (oauthInfo.accessToken && oauthInfo.accessToken.refresh_token) { debug(`Application ${oauthInfo.appInfo.id} is a public client; deleting refresh_token.`); delete oauthInfo.accessToken.refresh_token; } } return callback(null, oauthInfo); } // Note that this is not necessary for the /authorize end point, only for the token // end point. Maybe it might be a good idea to make this behaviour configurable. function validateTokenRequest(oauthInfo: TokenOAuthInfo, callback: TokenOAuthInfoCallback) { debug('validateTokenRequest()'); debug(oauthInfo.inputData); const appId = oauthInfo.appInfo.id; const grantType = oauthInfo.inputData.grant_type; switch (grantType) { case 'password': case 'refresh_token': // Confidential clients MUST present their client_secret, non-confidential clients // MUST NOT present their client_secret. if (!oauthInfo.appInfo.confidential) { if (oauthInfo.inputData.client_secret) return failOAuth(401, 'unauthorized_client', `client_secret is being passed; the application ${appId} is not declared as a confidential application; it must not contain and pass its client_secret using the ${grantType} grant.`, callback); } else { if (!oauthInfo.inputData.client_secret) return failOAuth(401, 'unauthorized_client', `client_secret is missing; the application ${appId} is declared as a confidential application; it must pass its client_secret using the ${grantType} grant.`, callback); } break; // The client credentials flow *requires* a confidential (non-public client) case 'client_credentials': if (!oauthInfo.appInfo.confidential) return failOAuth(401, 'unauthorized_client', `the application ${appId} is not declared as a confidential application, thus cannot request access tokens via grant ${grantType}.`, callback); if (!oauthInfo.inputData.client_secret) return failOAuth(400, 'unauthorized_client', 'client_secret is missing.', callback); break; // For the authorization code to work with a public client, PKCE must be active case 'authorization_code': if (oauthInfo.appInfo.confidential) { if (!oauthInfo.inputData.client_secret) return failOAuth(400, 'unauthorized_client', 'client_secret is missing.', callback); } else { debug(`validateTokenRequest: Validate PKCE`) debug(oauthInfo.inputData); // Verify PKCE if (oauthInfo.inputData.client_secret) return failOAuth(400, 'unauthorized_client', `the application ${appId} is a public client and must not pass in its client_secret (must not be part of deployed application)`, callback); if (!oauthInfo.inputData.code_verifier) return failOAuth(400, 'invalid_request', `the application ${appId} is not declared as a confidential application, and does not pass in a code_verifier, thus cannot request access tokens via grant ${grantType}.`, callback); const codeVerifier = oauthInfo.inputData.code_verifier; if (codeVerifier.length < 43 || codeVerifier.length > 128) return failOAuth(400, 'invalid_request', 'code_verifier has to be at least 43 characters and at most 128 characters', callback); if (!oauthInfo.inputData.code_challenge || !oauthInfo.inputData.code_challenge_method) return failOAuth(400, 'invalid_request', 'the authorization code flow was started without a code_challenge, but a code_verifier was passed in.', callback); if (!verifyPKCE(oauthInfo.inputData)) return failOAuth(400, 'invalid_grant', `PKCE verification failed (method ${oauthInfo.inputData.code_challenge_method})`, callback); // PKCE good, let's add the client_secret so that Kong doesn't complain oauthInfo.inputData.client_secret = oauthInfo.subsInfo.clientSecret; } break; } return callback(null, oauthInfo); } function base64UrlEncode(s) { // https://tools.ietf.org/html/rfc7636#appendix-A let b = s.split('=')[0]; b = b.replace(/\+/g, '-'); b = b.replace(/\//g, '_'); return b; } function verifyPKCE(tokenRequest: TokenRequest): boolean { debug(`verifyPKCE(code_challenge: ${tokenRequest.code_challenge}, code_challenge_method: ${tokenRequest.code_challenge_method}, code_verifier: ${tokenRequest.code_verifier})`); switch (tokenRequest.code_challenge_method) { case "plain": return tokenRequest.code_challenge === tokenRequest.code_verifier; case "S256": const sha256 = crypto.createHash('sha256'); sha256.update(tokenRequest.code_verifier); const codeVerifierSHA256 = sha256.digest('base64'); if (tokenRequest.code_challenge === codeVerifierSHA256) return true; // Check base64-urlencode variants if (tokenRequest.code_challenge === base64UrlEncode(codeVerifierSHA256)) return true; if (base64UrlEncode(tokenRequest.code_challenge) === base64UrlEncode(codeVerifierSHA256)) return true; } error(`verifyPKCE: Unknown code_challenge_method ${tokenRequest.code_challenge_method}`); return false; } function createTokenRequest(grantType: string, oauthInfo: TokenOAuthInfo, callback: TokenRequestPayloadCallback) { const { kongUrl, headers, agent } = buildKongUrl(oauthInfo.apiInfo.uris[0], '/oauth2/token'); const tokenUrl = kongUrl.toString(); info(`Kong Token URL: ${tokenUrl}`); let scope = null; if (oauthInfo.inputData.scope) { let s = oauthInfo.inputData.scope; if (typeof (s) === 'string') scope = s; else if (Array.isArray(s)) scope = s.join(' '); else // else: what? return failOAuth(400, 'invalid_scope', 'unknown type of scope input parameter: ' + typeof (s), callback); } let tokenBody; switch (grantType) { case 'client_credentials': tokenBody = { grant_type: grantType, client_id: oauthInfo.inputData.client_id, client_secret: oauthInfo.inputData.client_secret, scope: scope }; break; case 'authorization_code': tokenBody = { grant_type: grantType, client_id: oauthInfo.inputData.client_id, client_secret: oauthInfo.inputData.client_secret, code: oauthInfo.inputData.code, redirect_uri: oauthInfo.appInfo.redirectUri }; break; case 'password': tokenBody = { grant_type: grantType, client_id: oauthInfo.inputData.client_id, client_secret: oauthInfo.subsInfo.clientSecret, // On purpose! These aren't always here. provision_key: oauthInfo.provisionKey, authenticated_userid: oauthInfo.inputData.authenticated_userid, scope: scope }; break; case 'refresh_token': tokenBody = { grant_type: grantType, client_id: oauthInfo.inputData.client_id, client_secret: oauthInfo.subsInfo.clientSecret, // On purpose! These aren't always here. refresh_token: oauthInfo.inputData.refresh_token }; break; default: return failOAuth(400, 'invalid_request', `invalid grant_type ${grantType}`, callback); } // Kong is very picky about this if (!scope && tokenBody.hasOwnProperty('scope')) delete tokenBody.scope; const tokenRequest = { url: tokenUrl, headers: headers, agent: agent, json: true, body: tokenBody } as TokenRequestPayload; debug(JSON.stringify(tokenRequest.body, null, 2)); return callback(null, tokenRequest); } function postTokenRequest(tokenRequest: TokenRequestPayload, callback: AccessTokenCallback) { request.post(tokenRequest, function (err, res, body) { if (err) return failOAuth(500, 'server_error', 'calling kong token endpoint returned an error', err, callback); const jsonBody = utils.getJson(body); // jsonBody is now either of AccessToken type, or it contains an error // and an error_description if (res.statusCode > 299) { debug('postTokenRequest: Kong did not create a token, response body:'); debug(JSON.stringify(jsonBody)); // Kong _should_ return an RFC6479 compliant response; let's see const error = jsonBody.error || 'server_error'; const message = jsonBody.error_description || 'Get auth code for user with Kong failed: ' + utils.getText(body); const statusCode = res.statusCode || 500; return failOAuth(statusCode, error, message, callback); } debug('Kong authorize response:'); debug(JSON.stringify(jsonBody)); return callback(null, jsonBody); }); } // ----------------------------------- // GENERIC HELPER METHODS // ----------------------------------- function lookupSubscription(oauthInfo: OAuthInfo, callback: OAuthInfoCallback) { debug('lookupSubscription()'); wicked.getSubscriptionByClientId(oauthInfo.inputData.client_id, oauthInfo.inputData.api_id, function (err, subscription) { if (err) return failOAuth(401, 'unauthorized_client', 'invalid client_id', err, callback); const subsInfo = subscription.subscription; debug('subsInfo:'); debug(subsInfo); const appInfo = subscription.application; debug('appInfo:'); debug(appInfo); // Validate that the subscription is for the correct API if (oauthInfo.inputData.api_id !== subsInfo.api) { debug('inputData:'); debug(oauthInfo.inputData); debug('subInfo:'); debug(subsInfo); return failOAuth(401, 'unauthorized_client', 'subscription does not match client_id, or invalid api_id', callback); } oauthInfo.subsInfo = subsInfo; oauthInfo.appInfo = appInfo; return callback(null, oauthInfo); }); } const _oauth2Configs = {}; function getOAuth2Config(oauthInfo: OAuthInfo, callback: OAuthInfoCallback) { debug('getOAuth2Config() for ' + oauthInfo.inputData.api_id); const apiId = oauthInfo.inputData.api_id; if (_oauth2Configs[apiId]) { oauthInfo.oauth2Config = _oauth2Configs[apiId]; oauthInfo.provisionKey = oauthInfo.oauth2Config.provision_key; return callback(null, oauthInfo); } // We haven't seen this API yet, get it from le Kong. kongUtils.kongGetApiOAuth2Plugins(apiId, function (err, body) { if (err) return failOAuth(500, 'server_error', 'could not retrieve oauth2 plugins from Kong', err, callback); if (body.data.length <= 0) return failOAuth(500, 'server_error', `api ${apiId} is not configured for use with oauth2`, callback); const oauth2Plugin = body.data[0] as any; if (!oauth2Plugin.config.provision_key) return failOAuth(500, 'server_error', `api ${apiId} does not have a valid provision_key`, callback); // Looks good, remember dat thing oauthInfo.oauth2Config = oauth2Plugin.config; oauthInfo.provisionKey = oauth2Plugin.config.provision_key; _oauth2Configs[apiId] = oauth2Plugin.config; callback(null, oauthInfo); }); } // This is a really interesting little function, but I just don't get anymore what it // was needed for. I think it actually *isn't* needed. But let's keep it in here for // a little while and see whether the need pops up again... // // function lookupConsumer(oauthInfo, callback) { // const customId = oauthInfo.subsInfo.id; // debug('lookupConsumer() for subscription ' + customId); // // kongUtils.kongGet('consumers?custom_id=' + qs.escape(customId), function (err, consumer) { // if (err) { // return failOAuth(500, 'server_error', `could not retrieve consumer for custom id ${customId}`, err, callback); // } // // debug('Found these consumers for subscription ' + customId); // debug(consumer); // // if (!consumer.total || // consumer.total <= 0 || // !consumer.data || // consumer.data.length <= 0) { // return failOAuth(500, 'server_error', `list of consumers for custom id ${customId} either not returned or empty`, callback); // } // // oauthInfo.consumer = consumer.data[0]; // callback(null, oauthInfo); // }); // } const _kongApis: { [apiId: string]: KongApi } = {}; function getKongApi(apiId: string, callback: Callback<KongApi>) { debug(`getKongApi(${apiId})`); if (_kongApis[apiId]) return callback(null, _kongApis[apiId]); kongUtils.kongGetApi(apiId, function (err, apiData) { if (err) return callback(err); _kongApis[apiId] = apiData; return callback(null, apiData); }); } const _wickedApis: { [apiId: string]: WickedApi } = {}; function getWickedApi(apiId, callback: Callback<WickedApi>): void { debug(`getWickedApi(${apiId})`); if (_wickedApis[apiId]) return callback(null, _wickedApis[apiId]); wicked.getApi(apiId, function (err, apiData) { if (err) return callback(err); _wickedApis[apiId] = apiData; return callback(null, apiData); }); } function lookupApi(oauthInfo: OAuthInfo, callback: OAuthInfoCallback): void { const apiId = oauthInfo.subsInfo.api; debug('lookupApi() for API ' + apiId); async.parallel({ kongApi: callback => getKongApi(apiId, callback), wickedApi: callback => getWickedApi(apiId, callback) }, function (err, results) { if (err) { return failOAuth(500, 'server_error', 'could not retrieve API information from API or kong', err, callback); } const apiInfo = results.kongApi as KongApi; const wickedApiInfo = results.wickedApi as WickedApi; if (!apiInfo.uris) { return failOAuth(500, 'server_error', `api ${apiId} does not have a valid uris setting`, callback); } // We will have a specified auth_method, as it's mandatory, now check which auth methods are // allowed for the API. This is mandatory for the API. if (!wickedApiInfo.authMethods) return failOAuth(500, 'server_error', `api ${apiId} does not have any authMethods configured`, callback); const authMethod = oauthInfo.inputData.auth_method; debug(`lookupApi: Matching auth method ${authMethod} against API ${apiId}`); const foundMethod = wickedApiInfo.authMethods.find(m => m === authMethod); if (!foundMethod) return failOAuth(500, 'unauthorized_client', `auth method ${authMethod} is not allowed for api ${apiId}`, callback); debug(`lookupApi: Auth method ${authMethod} is fine`); oauthInfo.apiInfo = apiInfo; return callback(null, oauthInfo); }); } function buildKongUrl(requestPath: string, additionalPath: string): { kongUrl: URL, headers: RequestHeaders, agent: any } { const globs = wicked.getGlobals(); let hostUrl = wicked.getExternalApiUrl(); if (globs.network && globs.network.kongProxyUrl) { // Prefer to use the internal proxy URL hostUrl = wicked.getInternalKongProxyUrl(); } let reqPath = requestPath; let addPath = additionalPath; if (!hostUrl.endsWith('/')) hostUrl = hostUrl + '/'; if (reqPath.startsWith('/')) reqPath = reqPath.substring(1); // cut leading / if (!reqPath.endsWith('/')) reqPath = reqPath + '/'; if (addPath.startsWith('/')) addPath = addPath.substring(1); // cut leading / const kongUrl = new URL(hostUrl + reqPath + addPath); let headers: RequestHeaders = null; let agent = null; // Depending on the type of protocol, we need additional settings: if ('http:' === kongUrl.protocol) { // We are accessing Kong via the internal, unencrypted port; this is the default, // but Kong needs to know that it's safe to do this. In production environments, // the proxy port must be behind a TLS terminating load balancer, which by default // already introduces this header. headers = { 'X-Forwarded-Proto': 'https' }; } else if ('https:' === kongUrl.protocol) { // Make sure we accept self signed certs. agent = sslAgent; } return { kongUrl, headers, agent }; } // module.exports = oauth2;
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Logs-based metric can also be used to extract values from logs and create a a distribution * of the values. The distribution records the statistics of the extracted values along with * an optional histogram of the values as specified by the bucket options. * * To get more information about Metric, see: * * * [API documentation](https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create) * * How-to Guides * * [Official Documentation](https://cloud.google.com/logging/docs/apis) * * ## Example Usage * ### Logging Metric Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const loggingMetric = new gcp.logging.Metric("logging_metric", { * bucketOptions: { * linearBuckets: { * numFiniteBuckets: 3, * offset: 1, * width: 1, * }, * }, * filter: "resource.type=gae_app AND severity>=ERROR", * labelExtractors: { * mass: "EXTRACT(jsonPayload.request)", * sku: "EXTRACT(jsonPayload.id)", * }, * metricDescriptor: { * displayName: "My metric", * labels: [ * { * description: "amount of matter", * key: "mass", * valueType: "STRING", * }, * { * description: "Identifying number for item", * key: "sku", * valueType: "INT64", * }, * ], * metricKind: "DELTA", * unit: "1", * valueType: "DISTRIBUTION", * }, * valueExtractor: "EXTRACT(jsonPayload.request)", * }); * ``` * ### Logging Metric Counter Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const loggingMetric = new gcp.logging.Metric("logging_metric", { * filter: "resource.type=gae_app AND severity>=ERROR", * metricDescriptor: { * metricKind: "DELTA", * valueType: "INT64", * }, * }); * ``` * ### Logging Metric Counter Labels * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const loggingMetric = new gcp.logging.Metric("logging_metric", { * filter: "resource.type=gae_app AND severity>=ERROR", * labelExtractors: { * mass: "EXTRACT(jsonPayload.request)", * }, * metricDescriptor: { * labels: [{ * description: "amount of matter", * key: "mass", * valueType: "STRING", * }], * metricKind: "DELTA", * valueType: "INT64", * }, * }); * ``` * * ## Import * * Metric can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:logging/metric:Metric default {{project}} {{name}} * ``` * * ```sh * $ pulumi import gcp:logging/metric:Metric default {{name}} * ``` */ export class Metric extends pulumi.CustomResource { /** * Get an existing Metric 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?: MetricState, opts?: pulumi.CustomResourceOptions): Metric { return new Metric(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:logging/metric:Metric'; /** * Returns true if the given object is an instance of Metric. 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 Metric { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Metric.__pulumiType; } /** * The bucketOptions are required when the logs-based metric is using a DISTRIBUTION value type and it * describes the bucket boundaries used to create a histogram of the extracted values. * Structure is documented below. */ public readonly bucketOptions!: pulumi.Output<outputs.logging.MetricBucketOptions | undefined>; /** * A description of this metric, which is used in documentation. The maximum length of the * description is 8000 characters. */ public readonly description!: pulumi.Output<string | undefined>; /** * An advanced logs filter (https://cloud.google.com/logging/docs/view/advanced-filters) which * is used to match log entries. */ public readonly filter!: pulumi.Output<string>; /** * A map from a label key string to an extractor expression which is used to extract data from a log * entry field and assign as the label value. Each label key specified in the LabelDescriptor must * have an associated extractor expression in this map. The syntax of the extractor expression is * the same as for the valueExtractor field. */ public readonly labelExtractors!: pulumi.Output<{[key: string]: string} | undefined>; /** * The metric descriptor associated with the logs-based metric. * Structure is documented below. */ public readonly metricDescriptor!: pulumi.Output<outputs.logging.MetricMetricDescriptor>; /** * The client-assigned metric identifier. Examples - "errorCount", "nginx/requests". * Metric identifiers are limited to 100 characters and can include only the following * characters A-Z, a-z, 0-9, and the special characters _-.,+!*',()%/. The forward-slash * character (/) denotes a hierarchy of name pieces, and it cannot be the first character * of the name. */ public readonly name!: pulumi.Output<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * A valueExtractor is required when using a distribution logs-based metric to extract the values to * record from a log entry. Two functions are supported for value extraction - EXTRACT(field) or * REGEXP_EXTRACT(field, regex). The argument are 1. field - The name of the log entry field from which * the value is to be extracted. 2. regex - A regular expression using the Google RE2 syntax * (https://github.com/google/re2/wiki/Syntax) with a single capture group to extract data from the specified * log entry field. The value of the field is converted to a string before applying the regex. It is an * error to specify a regex that does not include exactly one capture group. */ public readonly valueExtractor!: pulumi.Output<string | undefined>; /** * Create a Metric 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: MetricArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: MetricArgs | MetricState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as MetricState | undefined; inputs["bucketOptions"] = state ? state.bucketOptions : undefined; inputs["description"] = state ? state.description : undefined; inputs["filter"] = state ? state.filter : undefined; inputs["labelExtractors"] = state ? state.labelExtractors : undefined; inputs["metricDescriptor"] = state ? state.metricDescriptor : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; inputs["valueExtractor"] = state ? state.valueExtractor : undefined; } else { const args = argsOrState as MetricArgs | undefined; if ((!args || args.filter === undefined) && !opts.urn) { throw new Error("Missing required property 'filter'"); } if ((!args || args.metricDescriptor === undefined) && !opts.urn) { throw new Error("Missing required property 'metricDescriptor'"); } inputs["bucketOptions"] = args ? args.bucketOptions : undefined; inputs["description"] = args ? args.description : undefined; inputs["filter"] = args ? args.filter : undefined; inputs["labelExtractors"] = args ? args.labelExtractors : undefined; inputs["metricDescriptor"] = args ? args.metricDescriptor : undefined; inputs["name"] = args ? args.name : undefined; inputs["project"] = args ? args.project : undefined; inputs["valueExtractor"] = args ? args.valueExtractor : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Metric.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Metric resources. */ export interface MetricState { /** * The bucketOptions are required when the logs-based metric is using a DISTRIBUTION value type and it * describes the bucket boundaries used to create a histogram of the extracted values. * Structure is documented below. */ bucketOptions?: pulumi.Input<inputs.logging.MetricBucketOptions>; /** * A description of this metric, which is used in documentation. The maximum length of the * description is 8000 characters. */ description?: pulumi.Input<string>; /** * An advanced logs filter (https://cloud.google.com/logging/docs/view/advanced-filters) which * is used to match log entries. */ filter?: pulumi.Input<string>; /** * A map from a label key string to an extractor expression which is used to extract data from a log * entry field and assign as the label value. Each label key specified in the LabelDescriptor must * have an associated extractor expression in this map. The syntax of the extractor expression is * the same as for the valueExtractor field. */ labelExtractors?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The metric descriptor associated with the logs-based metric. * Structure is documented below. */ metricDescriptor?: pulumi.Input<inputs.logging.MetricMetricDescriptor>; /** * The client-assigned metric identifier. Examples - "errorCount", "nginx/requests". * Metric identifiers are limited to 100 characters and can include only the following * characters A-Z, a-z, 0-9, and the special characters _-.,+!*',()%/. The forward-slash * character (/) denotes a hierarchy of name pieces, and it cannot be the first character * of the name. */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * A valueExtractor is required when using a distribution logs-based metric to extract the values to * record from a log entry. Two functions are supported for value extraction - EXTRACT(field) or * REGEXP_EXTRACT(field, regex). The argument are 1. field - The name of the log entry field from which * the value is to be extracted. 2. regex - A regular expression using the Google RE2 syntax * (https://github.com/google/re2/wiki/Syntax) with a single capture group to extract data from the specified * log entry field. The value of the field is converted to a string before applying the regex. It is an * error to specify a regex that does not include exactly one capture group. */ valueExtractor?: pulumi.Input<string>; } /** * The set of arguments for constructing a Metric resource. */ export interface MetricArgs { /** * The bucketOptions are required when the logs-based metric is using a DISTRIBUTION value type and it * describes the bucket boundaries used to create a histogram of the extracted values. * Structure is documented below. */ bucketOptions?: pulumi.Input<inputs.logging.MetricBucketOptions>; /** * A description of this metric, which is used in documentation. The maximum length of the * description is 8000 characters. */ description?: pulumi.Input<string>; /** * An advanced logs filter (https://cloud.google.com/logging/docs/view/advanced-filters) which * is used to match log entries. */ filter: pulumi.Input<string>; /** * A map from a label key string to an extractor expression which is used to extract data from a log * entry field and assign as the label value. Each label key specified in the LabelDescriptor must * have an associated extractor expression in this map. The syntax of the extractor expression is * the same as for the valueExtractor field. */ labelExtractors?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The metric descriptor associated with the logs-based metric. * Structure is documented below. */ metricDescriptor: pulumi.Input<inputs.logging.MetricMetricDescriptor>; /** * The client-assigned metric identifier. Examples - "errorCount", "nginx/requests". * Metric identifiers are limited to 100 characters and can include only the following * characters A-Z, a-z, 0-9, and the special characters _-.,+!*',()%/. The forward-slash * character (/) denotes a hierarchy of name pieces, and it cannot be the first character * of the name. */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * A valueExtractor is required when using a distribution logs-based metric to extract the values to * record from a log entry. Two functions are supported for value extraction - EXTRACT(field) or * REGEXP_EXTRACT(field, regex). The argument are 1. field - The name of the log entry field from which * the value is to be extracted. 2. regex - A regular expression using the Google RE2 syntax * (https://github.com/google/re2/wiki/Syntax) with a single capture group to extract data from the specified * log entry field. The value of the field is converted to a string before applying the regex. It is an * error to specify a regex that does not include exactly one capture group. */ valueExtractor?: pulumi.Input<string>; }
the_stack
import { Point, PolyPoints } from "../common-types"; import { isTruthy } from "../utils"; import { GridMap, TileWalkableTest } from "./grid-map"; import { PointQueue } from "./point-queue"; import { RectangleHull } from "./rectangle-hull"; type CardinalDirection = "top" | "bottom" | "left" | "right"; /** * This parses a world that is a uniform grid into convex polygons (specifically rectangles) that * can be used for building a navmesh. This is designed mainly for parsing tilemaps into polygons. * The functions takes a 2D array that indicates which tiles are walkable and which aren't. The * function returns PolyPoint[] that can be used to construct a NavMesh. * * Notes: * - This algorithm traverses the walkable tiles in a depth-first search, combining neighbors into * rectangular polygons. This may not produce the best navmesh, but it doesn't require any manual * work! * - This assumes the world is a uniform grid. It should work for any tile size, provided that all * tiles are the same width and height. * * @param map 2D array of any type. * @param tileWidth The width of each tile in the grid. * @param tileHeight The height of each tile in the grid. * @param isWalkable Function that is used to test if a specific location in the map is walkable. * Defaults to assuming "truthy" means walkable. * @param shrinkAmount Amount to "shrink" the mesh away from the tiles. This adds more polygons * to the generated mesh, but can be helpful for preventing agents from getting caught on edges. * This supports values between 0 and tileWidth/tileHeight (whichever dimension is smaller). */ export default function buildPolysFromGridMap<TileType>( map: TileType[][], tileWidth: number = 1, tileHeight: number = 1, isWalkable: TileWalkableTest<TileType> = isTruthy, shrinkAmount: number = 0 ): PolyPoints[] { const gridMap = new GridMap(map, isWalkable, tileWidth, tileHeight); if (shrinkAmount >= tileWidth || shrinkAmount >= tileHeight) { throw new Error( `navmesh: Unsupported shrink amount ${shrinkAmount}. Must be less than tile width and height.` ); } let hulls: RectangleHull[] = buildInitialHulls(gridMap); if (shrinkAmount > 0) { hulls = shrinkHulls(hulls, gridMap, shrinkAmount); } return hulls.map((hull) => hull.toPoints()); } /** * Build up rectangular hulls from the walkable areas of a GridMap. This starts with a walkable tile * and attempts to "grow" each of its edges to engulf its neighbors. This process repeats until the * current hull can't engulf any neighbors. * @param gridMap */ function buildInitialHulls<TileType>(gridMap: GridMap<TileType>) { const walkableQueue = new PointQueue(); const { tileWidth, tileHeight } = gridMap; const hulls: RectangleHull[] = []; let currentHull; gridMap.forEach((x, y) => { if (gridMap.isWalkable(x, y)) walkableQueue.add({ x, y }); }); const getExtensionPoints = (hull: RectangleHull, dir: CardinalDirection) => { const { top, left, right, bottom } = hull; let points: Point[] = []; if (dir === "top") { for (let x = left; x <= right - 1; x++) points.push({ x, y: top }); } else if (dir === "bottom") { for (let x = left; x <= right - 1; x++) points.push({ x, y: bottom }); } else if (dir === "left") { for (let y = top; y <= bottom - 1; y++) points.push({ x: left, y }); } else if (dir === "right") { for (let y = top; y <= bottom - 1; y++) points.push({ x: right, y }); } else { throw new Error(`Invalid dir "${dir}" for extend`); } return points; }; const extendHullInDirection = (hull: RectangleHull, dir: CardinalDirection) => { if (dir === "top") hull.y -= 1; else if (dir === "bottom") hull.bottom += 1; else if (dir === "left") hull.x -= 1; else if (dir === "right") hull.right += 1; else throw new Error(`Invalid dir "${dir}" for extend`); }; const attemptExtension = (hull: RectangleHull, dir: CardinalDirection) => { const neighborPoints = getExtensionPoints(hull, dir); const canExtend = walkableQueue.containsAllPoints(neighborPoints); if (canExtend) { extendHullInDirection(hull, dir); walkableQueue.removePoints(neighborPoints); } return canExtend; }; while (!walkableQueue.isEmpty()) { // Find next colliding tile to start the algorithm. const tile = walkableQueue.shift(); if (tile === undefined) break; // Use tile dimensions (i.e. 1 tile wide, 1 tile tall) to simplify the checks. currentHull = new RectangleHull(tile.x, tile.y, 1, 1); // Check edges of bounding box to see if they can be extended. let needsExtensionCheck = true; while (needsExtensionCheck) { const extendedTop = attemptExtension(currentHull, "top"); const extendedRight = attemptExtension(currentHull, "right"); const extendedLeft = attemptExtension(currentHull, "left"); const extendedBottom = attemptExtension(currentHull, "bottom"); needsExtensionCheck = extendedTop || extendedBottom || extendedLeft || extendedRight; } // Scale the hull up from grid dimensions to real world dimensions. currentHull.setPosition(currentHull.x * tileWidth, currentHull.y * tileHeight); currentHull.setSize(currentHull.width * tileWidth, currentHull.height * tileHeight); hulls.push(currentHull); } return hulls; } // TODO: check larger than tile size. Assumes shrink <= 1 tile. function shrinkHull<TileType>( hull: RectangleHull, gridMap: GridMap<TileType>, shrinkAmount: number, tileWidth: number, tileHeight: number ) { const s = shrinkAmount; const halfWidth = tileWidth / 2; const halfHeight = tileHeight / 2; const { left, top, right, bottom } = hull; const info = { left: false, right: false, top: false, bottom: false, topLeft: gridMap.isBlockedAtWorld(left - s, top - s), topRight: gridMap.isBlockedAtWorld(right + s, top - s), bottomLeft: gridMap.isBlockedAtWorld(left - s, bottom + s), bottomRight: gridMap.isBlockedAtWorld(right + s, bottom + s), }; for (let y = top + halfHeight; y < bottom; y += halfHeight) { if (gridMap.isBlockedAtWorld(left - s, y)) { info.left = true; break; } } for (let y = top + halfHeight; y < bottom; y += halfHeight) { if (gridMap.isBlockedAtWorld(right + s, y)) { info.right = true; break; } } for (let x = left + halfWidth; x < right; x += halfWidth) { if (gridMap.isBlockedAtWorld(x, top - shrinkAmount)) { info.top = true; break; } } for (let x = left + halfWidth; x < right; x += halfWidth) { if (gridMap.isBlockedAtWorld(x, bottom + shrinkAmount)) { info.bottom = true; break; } } const shrink = { left: info.left, right: info.right, top: info.top, bottom: info.bottom, }; if (info.topLeft && !info.left && !info.top) { if (hull.width > hull.height) shrink.left = true; else shrink.top = true; } if (info.topRight && !info.right && !info.top) { if (hull.width > hull.height) shrink.right = true; else shrink.top = true; } if (info.bottomLeft && !info.bottom && !info.left) { if (hull.width > hull.height) shrink.left = true; else shrink.bottom = true; } if (info.bottomRight && !info.bottom && !info.right) { if (hull.width > hull.height) shrink.right = true; else shrink.bottom = true; } if (shrink.left) { hull.x += shrinkAmount; hull.width -= shrinkAmount; } if (shrink.top) { hull.y += shrinkAmount; hull.height -= shrinkAmount; } if (shrink.right) { hull.width -= shrinkAmount; } if (shrink.bottom) { hull.height -= shrinkAmount; } return shrink; } function shrinkHulls<TileType>( hulls: RectangleHull[], gridMap: GridMap<TileType>, shrinkAmount: number ) { const { tileHeight, tileWidth } = gridMap; const newHulls: RectangleHull[] = []; const finalHulls: RectangleHull[] = []; hulls.forEach((hull, hullIndex) => { const th = tileHeight; const tw = tileWidth; const tLeft = gridMap.getGridX(hull.x); const tTop = gridMap.getGridY(hull.y); const tBottom = gridMap.getGridY(hull.bottom); const tRight = gridMap.getGridX(hull.right); const shrink = shrinkHull(hull, gridMap, shrinkAmount, tileWidth, tileHeight); if (hull.left >= hull.right || hull.top >= hull.bottom) return; finalHulls.push(hull); const newVerticalHulls: RectangleHull[] = []; const newHorizontalHulls: RectangleHull[] = []; const addHull = (x: number, y: number, w: number, h: number) => { const hull = new RectangleHull(x, y, w, h); if (w > h) newHorizontalHulls.push(hull); else newVerticalHulls.push(hull); }; if (shrink.left) { const x = hull.left - shrinkAmount; let startY = tTop; let endY = startY - 1; for (let y = tTop; y < tBottom; y++) { if (gridMap.isBlocked(tLeft - 1, y)) { if (startY <= endY) { addHull(x, startY * th, shrinkAmount, (endY - startY + 1) * th); } startY = y + 1; } else { endY = y; } } if (startY <= endY) { addHull(x, startY * th, shrinkAmount, (endY - startY + 1) * th); } } if (shrink.right) { const x = hull.right; let startY = tTop; let endY = startY - 1; for (let y = tTop; y < tBottom; y++) { if (gridMap.isBlocked(tRight, y)) { if (startY <= endY) { addHull(x, startY * th, shrinkAmount, (endY - startY + 1) * th); } startY = y + 1; } else { endY = y; } } if (startY <= endY) { addHull(x, startY * th, shrinkAmount, (endY - startY + 1) * th); } } if (shrink.top) { const y = hull.top - shrinkAmount; let startX = tLeft; let endX = startX - 1; for (let x = tLeft; x < tRight; x++) { if (gridMap.isBlocked(x, tTop - 1)) { if (startX <= endX) { addHull(startX * tw, y, (endX - startX + 1) * th, shrinkAmount); } startX = x + 1; } else { endX = x; } } if (startX <= endX) { addHull(startX * tw, y, (endX - startX + 1) * th, shrinkAmount); } } if (shrink.bottom) { const y = hull.bottom; let startX = tLeft; let endX = startX - 1; for (let x = tLeft; x < tRight; x++) { if (gridMap.isBlocked(x, tBottom)) { if (startX <= endX) { addHull(startX * tw, y, (endX - startX + 1) * th, shrinkAmount); } startX = x + 1; } else { endX = x; } } if (startX <= endX) { addHull(startX * tw, y, (endX - startX + 1) * th, shrinkAmount); } } // Shrunk at corners when the new hulls overlap. newHorizontalHulls.forEach((hh) => { newVerticalHulls.forEach((vh) => { if (hh.doesOverlap(vh)) { const isBottomSide = hh.y > vh.y; if (isBottomSide) vh.height -= shrinkAmount; else vh.top += shrinkAmount; } }); }); [...newHorizontalHulls, ...newVerticalHulls].forEach((hull) => { shrinkHull(hull, gridMap, shrinkAmount, tileWidth, tileHeight); if (hull.left >= hull.right || hull.top >= hull.bottom) return; newHulls.push(hull); }); }); // Attempt to merge new hulls into existing hulls if possible. for (let i = 0; i < newHulls.length; i++) { let wasMerged = false; // Attempt to merge into the main (shrunken) hulls first. for (const mainHull of hulls) { wasMerged = mainHull.attemptMergeIn(newHulls[i]); if (wasMerged) break; } if (wasMerged) continue; // Then check to see if we can merge into a later hull in newHulls. for (let j = i + 1; j < newHulls.length; j++) { wasMerged = newHulls[j].attemptMergeIn(newHulls[i]); if (wasMerged) break; } if (!wasMerged) finalHulls.push(newHulls[i]); } return finalHulls; }
the_stack
import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader, GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js'; import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'; import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js'; let orbitControls: OrbitControls; let camera: THREE.PerspectiveCamera; let scene: THREE.Scene; let renderer: THREE.WebGLRenderer; let loader: GLTFLoader; let gltf: GLTF; let background: THREE.Texture; let envMap: THREE.Texture; let mixer: THREE.AnimationMixer; const clock = new THREE.Clock(); interface SceneInfo { name: string; url: string; author: string; authorURL: string; cameraPos: THREE.Vector3; extensions: string[]; addEnvMap?: boolean | undefined; objectRotation?: THREE.Euler | undefined; objectScale?: THREE.Vector3 | undefined; objectPosition?: THREE.Vector3 | undefined; center?: THREE.Vector3 | undefined; addLights?: boolean | undefined; addGround?: boolean | undefined; shadows?: boolean | undefined; animationTime?: number | undefined; } const scenes: Record<string, SceneInfo> = { Boombox: { name: 'BoomBox (PBR)', url: './models/gltf/BoomBox/%s/BoomBox.gltf', author: 'Microsoft', authorURL: 'https://www.microsoft.com/', cameraPos: new THREE.Vector3(0.02, 0.01, 0.03), objectRotation: new THREE.Euler(0, Math.PI, 0), extensions: ['glTF', 'glTF-pbrSpecularGlossiness', 'glTF-Binary'], addEnvMap: true, }, 'Bot Skinned': { name: 'Bot Skinned', url: './models/gltf/BotSkinned/%s/Bot_Skinned.gltf', author: 'MozillaVR', authorURL: 'https://vr.mozilla.org/', cameraPos: new THREE.Vector3(0.5, 2, 2), center: new THREE.Vector3(0, 1.2, 0), objectRotation: new THREE.Euler(0, 0, 0), addLights: true, addGround: true, shadows: true, extensions: ['glTF-MaterialsUnlit'], }, MetalRoughSpheres: { name: 'MetalRoughSpheres (PBR)', url: './models/gltf/MetalRoughSpheres/%s/MetalRoughSpheres.gltf', author: '@emackey', authorURL: 'https://twitter.com/emackey', cameraPos: new THREE.Vector3(2, 1, 15), objectRotation: new THREE.Euler(0, 0, 0), extensions: ['glTF', 'glTF-Embedded'], addEnvMap: true, }, 'Clearcoat Test': { name: 'Clearcoat Test', url: './models/gltf/ClearcoatTest/ClearcoatTest.glb', author: 'Ed Mackey (Analytical Graphics, Inc.)', authorURL: 'https://www.agi.com/', cameraPos: new THREE.Vector3(0, 0, 20), extensions: ['glTF'], addEnvMap: true, }, Duck: { name: 'Duck', url: './models/gltf/Duck/%s/Duck.gltf', author: 'Sony', authorURL: 'https://www.playstation.com/en-us/corporate/about/', cameraPos: new THREE.Vector3(0, 3, 5), addLights: true, addGround: true, shadows: true, extensions: ['glTF', 'glTF-Embedded', 'glTF-pbrSpecularGlossiness', 'glTF-Binary', 'glTF-Draco'], }, Monster: { name: 'Monster', url: './models/gltf/Monster/%s/Monster.gltf', author: '3drt.com', authorURL: 'http://www.3drt.com/downloads.htm', cameraPos: new THREE.Vector3(3, 1, 7), objectScale: new THREE.Vector3(0.04, 0.04, 0.04), objectPosition: new THREE.Vector3(0.2, 0.1, 0), objectRotation: new THREE.Euler(0, (-3 * Math.PI) / 4, 0), animationTime: 3, addLights: true, shadows: true, addGround: true, extensions: ['glTF', 'glTF-Embedded', 'glTF-Binary', 'glTF-Draco', 'glTF-lights'], }, 'Cesium Man': { name: 'Cesium Man', url: './models/gltf/CesiumMan/%s/CesiumMan.gltf', author: 'Cesium', authorURL: 'https://cesiumjs.org/', cameraPos: new THREE.Vector3(0, 3, 10), objectRotation: new THREE.Euler(0, 0, 0), addLights: true, addGround: true, shadows: true, extensions: ['glTF', 'glTF-Embedded', 'glTF-Binary', 'glTF-Draco'], }, 'Cesium Milk Truck': { name: 'Cesium Milk Truck', url: './models/gltf/CesiumMilkTruck/%s/CesiumMilkTruck.gltf', author: 'Cesium', authorURL: 'https://cesiumjs.org/', cameraPos: new THREE.Vector3(0, 3, 10), addLights: true, addGround: true, shadows: true, extensions: ['glTF', 'glTF-Embedded', 'glTF-Binary', 'glTF-Draco'], }, 'Outlined Box': { name: 'Outlined Box', url: './models/gltf/OutlinedBox/OutlinedBox.gltf', author: '@twittmann', authorURL: 'https://github.com/twittmann', cameraPos: new THREE.Vector3(0, 5, 15), objectScale: new THREE.Vector3(0.01, 0.01, 0.01), objectRotation: new THREE.Euler(0, 90, 0), addLights: true, shadows: true, extensions: ['glTF'], }, }; const state = { scene: Object.keys(scenes)[0], extension: scenes[Object.keys(scenes)[0]].extensions[0], playAnimation: true, }; function onload() { renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); renderer.outputEncoding = THREE.sRGBEncoding; renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1; renderer.physicallyCorrectLights = true; document.body.appendChild(renderer.domElement); window.addEventListener('resize', onWindowResize); // Load background and generate envMap new RGBELoader() .setDataType(THREE.UnsignedByteType) .setPath('textures/equirectangular/') .load('venice_sunset_1k.hdr', texture => { envMap = pmremGenerator.fromEquirectangular(texture).texture; pmremGenerator.dispose(); background = envMap; // initScene(scenes[state.scene]); animate(); }); const pmremGenerator = new THREE.PMREMGenerator(renderer); pmremGenerator.compileEquirectangularShader(); } function initScene(sceneInfo: SceneInfo) { const descriptionEl = document.getElementById('description'); if (descriptionEl && sceneInfo.author && sceneInfo.authorURL) { descriptionEl.innerHTML = `${sceneInfo.name} by <a href="${sceneInfo.authorURL}" target="_blank" rel="noopener">${sceneInfo.author}</a>`; } scene = new THREE.Scene(); scene.background = new THREE.Color(0x222222); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.001, 1000); scene.add(camera); let spot1: THREE.SpotLight; if (sceneInfo.addLights) { const ambient = new THREE.AmbientLight(0x222222); scene.add(ambient); const directionalLight = new THREE.DirectionalLight(0xdddddd, 4); directionalLight.position.set(0, 0, 1).normalize(); scene.add(directionalLight); spot1 = new THREE.SpotLight(0xffffff, 1); spot1.position.set(5, 10, 5); spot1.angle = 0.5; spot1.penumbra = 0.75; spot1.intensity = 100; spot1.decay = 2; if (sceneInfo.shadows) { spot1.castShadow = true; spot1.shadow.bias = 0.0001; spot1.shadow.mapSize.width = 2048; spot1.shadow.mapSize.height = 2048; } scene.add(spot1); } if (sceneInfo.shadows) { renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; } // TODO: Reuse existing OrbitControls, GLTFLoaders, and so on orbitControls = new OrbitControls(camera, renderer.domElement); if (sceneInfo.addGround) { const groundMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff }); const ground = new THREE.Mesh(new THREE.PlaneGeometry(512, 512), groundMaterial); ground.receiveShadow = !!sceneInfo.shadows; ground.position.z = -70; ground.rotation.x = -Math.PI / 2; scene.add(ground); } loader = new GLTFLoader(); const dracoLoader = new DRACOLoader(); dracoLoader.setDecoderPath('js/libs/draco/gltf/'); loader.setDRACOLoader(dracoLoader); let url = sceneInfo.url.replace(/%s/g, state.extension); if (state.extension === 'glTF-Binary') { url = url.replace('.gltf', '.glb'); } const loadStartTime = performance.now(); loader.load( url, data => { gltf = data; const object = gltf.scene; console.info(`Load time: ${(performance.now() - loadStartTime).toFixed(2)}ms.`); if (sceneInfo.cameraPos) { camera.position.copy(sceneInfo.cameraPos); } if (sceneInfo.center) { orbitControls.target.copy(sceneInfo.center); } if (sceneInfo.objectPosition) { object.position.copy(sceneInfo.objectPosition); if (spot1) { spot1.target.position.copy(sceneInfo.objectPosition); } } if (sceneInfo.objectRotation) { object.rotation.copy(sceneInfo.objectRotation); } if (sceneInfo.objectScale) { object.scale.copy(sceneInfo.objectScale); } if (sceneInfo.addEnvMap) { object.traverse(node => { const mesh = node as THREE.Mesh; if ( mesh.material && ((mesh.material as THREE.MeshStandardMaterial).isMeshStandardMaterial || (mesh.material as THREE.ShaderMaterial).isShaderMaterial) ) { (mesh.material as THREE.MeshStandardMaterial).envMap = envMap; (mesh.material as THREE.MeshStandardMaterial).envMapIntensity = 1.5; // boombox seems too dark otherwise } }); scene.background = background; } object.traverse(node => { if ((node as THREE.Mesh).isMesh || (node as THREE.Light).isLight) node.castShadow = true; }); const animations = gltf.animations; if (animations && animations.length) { mixer = new THREE.AnimationMixer(object); animations.forEach(anim => { if (sceneInfo.animationTime) { anim.duration = sceneInfo.animationTime; } const action = mixer.clipAction(anim); if (state.playAnimation) action.play(); }); } scene.add(object); onWindowResize(); }, undefined, error => { console.error(error); }, ); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function animate() { requestAnimationFrame(animate); if (mixer) mixer.update(clock.getDelta()); orbitControls.update(); render(); } function render() { renderer.render(scene, camera); } onload();
the_stack
'use strict'; import * as jsonc from 'jsonc-parser'; import * as path from 'path'; import * as vscode from 'vscode'; import { ICodeDeployer, IExecuteAPI, IExternalAPI, IPreferencesAPI } from 'vscode-wpilibapi'; import { getIsWindows, gradleRun, readFileAsync } from '../utilities'; import { IDebugCommands, startDebugging } from './debug'; import { IUnixSimulateCommands, startUnixSimulation } from './simulateunix'; import { IWindowsSimulateCommands, startWindowsSimulation } from './simulatewindows'; interface ICppDebugInfo { name: string; path: string; } interface ICppSimExtensions { name: string; libName: string; defaultEnabled: boolean; } interface ICppSimulateInfo { type: string; name: string; extensions: ICppSimExtensions[]; launchfile: string; clang: boolean; environment?: Map<string, string>; srcpaths: string[]; headerpaths: string[]; libpaths: string[]; libsrcpaths: string[]; } interface ICppDebugCommand { type: string; name: string; port: number; target: string; launchfile: string; gdb: string; sysroot: string | undefined; srcpaths: string[]; headerpaths: string[]; libpaths: string[]; libsrcpaths: string[]; } class CppQuickPick<T> implements vscode.QuickPickItem { public label: string; public description?: string | undefined; public detail?: string | undefined; public picked?: boolean | undefined; public debugInfo: T; public constructor(debugInfo: T, label: string) { this.debugInfo = debugInfo; this.label = label; } } class DebugCodeDeployer implements ICodeDeployer { private preferences: IPreferencesAPI; private executeApi: IExecuteAPI; constructor(externalApi: IExternalAPI) { this.preferences = externalApi.getPreferencesAPI(); this.executeApi = externalApi.getExecuteAPI(); } public async getIsCurrentlyValid(workspace: vscode.WorkspaceFolder): Promise<boolean> { const prefs = this.preferences.getPreferences(workspace); const currentLanguage = prefs.getCurrentLanguage(); return currentLanguage === 'none' || currentLanguage === 'cpp'; } public async runDeployer(teamNumber: number, workspace: vscode.WorkspaceFolder, _: vscode.Uri | undefined, ...args: string[]): Promise<boolean> { let command = 'deploy ' + args.join(' ') + ' -PdebugMode -PteamNumber=' + teamNumber; const prefs = this.preferences.getPreferences(workspace); // If deploy offline, and builds online, set flags // Otherwise, build offline will be set later if (prefs.getDeployOffline() && !prefs.getOffline()) { command += ' --offline'; } const result = await gradleRun(command, workspace.uri.fsPath, workspace, 'C++ Debug', this.executeApi, prefs); if (result !== 0) { return false; } const debugInfo = await readFileAsync(path.join(workspace.uri.fsPath, 'build', 'debug', 'debug_info.json'), 'utf8'); const parsedDebugInfo: ICppDebugInfo[] = jsonc.parse(debugInfo) as ICppDebugInfo[]; if (parsedDebugInfo.length === 0) { await vscode.window.showInformationMessage('No target configurations found. Is this a robot project?', { modal: true, }); return false; } let targetDebugInfo = parsedDebugInfo[0]; if (parsedDebugInfo.length > 1) { const arr: CppQuickPick<ICppDebugInfo>[] = []; for (const i of parsedDebugInfo) { arr.push(new CppQuickPick<ICppDebugInfo>(i, i.name)); } const picked = await vscode.window.showQuickPick(arr, { placeHolder: 'Select a target', }); if (picked === undefined) { vscode.window.showInformationMessage('Target cancelled'); return false; } targetDebugInfo = picked.debugInfo; } const debugPath = targetDebugInfo.path; const targetReadInfo = await readFileAsync(debugPath, 'utf8'); const targetInfoArray: ICppDebugCommand[] = jsonc.parse(targetReadInfo) as ICppDebugCommand[]; if (targetInfoArray.length === 0) { await vscode.window.showInformationMessage('No debug configurations found. Is this a robot project?', { modal: true, }); return false; } // TODO Filter this off of type let targetInfoParsed = targetInfoArray[0]; if (targetInfoArray.length > 1) { const arr: CppQuickPick<ICppDebugCommand>[] = []; for (const i of targetInfoArray) { arr.push(new CppQuickPick<ICppDebugCommand>(i, i.name)); } const picked = await vscode.window.showQuickPick(arr, { placeHolder: 'Select an artifact', }); if (picked === undefined) { vscode.window.showInformationMessage('Artifact cancelled'); return false; } targetInfoParsed = picked.debugInfo; } const set = new Set<string>(targetInfoParsed.libpaths); let soPath = ''; for (const p of set) { soPath += path.dirname(p) + ';'; } soPath = soPath.substring(0, soPath.length - 1); let sysroot = ''; if (targetInfoParsed.sysroot !== undefined) { sysroot = targetInfoParsed.sysroot; } const srcArrs = []; srcArrs.push(...targetInfoParsed.srcpaths); srcArrs.push(...targetInfoParsed.headerpaths); srcArrs.push(...targetInfoParsed.libsrcpaths); const config: IDebugCommands = { executablePath: targetInfoParsed.launchfile, gdbPath: targetInfoParsed.gdb, soLibPath: soPath, srcPaths: new Set<string>(srcArrs), sysroot, target: targetInfoParsed.target + ':' + targetInfoParsed.port.toString(10), workspace, }; await startDebugging(config); return true; } public getDisplayName(): string { return 'cpp'; } public getDescription(): string { return 'C++ Debugging'; } } class DeployCodeDeployer implements ICodeDeployer { private preferences: IPreferencesAPI; private executeApi: IExecuteAPI; constructor(externalApi: IExternalAPI) { this.preferences = externalApi.getPreferencesAPI(); this.executeApi = externalApi.getExecuteAPI(); } public async getIsCurrentlyValid(workspace: vscode.WorkspaceFolder): Promise<boolean> { const prefs = this.preferences.getPreferences(workspace); const currentLanguage = prefs.getCurrentLanguage(); return currentLanguage === 'none' || currentLanguage === 'cpp'; } public async runDeployer(teamNumber: number, workspace: vscode.WorkspaceFolder, _: vscode.Uri | undefined, ...args: string[]): Promise<boolean> { let command = 'deploy ' + args.join(' ') + ' -PteamNumber=' + teamNumber; const prefs = this.preferences.getPreferences(workspace); // If deploy offline, and builds online, set flags // Otherwise, build offline will be set later if (prefs.getDeployOffline() && !prefs.getOffline()) { command += ' --offline'; } const result = await gradleRun(command, workspace.uri.fsPath, workspace, 'C++ Deploy', this.executeApi, prefs); if (result !== 0) { return false; } return true; } public getDisplayName(): string { return 'cpp'; } public getDescription(): string { return 'C++ Deployment'; } } class SimulateCodeDeployer implements ICodeDeployer { private preferences: IPreferencesAPI; private executeApi: IExecuteAPI; constructor(externalApi: IExternalAPI) { this.preferences = externalApi.getPreferencesAPI(); this.executeApi = externalApi.getExecuteAPI(); } public async getIsCurrentlyValid(workspace: vscode.WorkspaceFolder): Promise<boolean> { const prefs = this.preferences.getPreferences(workspace); const currentLanguage = prefs.getCurrentLanguage(); return currentLanguage === 'none' || currentLanguage === 'cpp'; } public async runDeployer(_: number, workspace: vscode.WorkspaceFolder, __: vscode.Uri | undefined, ...args: string[]): Promise<boolean> { // Support release const command = 'simulateExternalNativeDebug ' + args.join(' '); const prefs = this.preferences.getPreferences(workspace); const result = await gradleRun(command, workspace.uri.fsPath, workspace, 'C++ Simulate', this.executeApi, prefs); if (result !== 0) { return false; } const simulateInfo = await readFileAsync(path.join(workspace.uri.fsPath, 'build', 'sim', 'debug_native.json'), 'utf8'); const parsedSimulateInfo: ICppSimulateInfo[] = jsonc.parse(simulateInfo) as ICppSimulateInfo[]; if (parsedSimulateInfo.length === 0) { await vscode.window.showInformationMessage('No debug configurations found. Do you have desktop builds enabled?', { modal: true, }); return false; } let targetSimulateInfo = parsedSimulateInfo[0]; if (parsedSimulateInfo.length > 1) { const arr: CppQuickPick<ICppSimulateInfo>[] = []; for (const i of parsedSimulateInfo) { arr.push(new CppQuickPick<ICppSimulateInfo>(i, i.name)); } const picked = await vscode.window.showQuickPick(arr, { placeHolder: 'Select an artifact', }); if (picked === undefined) { vscode.window.showInformationMessage('Artifact cancelled'); return false; } targetSimulateInfo = picked.debugInfo; } let extensions = ''; if (targetSimulateInfo.extensions.length > 0) { if (this.preferences.getPreferences(workspace).getSkipSelectSimulateExtension()) { for (const e of targetSimulateInfo.extensions) { if (e.defaultEnabled) { extensions += e.libName; extensions += path.delimiter; } } } else { const extList = []; for (const e of targetSimulateInfo.extensions) { extList.push({ label: e.name, path: e.libName, picked: e.defaultEnabled, }); } const quickPick = await vscode.window.showQuickPick(extList, { canPickMany: true, placeHolder: 'Pick extensions to run', }); if (quickPick !== undefined) { for (const qp of quickPick) { extensions += qp.path; extensions += path.delimiter; } } } } if (!getIsWindows()) { const set = new Set<string>(targetSimulateInfo.libpaths); let soPath = ''; for (const p of set) { soPath += path.dirname(p) + ';'; } soPath = soPath.substring(0, soPath.length - 1); const config: IUnixSimulateCommands = { clang: targetSimulateInfo.clang, environment: targetSimulateInfo.environment, executablePath: targetSimulateInfo.launchfile, extensions, ldPath: path.dirname(targetSimulateInfo.launchfile), // gradle puts all the libs in the same dir as the executable soLibPath: soPath, srcPaths: new Set<string>(targetSimulateInfo.srcpaths), stopAtEntry: this.preferences.getPreferences(workspace).getStopSimulationOnEntry(), workspace, }; await startUnixSimulation(config); } else { const config: IWindowsSimulateCommands = { debugPaths: targetSimulateInfo.libpaths, environment: targetSimulateInfo.environment, extensions, launchfile: targetSimulateInfo.launchfile, srcPaths: targetSimulateInfo.srcpaths, stopAtEntry: this.preferences.getPreferences(workspace).getStopSimulationOnEntry(), workspace, }; await startWindowsSimulation(config); } return true; } public getDisplayName(): string { return 'cpp'; } public getDescription(): string { return 'C++ Simulation'; } } export class DeployDebug { private deployDebuger: DebugCodeDeployer; private deployDeployer: DeployCodeDeployer; private simulator: SimulateCodeDeployer; constructor(externalApi: IExternalAPI, allowDebug: boolean) { const deployDebugApi = externalApi.getDeployDebugAPI(); deployDebugApi.addLanguageChoice('cpp'); this.deployDebuger = new DebugCodeDeployer(externalApi); this.deployDeployer = new DeployCodeDeployer(externalApi); this.simulator = new SimulateCodeDeployer(externalApi); deployDebugApi.registerCodeDeploy(this.deployDeployer); if (allowDebug) { deployDebugApi.registerCodeDebug(this.deployDebuger); deployDebugApi.registerCodeSimulate(this.simulator); } } public dispose() { // } }
the_stack
import { Range, Point, TextBuffer, TextEditor } from 'atom' import { delimiter, sep, extname } from 'path' import * as Temp from 'temp' import * as FS from 'fs' import * as CP from 'child_process' import { EOL } from 'os' import { getRootDirFallback, getRootDir, isDirectory } from 'atom-haskell-utils' import { RunOptions, IErrorCallbackArgs } from './ghc-mod/ghc-modi-process-real' import { GHCModVers } from './ghc-mod/ghc-modi-process-real-factory' import { GHCModCaps } from './ghc-mod/interactive-process' import * as UPI from 'atom-haskell-upi' type ExecOpts = CP.ExecFileOptionsWithStringEncoding export { getRootDirFallback, getRootDir, isDirectory, ExecOpts } let debuglog: Array<{ timestamp: number; messages: string[] }> = [] const logKeep = 30000 // ms function savelog(...messages: string[]) { const ts = Date.now() debuglog.push({ timestamp: ts, messages, }) let ks = 0 for (const v of debuglog) { if (ts - v.timestamp >= logKeep) { break } ks++ } debuglog.splice(0, ks) } function joinPath(ds: string[]) { const set = new Set(ds) return Array.from(set).join(delimiter) } export const EOT = `${EOL}\x04${EOL}` export function debug(...messages: any[]) { if (atom.config.get('haskell-ghc-mod.debug')) { // tslint:disable-next-line: no-console console.log('haskell-ghc-mod debug:', ...messages) } savelog(...messages.map((v) => JSON.stringify(v))) } export function warn(...messages: any[]) { // tslint:disable-next-line: no-console console.warn('haskell-ghc-mod warning:', ...messages) savelog(...messages.map((v) => JSON.stringify(v))) } export function error(...messages: any[]) { // tslint:disable-next-line: no-console console.error('haskell-ghc-mod error:', ...messages) savelog(...messages.map((v) => JSON.stringify(v))) } export function getDebugLog() { const ts = Date.now() debuglog = debuglog.filter(({ timestamp }) => ts - timestamp < logKeep) return debuglog .map( ({ timestamp, messages }) => `${(timestamp - ts) / 1000}s: ${messages.join(',')}`, ) .join(EOL) } export async function execPromise( cmd: string, args: string[], opts: ExecOpts, stdin?: string, ) { return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => { debug(`Running ${cmd} ${args} with opts = `, opts) const child = CP.execFile( cmd, args, opts, (error, stdout: string, stderr: string) => { if (stderr.trim().length > 0) { warn(stderr) } if (error) { warn(`Running ${cmd} ${args} failed with `, error) if (stdout) { warn(stdout) } error.stack = new Error().stack reject(error) } else { debug(`Got response from ${cmd} ${args}`, { stdout, stderr }) resolve({ stdout, stderr }) } }, ) if (stdin) { debug(`sending stdin text to ${cmd} ${args}`) child.stdin.write(stdin) } }) } export async function getCabalSandbox( rootPath: string, ): Promise<string | undefined> { debug('Looking for cabal sandbox...') const sbc = await parseSandboxConfig(`${rootPath}${sep}cabal.sandbox.config`) // tslint:disable: no-string-literal if (sbc && sbc['install-dirs'] && sbc['install-dirs']['bindir']) { const sandbox: string = sbc['install-dirs']['bindir'] debug('Found cabal sandbox: ', sandbox) if (isDirectory(sandbox)) { return sandbox } else { warn('Cabal sandbox ', sandbox, ' is not a directory') return undefined } } else { warn('No cabal sandbox found') return undefined } // tslint:enable: no-string-literal } export async function getStackSandbox( rootPath: string, apd: string[], env: { [key: string]: string | undefined }, ) { debug('Looking for stack sandbox...') env.PATH = joinPath(apd) debug('Running stack with PATH ', env.PATH) try { const out = await execPromise( 'stack', [ '--no-install-ghc', 'path', '--snapshot-install-root', '--local-install-root', '--bin-path', ], { encoding: 'utf8', cwd: rootPath, env, timeout: atom.config.get('haskell-ghc-mod.initTimeout') * 1000, }, ) const lines = out.stdout.split(EOL) const sir = lines .filter((l) => l.startsWith('snapshot-install-root: '))[0] .slice(23) + `${sep}bin` const lir = lines.filter((l) => l.startsWith('local-install-root: '))[0].slice(20) + `${sep}bin` const bp = lines .filter((l) => l.startsWith('bin-path: '))[0] .slice(10) .split(delimiter) .filter((p) => !(p === sir || p === lir || apd.includes(p))) debug('Found stack sandbox ', lir, sir, ...bp) return [lir, sir, ...bp] } catch (err) { warn('No stack sandbox found because ', err) return undefined } } const processOptionsCache = new Map<string, RunOptions>() export async function getProcessOptions( rootPath?: string, ): Promise<RunOptions> { if (!rootPath) { // tslint:disable-next-line: no-null-keyword rootPath = getRootDirFallback(null).getPath() } // cache const cached = processOptionsCache.get(rootPath) if (cached) { return cached } debug(`getProcessOptions(${rootPath})`) const env = { ...process.env } // tslint:disable-next-line: totality-check if (process.platform === 'win32') { const PATH = [] const capMask = (str: string, mask: number) => { const a = str.split('') for (let i = 0; i < a.length; i++) { if (mask & Math.pow(2, i)) { a[i] = a[i].toUpperCase() } } return a.join('') } for (let m = 0b1111; m >= 0; m--) { const vn = capMask('path', m) if (env[vn]) { PATH.push(env[vn]) } } env.PATH = PATH.join(delimiter) } const PATH = env.PATH || '' const apd = atom.config .get('haskell-ghc-mod.additionalPathDirectories') .concat(PATH.split(delimiter)) const cabalSandbox = atom.config.get('haskell-ghc-mod.cabalSandbox') ? getCabalSandbox(rootPath) : Promise.resolve(undefined) const stackSandbox = atom.config.get('haskell-ghc-mod.stackSandbox') ? getStackSandbox(rootPath, apd, { ...env }) : Promise.resolve(undefined) const [cabalSandboxDir, stackSandboxDirs] = await Promise.all([ cabalSandbox, stackSandbox, ]) const newp = [] if (cabalSandboxDir) { newp.push(cabalSandboxDir) } if (stackSandboxDirs) { newp.push(...stackSandboxDirs) } newp.push(...apd) env.PATH = joinPath(newp) debug(`PATH = ${env.PATH}`) const res: RunOptions = { cwd: rootPath, env, encoding: 'utf8', maxBuffer: Infinity, } processOptionsCache.set(rootPath, res) return res } export function getSymbolAtPoint(editor: TextEditor, point: Point) { const [scope] = editor .scopeDescriptorForBufferPosition(point) .getScopesArray() .slice(-1) if (scope) { const range = editor.bufferRangeForScopeAtPosition(scope, point) if (range && !range.isEmpty()) { const symbol = editor.getTextInBufferRange(range) return { scope, range, symbol } } } return undefined } export function getSymbolInRange(editor: TextEditor, crange: Range) { const buffer = editor.getBuffer() if (crange.isEmpty()) { return getSymbolAtPoint(editor, crange.start) } else { return { symbol: buffer.getTextInRange(crange), range: crange, } } } export async function withTempFile<T>( contents: string, uri: string, gen: (path: string) => Promise<T>, ): Promise<T> { const info = await new Promise<Temp.OpenFile>((resolve, reject) => Temp.open( { prefix: 'haskell-ghc-mod', suffix: extname(uri || '.hs') }, (err, info2) => { if (err) { reject(err) } else { resolve(info2) } }, ), ) return new Promise<T>((resolve, reject) => FS.write(info.fd, contents, async (err) => { if (err) { reject(err) } else { resolve(await gen(info.path)) FS.close(info.fd, () => FS.unlink(info.path, () => { /*noop*/ }), ) } }), ) } export type KnownErrorName = | 'GHCModStdoutError' | 'InteractiveActionTimeout' | 'GHCModInteractiveCrash' export function mkError(name: KnownErrorName, message: string) { const err = new Error(message) err.name = name return err } export interface SandboxConfigTree { [k: string]: SandboxConfigTree | string } export async function parseSandboxConfig(file: string) { try { const sbc = await new Promise<string>((resolve, reject) => FS.readFile(file, { encoding: 'utf-8' }, (err, sbc2) => { if (err) { reject(err) } else { resolve(sbc2) } }), ) const vars: SandboxConfigTree = {} let scope = vars const rv = (v: string) => { for (const k1 of Object.keys(scope)) { const v1 = scope[k1] if (typeof v1 === 'string') { v = v.split(`$${k1}`).join(v1) } } return v } for (const line of sbc.split(/\r?\n|\r/)) { if (!line.match(/^\s*--/) && !line.match(/^\s*$/)) { const [l] = line.split(/--/) const m = l.match(/^\s*([\w-]+):\s*(.*)\s*$/) if (m) { const [, name, val] = m scope[name] = rv(val) } else { const newscope = {} scope[line] = newscope scope = newscope } } } return vars } catch (err) { warn('Reading cabal sandbox config failed with ', err) return undefined } } // A dirty hack to work with tabs export function tabShiftForPoint(buffer: TextBuffer, point: Point) { const line = buffer.lineForRow(point.row) const match = line ? line.slice(0, point.column).match(/\t/g) || [] : [] const columnShift = 7 * match.length return new Point(point.row, point.column + columnShift) } export function tabShiftForRange(buffer: TextBuffer, range: Range) { const start = tabShiftForPoint(buffer, range.start) const end = tabShiftForPoint(buffer, range.end) return new Range(start, end) } export function tabUnshiftForPoint(buffer: TextBuffer, point: Point) { const line = buffer.lineForRow(point.row) let columnl = 0 let columnr = point.column while (columnl < columnr) { // tslint:disable-next-line: strict-type-predicates if (line === undefined || line[columnl] === undefined) { break } if (line[columnl] === '\t') { columnr -= 7 } columnl += 1 } return new Point(point.row, columnr) } export function tabUnshiftForRange(buffer: TextBuffer, range: Range) { const start = tabUnshiftForPoint(buffer, range.start) const end = tabUnshiftForPoint(buffer, range.end) return new Range(start, end) } export function isUpperCase(ch: string): boolean { return ch.toUpperCase() === ch } export function getErrorDetail({ err, runArgs, caps }: IErrorCallbackArgs) { return `caps: ${JSON.stringify(caps, undefined, 2)} Args: ${JSON.stringify(runArgs, undefined, 2)} message: ${err.message} log: ${getDebugLog()}` } export function formatError({ err, runArgs }: IErrorCallbackArgs) { if (err.name === 'InteractiveActionTimeout' && runArgs) { return `\ Haskell-ghc-mod: ghc-mod \ ${runArgs.interactive ? 'interactive ' : ''}command ${runArgs.command} \ timed out. You can try to fix it by raising 'Interactive Action \ Timeout' setting in haskell-ghc-mod settings.` } else if (runArgs) { return `\ Haskell-ghc-mod: ghc-mod \ ${runArgs.interactive ? 'interactive ' : ''}command ${runArgs.command} \ failed with error ${err.name}` } else { return `There was an unexpected error ${err.name}` } } export function defaultErrorHandler(args: IErrorCallbackArgs) { const { err, runArgs, caps } = args const suppressErrors = runArgs && runArgs.suppressErrors if (!suppressErrors) { atom.notifications.addError(formatError(args), { detail: getErrorDetail(args), stack: err.stack, dismissable: true, }) } else { error(caps, runArgs, err) } } export function warnGHCPackagePath() { atom.notifications.addWarning( 'haskell-ghc-mod: You have GHC_PACKAGE_PATH environment variable set!', { dismissable: true, detail: `\ This configuration is not supported, and can break arbitrarily. You can try to band-aid it by adding delete process.env.GHC_PACKAGE_PATH to your Atom init script (Edit → Init Script...) You can suppress this warning in haskell-ghc-mod settings.`, }, ) } function filterEnv(env: { [name: string]: string | undefined }) { const fenv = {} // tslint:disable-next-line: forin for (const evar in env) { const evarU = evar.toUpperCase() if ( evarU === 'PATH' || evarU.startsWith('GHC_') || evarU.startsWith('STACK_') || evarU.startsWith('CABAL_') ) { fenv[evar] = env[evar] } } return fenv } export interface SpawnFailArgs { dir: string err: Error & { code?: any } opts?: RunOptions vers?: GHCModVers caps?: GHCModCaps } export function notifySpawnFail(args: Readonly<SpawnFailArgs>) { if (spawnFailENOENT(args) || spawnFailEACCESS(args)) return const debugInfo: SpawnFailArgs = Object.assign({}, args) if (args.opts) { const optsclone: RunOptions = Object.assign({}, args.opts) optsclone.env = filterEnv(optsclone.env) debugInfo.opts = optsclone } atom.notifications.addFatalError( `Haskell-ghc-mod: ghc-mod failed to launch. It is probably missing or misconfigured. ${args.err.code}`, { detail: `\ Error was: ${debugInfo.err.name} ${debugInfo.err.message} Debug information: ${JSON.stringify(debugInfo, undefined, 2)} Config: ${JSON.stringify(atom.config.get('haskell-ghc-mod'), undefined, 2)} Environment (filtered): ${JSON.stringify(filterEnv(process.env), undefined, 2)} `, stack: debugInfo.err.stack, dismissable: true, }, ) } function spawnFailENOENT(args: Readonly<SpawnFailArgs>): boolean { if (args.err.code === 'ENOENT') { const exePath = atom.config.get('haskell-ghc-mod.ghcModPath') const not = atom.notifications.addError( `Atom couldn't find ghc-mod executable`, { detail: `Atom tried to find ${exePath} in "${args.opts && args.opts.env.PATH}" but failed.`, dismissable: true, buttons: [ { className: 'icon-globe', text: 'Open installation guide', async onDidClick() { const opener = await import('opener') not.dismiss() opener( 'https://atom-haskell.github.io/installation/installing-binary-dependencies/', ) }, }, ], }, ) return true } return false } function spawnFailEACCESS(args: Readonly<SpawnFailArgs>): boolean { if (args.err.code === 'EACCES') { const exePath = atom.config.get('haskell-ghc-mod.ghcModPath') const isDir = FS.existsSync(exePath) && FS.statSync(exePath).isDirectory() if (isDir) { atom.notifications.addError(`Atom couldn't run ghc-mod executable`, { detail: `Atom tried to run ${exePath} but it was a directory. Check haskell-ghc-mod package settings.`, dismissable: true, }) } else { atom.notifications.addError(`Atom couldn't run ghc-mod executable`, { detail: `Atom tried to run ${exePath} but it wasn't executable. Check access rights.`, dismissable: true, }) } return true } return false } export function handleException<T>( _target: { upi: UPI.IUPIInstance | Promise<UPI.IUPIInstance> }, _key: string, desc: TypedPropertyDescriptor<(...args: any[]) => Promise<T>>, ): TypedPropertyDescriptor<(...args: any[]) => Promise<T>> { return { ...desc, async value(...args: any[]) { try { // tslint:disable-next-line: no-non-null-assertion return await desc.value!.call(this, ...args) } catch (e) { debug(e) const upi: UPI.IUPIInstance = await (this as any).upi upi.setStatus({ status: 'warning', detail: e.toString(), }) // TODO: returning a promise that never resolves... ugly, but works? return new Promise(() => { /* noop */ }) } }, } } export function versAtLeast( vers: { [key: number]: number | undefined }, b: number[], ) { for (let i = 0; i < b.length; i++) { const v = b[i] const t = vers[i] const vv = t !== undefined ? t : 0 if (vv > v) { return true } else if (vv < v) { return false } } return true }
the_stack
import { Rect, RefLineMeta, MatchedLine, LineType, LineGroup, RefLinePosition, Delta, AdsorbLine, AdsorbVLine, AdsorbHLine, } from "./types"; import { toNumber as fixNumber, getRectRefLines, getBoundingRect, groupBy, find, getLineTypeFromPosition, mergeRefLineMeta, getMatchedLine, coordinateRotation, isNil, } from "./utils"; export const version = "%VERSION%"; export * from "./types"; export { fixNumber, coordinateRotation, getBoundingRect, getRectRefLines, mergeRefLineMeta }; export interface RefLineOpts<T extends Rect = Rect> { rects: T[]; current?: T | string; lineFilter?: (line: RefLineMeta) => boolean; // 垂直吸附线 adsorbVLines?: Omit<AdsorbLine, "type">[]; // 水平吸附线 adsorbHLines?: Omit<AdsorbLine, "type">[]; } export class RefLine<T extends Rect = Rect> { protected opts: Omit<RefLineOpts<T>, "rects" | "current"> = {}; private seq: number = 1; protected __rects: T[] = []; protected _rects: T[] = []; protected current: null | T = null; protected _dirty: boolean = true; // 吸附用 protected _vLines: LineGroup<T>[] = []; protected _hLines: LineGroup<T>[] = []; // 匹配用 offset : RefLineMeta protected _vLineMap: Map<string, RefLineMeta<T>[]> = new Map(); protected _hLineMap: Map<string, RefLineMeta<T>[]> = new Map(); // 自定义吸附线 protected _adsorbVLines: AdsorbVLine[] = []; protected _adsorbHLines: AdsorbHLine[] = []; protected _lineFilter: ((line: RefLineMeta) => boolean) | null = null; get rects() { if (this._dirty) { this.initRefLines(); } return this._rects; } set rects(rects: T[]) { this.__rects = rects; this._dirty = true; } get vLines() { if (this._dirty) { this.initRefLines(); } return this._vLines; } get hLines() { if (this._dirty) { this.initRefLines(); } return this._hLines; } get vLineMap() { if (this._dirty) { this.initRefLines(); } return this._vLineMap; } get hLineMap() { if (this._dirty) { this.initRefLines(); } return this._hLineMap; } get adsorbVLines() { return this._adsorbHLines; } set adsorbVLines(lines: AdsorbVLine[]) { this._adsorbVLines = lines; this._dirty = true; } get adsorbHLines() { return this._adsorbHLines; } set adsorbHLines(lines: AdsorbHLine[]) { this._adsorbHLines = lines; this._dirty = true; } constructor(opts?: RefLineOpts<T>) { this.opts = opts || {}; this.__rects = opts?.rects || []; this._lineFilter = opts?.lineFilter || null; this._adsorbVLines = opts?.adsorbVLines || []; this._adsorbHLines = opts?.adsorbHLines || []; if (opts?.current) { this.setCurrent(opts.current); } this._dirty = true; } getRectByKey(key: string | number) { return find(this.__rects, rect => rect.key === key); } getOffsetRefLineMetaList(type: LineType, offset: number) { offset = fixNumber(offset, 0); const lineMap = type === "vertical" ? this.vLineMap : this.hLineMap; return lineMap.get(this.toLineMapKey(offset)) || []; } /** * @deprecated * @param rects */ setRects(rects: T[]) { this.__rects = rects; this._dirty = true; } protected getRect(rect: T | string): T | null { let current: T | null; if (typeof rect === "string") { current = this.getRectByKey(rect); } else { current = rect; } return current; } setCurrent(current: T | string | null) { const old = this.getCurrent(); this.current = current ? this.getRect(current) : null; if (old?.key !== this.current?.key) { this._dirty = true; } } getCurrent() { return this.current; } setLineFilter(filter: ((line: RefLineMeta) => boolean) | null) { this._lineFilter = filter; this._dirty = true; } getLineFilter() { return this._lineFilter; } protected toLineMapKey<S>(v: S) { return v + ""; } protected getLineMapKey(line: { offset: number }) { return this.toLineMapKey(fixNumber(line.offset, 0)); } protected isEnableLine(line: RefLineMeta<T>) { // 自定义吸附线不参与过滤 if (line.adsorbOnly) return true; const filter = this.getLineFilter(); if (filter) { return filter(line); } return true; } protected getRectRefLines(rect: T) { let lines = getRectRefLines(rect); if (this.getLineFilter()) { lines = lines.filter(line => this.isEnableLine(line)); } return lines; } protected initRefLines() { const current = this.getCurrent(); let vLines: RefLineMeta<T>[] = []; let hLines: RefLineMeta<T>[] = []; this._rects = current ? this.__rects.filter(rect => rect.key !== current.key) : [...this.__rects]; this._rects.forEach(rect => { const lines = this.getRectRefLines(rect); lines.forEach(line => { const mKey = this.getLineMapKey(line); if (line.type === "vertical") { vLines.push(line); const matched: RefLineMeta<T>[] = this._vLineMap.get(mKey) || []; matched.push(line); this._vLineMap.set(mKey, matched); } else { hLines.push(line); const matched: RefLineMeta<T>[] = this._hLineMap.get(mKey) || []; matched.push(line); this._hLineMap.set(mKey, matched); } }); }); // 添加自定义吸附线 this._adsorbVLines.forEach(line => { const refLineMeta: RefLineMeta<T> = { type: "vertical", position: "vl", offset: line.offset, start: line.offset, end: 0, rect: { key: "v_" + line.key, width: 0, height: 0, left: line.offset, top: 0, } as T, adsorbOnly: true, }; vLines.push(refLineMeta); const mKey = this.getLineMapKey(line); const matched: RefLineMeta<T>[] = this._vLineMap.get(mKey) || []; matched.push(refLineMeta); this._vLineMap.set(mKey, matched); }); this._adsorbHLines.forEach(line => { const refLineMeta: RefLineMeta<T> = { type: "horizontal", position: "ht", offset: line.offset, start: line.offset, end: 0, rect: { key: "h_" + line.key, width: 0, height: 0, left: 0, top: line.offset, } as T, adsorbOnly: true, }; hLines.push(refLineMeta); const mKey = this.getLineMapKey(line); const matched: RefLineMeta<T>[] = this._hLineMap.get(mKey) || []; matched.push(refLineMeta); this._hLineMap.set(mKey, matched); }); vLines = vLines.sort((a, b) => a.offset - b.offset); hLines = hLines.sort((a, b) => a.offset - b.offset); let vGroup = groupBy(vLines, line => this.getLineMapKey(line)); let hGroup = groupBy(hLines, line => this.getLineMapKey(line)); this._vLines = vGroup.keys.map(key => { const lines = vGroup.group[key]; return { offset: fixNumber(lines[0].offset, 0), min: Math.min(...lines.map(line => line.offset)), max: Math.max(...lines.map(line => line.offset)), refLineMetaList: lines, }; }); this._hLines = hGroup.keys.map(key => { const lines = hGroup.group[key]; return { offset: fixNumber(lines[0].offset, 0), min: Math.min(...lines.map(line => line.offset)), max: Math.max(...lines.map(line => line.offset)), refLineMetaList: lines, }; }); this._dirty = false; } /** * 匹配参考线,主要用于显示,不包括自定义吸附线 * @param type * @param rect * @returns */ matchRefLines(type: LineType): MatchedLine<T>[] { const current = this.getCurrent(); if (!current) return []; const isVertical = type === "vertical"; const lineMap = isVertical ? this.vLineMap : this.hLineMap; const matchedLines: MatchedLine<T>[] = []; if (!current) return matchedLines; const cLines = this.getRectRefLines(current); cLines.forEach(line => { if (line.type !== type) return; const mKey = this.getLineMapKey(line); const lines = lineMap.get(mKey) || []; const matchedLine = getMatchedLine( line, lines.filter(line => !line.adsorbOnly) // 过滤自定义吸附线 ); if (matchedLine) { matchedLines.push(matchedLine); } }); return matchedLines; } /** * 给定offset(坐标x或y)的值,返回距离该offset的最近的两个offset(上下或左右)及距离 * @param type * @param offset * @returns */ getNearestOffsetFromOffset( type: LineType, offset: number ): [[number, number] | null, [number, number] | null] { const isVertical = type === "vertical"; const lines = isVertical ? this.vLines : this.hLines; let prev: number = -Infinity; let prevDist: number = Infinity; let next: number = Infinity; let nextDist: number = Infinity; lines.forEach(line => { const d = Math.abs(line.min - offset); if (line.min < offset && d >= 0.5) { prev = Math.max(line.min, prev); prevDist = Math.min(d, prevDist); } if (line.min > offset && d >= 0.5) { next = Math.min(line.min, next); nextDist = Math.min(d, nextDist); } }); return [ prev !== -Infinity ? [prev, prevDist] : null, next !== Infinity ? [next, nextDist] : null, ]; } /** * 指定当前矩形需要检查的参考线,判断是否存在匹配,包括自定义吸附线 * @param position * @returns */ hasMatchedRefLine(position: RefLinePosition) { const current = this.getCurrent(); if (!current) return false; const lines = this.getRectRefLines(current); const line = find(lines, line => line.position === position); if (!line) return false; const mKey = this.getLineMapKey(line); const lineMap = getLineTypeFromPosition(position) === "vertical" ? this.vLineMap : this.hLineMap; const matched = lineMap.get(mKey); if (!matched) return false; return !!matched.length; } /** * alias getVRefLines * @returns */ matchVRefLines() { return this.matchRefLines("vertical"); } getVRefLines() { return this.matchRefLines("vertical"); } /** * alias getHRefLines * @returns */ matchHRefLines() { return this.matchRefLines("horizontal"); } getHRefLines() { return this.matchRefLines("horizontal"); } /** * alias getAllRefLines * @returns */ matchAllRefLines() { return [...this.matchVRefLines(), ...this.matchHRefLines()]; } getAllRefLines() { return [...this.matchVRefLines(), ...this.matchHRefLines()]; } /** * 适配偏移量,达到吸附效果 * @param type * @param offset * @param delta * @param adsorbDistance * @returns */ getOffsetAdsorbDelta(type: LineType, offset: number, delta: number, adsorbDistance = 5) { adsorbDistance = Math.abs(adsorbDistance); if (adsorbDistance < 1) return delta; const hasMatchedLine = this.getOffsetRefLineMetaList(type, offset).length; const n = this.getNearestOffsetFromOffset(type, offset); const isMoveTopOrLeft = delta < 0; const useIndex = isMoveTopOrLeft ? 0 : 1; const nearestOffset = n[useIndex]; const value: number = nearestOffset ? nearestOffset[0] : 0; const dist: number = nearestOffset ? nearestOffset[1] : 0; if (nearestOffset && dist <= adsorbDistance) { adsorbDistance = dist; } else { adsorbDistance += 1; } if (hasMatchedLine) { if (Math.abs(delta) < adsorbDistance) { delta = 0; } else if (Math.abs(delta) === 1 && adsorbDistance < 1) { delta = adsorbDistance; } } else if (delta !== 0) { const dist = value - (offset + delta); if (Math.abs(dist) < adsorbDistance && (isMoveTopOrLeft ? dist <= 0 : dist >= 0)) { delta += dist; } } return delta; } /** * 适配偏移量,达到吸附效果 * @param delta * @param adsorbDistance * @returns */ getAdsorbDelta( delta: Delta, adsorbDistance: number, dir: { x: "left" | "right" | "none"; y: "up" | "down" | "none"; } ): Delta { const rect = this.getCurrent(); if (!rect) return delta; const dirX = dir?.x || "none"; const dirY = dir?.y || "none"; adsorbDistance = Math.abs(adsorbDistance || 5); const origAdsorbDistance = adsorbDistance; const newDelta = { ...delta, }; if (adsorbDistance < 1) return newDelta; const refLineMetaList = getRectRefLines(rect); const lineStatus = [ this.isEnableLine(refLineMetaList[0]), this.isEnableLine(refLineMetaList[1]), this.isEnableLine(refLineMetaList[2]), this.isEnableLine(refLineMetaList[3]), this.isEnableLine(refLineMetaList[4]), this.isEnableLine(refLineMetaList[5]), ]; const hasMatchedVRefLine = this.hasMatchedRefLine("vl") || this.hasMatchedRefLine("vc") || this.hasMatchedRefLine("vr"); const hasMatchedHRefLine = this.hasMatchedRefLine("ht") || this.hasMatchedRefLine("hc") || this.hasMatchedRefLine("hb"); if (delta.left !== 0 && dirX !== "none") { adsorbDistance = origAdsorbDistance; const currentOffsetList = [ refLineMetaList[0].offset, refLineMetaList[1].offset, refLineMetaList[2].offset, ]; const n1 = this.getNearestOffsetFromOffset("vertical", refLineMetaList[0].offset); const n2 = this.getNearestOffsetFromOffset("vertical", refLineMetaList[1].offset); const n3 = this.getNearestOffsetFromOffset("vertical", refLineMetaList[2].offset); const isMoveLeft = dirX === "left"; const values: number[] = [Infinity, Infinity, Infinity]; const distValues: number[] = [Infinity, Infinity, Infinity]; const useIndex = isMoveLeft ? 0 : 1; if (lineStatus[0] && n1[useIndex]) { values[0] = n1[useIndex]![0]; distValues[0] = n1[useIndex]![1]; } if (lineStatus[1] && n2[useIndex]) { values[1] = n2[useIndex]![0]; distValues[1] = n2[useIndex]![1]; } if (lineStatus[2] && n3[useIndex]) { values[2] = n3[useIndex]![0]; distValues[2] = n3[useIndex]![1]; } const minDist = Math.min(...distValues); const minIndex = distValues.indexOf(minDist); const minOffset = values[minIndex]; if (minDist <= adsorbDistance) { adsorbDistance = minDist; } else { adsorbDistance += 1; } if (hasMatchedVRefLine) { if (isMoveLeft && delta.left > 0) { newDelta.left = 0; } else if (!isMoveLeft && delta.left < 0) { newDelta.left = 0; } else if (Math.abs(delta.left) < adsorbDistance) { newDelta.left = 0; } } else { const currentOffset = currentOffsetList[minIndex]; const dist = minOffset - (currentOffset + delta.left); if (isMoveLeft && delta.left > 0) { newDelta.left = 0; } else if (!isMoveLeft && delta.left < 0) { newDelta.left = 0; } else if (Math.abs(dist) < adsorbDistance && (isMoveLeft ? dist <= 0 : dist >= 0)) { newDelta.left = dist + delta.left; } } } if (delta.top !== 0 && dirY !== "none") { adsorbDistance = origAdsorbDistance; const currentOffsetList = [ refLineMetaList[3].offset, refLineMetaList[4].offset, refLineMetaList[5].offset, ]; const n1 = this.getNearestOffsetFromOffset("horizontal", refLineMetaList[3].offset); const n2 = this.getNearestOffsetFromOffset("horizontal", refLineMetaList[4].offset); const n3 = this.getNearestOffsetFromOffset("horizontal", refLineMetaList[5].offset); const isMoveTop = dirY === "up"; const values: number[] = [Infinity, Infinity, Infinity]; const distValues: number[] = [Infinity, Infinity, Infinity]; const useIndex = isMoveTop ? 0 : 1; if (lineStatus[3] && n1[useIndex]) { values[0] = n1[useIndex]![0]; distValues[0] = n1[useIndex]![1]; } if (lineStatus[4] && n2[useIndex]) { values[1] = n2[useIndex]![0]; distValues[1] = n2[useIndex]![1]; } if (lineStatus[5] && n3[useIndex]) { values[2] = n3[useIndex]![0]; distValues[2] = n3[useIndex]![1]; } const minDist = Math.min(...distValues); const minIndex = distValues.indexOf(minDist); const minOffset = values[minIndex]; if (minDist <= adsorbDistance) { adsorbDistance = minDist; } else { adsorbDistance += 1; } if (hasMatchedHRefLine) { if (isMoveTop && delta.top > 0) { newDelta.top = 0; } else if (!isMoveTop && delta.top < 0) { newDelta.top = 0; } else if (Math.abs(delta.top) < adsorbDistance) { newDelta.top = 0; } } else { const currentOffset = currentOffsetList[minIndex]; const dist = minOffset - (currentOffset + delta.top); if (isMoveTop && delta.top > 0) { newDelta.top = 0; } else if (!isMoveTop && delta.top < 0) { newDelta.top = 0; } else if (Math.abs(dist) < adsorbDistance && (isMoveTop ? dist <= 0 : dist >= 0)) { newDelta.top = dist + delta.top; } } } return newDelta; } adsorbCreator({ pageX, pageY, current = this.getCurrent(), distance = 5, disableAdsorb = false, scale, }: { pageX: number; pageY: number; current?: T | null; distance?: number; disableAdsorb?: boolean; scale?: number; }) { if (!current) { throw new Error("[refline.js] current rect does not exist!"); } let currentRect: T = { ...current, }; const startX = pageX; const startY = pageY; const startLeft = currentRect.left; const startTop = currentRect.top; const _scale = scale || 1; const defaultDisableAdsorb = disableAdsorb; // 记录上次坐标,如果相同则偏移量返回0,修复吸附后重复计算导致结果不一致问题 let lastX = pageX; let lastY = pageY; let lastDirX, lastDirY; return (data: { pageX?: number; pageY?: number; current?: T; distance?: number; disableAdsorb?: boolean; scale?: number; // 设置距离起始坐标偏移量,设置后相应的pageX或pageY及scale会失效 offsetX?: number; offsetY?: number; }) => { let disableAdsorb = defaultDisableAdsorb; if (data.current) { currentRect = { ...data.current, }; } if (!isNil(data.distance)) { distance = data.distance as number; } if (!isNil(data.disableAdsorb)) { disableAdsorb = data.disableAdsorb as boolean; } const currentX = isNil(data.pageX) ? startX : (data.pageX as number); const currentY = isNil(data.pageY) ? startY : (data.pageY as number); const scale = isNil(data.scale) ? _scale : (data.scale as number); const dir = { x: "none", y: "none", } as { x: "left" | "right" | "none"; y: "up" | "down" | "none"; }; if (!isNil(data.pageX)) { if (currentX === lastX) { dir.x = lastDirX; } else { dir.x = currentX < lastX ? "left" : "right"; } lastDirX = dir.x; } if (!isNil(data.pageY)) { if (currentY === lastY) { dir.y = lastDirY; } else { dir.y = currentY < lastY ? "up" : "down"; } lastDirY = dir.y; } const offsetX = isNil(data.offsetX) ? (currentX - startX) / scale : (data.offsetX as number); const offsetY = isNil(data.offsetY) ? (currentY - startY) / scale : (data.offsetY as number); const left = startLeft + offsetX; const top = startTop + offsetY; let delta = { left: left - currentRect.left, top: top - currentRect.top, }; if (!isNil(data.pageX) && currentX === lastX) { delta.left = 0; } if (!isNil(data.pageY) && currentY === lastY) { delta.top = 0; } if (!isNil(data.pageX) && !isNil(data.pageY) && currentX === lastX && currentY === lastY) { disableAdsorb = true; } const raw = delta; if (!disableAdsorb) { this.setCurrent(currentRect); delta = this.getAdsorbDelta(delta, distance || 5, dir); } currentRect.left += delta.left; currentRect.top += delta.top; lastX = currentX; lastY = currentY; return { raw, delta, offset: { left: currentRect.left - startLeft, top: currentRect.top - startTop, }, rect: { ...currentRect, }, }; }; } } export function createRefLine<T extends Rect = Rect>(opts: RefLineOpts<T>) { return new RefLine(opts); } export default RefLine;
the_stack
import { Component, ContentChildren, ElementRef, EventEmitter, Input, NgModule, Output, QueryList, Renderer2, Type, ViewChild, Directive, NgZone, ChangeDetectionStrategy, Injector } from "@angular/core"; import {CommonModule} from "@angular/common"; import {TranslateModule, TranslateService} from "@ngx-translate/core"; import { AbstractDialogComponentBase, DialogBase, DialogCallback, JigsawDialog, JigsawDialogModule } from "../dialog/dialog"; import {JigsawButton, JigsawButtonModule} from "../button/button"; import {InternalUtils} from "../../common/core/utils/internal-utils"; import {TranslateHelper} from "../../common/core/utils/translate-helper"; import {JigsawMovableModule} from "../../common/directive/movable/index"; import {ButtonInfo, PopupEffect, PopupInfo, PopupOptions, PopupService} from "../../common/service/popup.service"; import {CommonUtils} from "../../common/core/utils/common-utils"; import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar'; export enum AlertLevel { info, warning, error, confirm } export type AlertMessage = {message?: string, header: string}; @Component({ selector: 'jigsaw-alert, j-alert', templateUrl: 'alert.html', host: { '[class.jigsaw-alert-host]': 'true' }, changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawAlert extends AbstractDialogComponentBase { constructor(protected renderer: Renderer2, protected elementRef: ElementRef, protected _zone: NgZone, // @RequireMarkForCheck 需要用到,勿删 protected _injector: Injector) { super(renderer, elementRef, _zone, _injector); } @Output() public close: EventEmitter<any> = new EventEmitter<any>(); /** * @internal */ @ContentChildren(JigsawButton, {descendants: true}) public _$inlineButtons: QueryList<JigsawButton>; /** * @internal */ public _$alertClass = { 'jigsaw-alert-info': true, 'jigsaw-alert-warning': false, 'jigsaw-alert-error': false, 'jigsaw-alert-confirm': false }; private _level: AlertLevel = AlertLevel.info; /** * @NoMarkForCheckRequired */ @Input() public get level(): AlertLevel | string { return this._level; } public set level(value: AlertLevel | string) { switch (value) { case AlertLevel.warning: case "warning": this._level = AlertLevel.warning; break; case AlertLevel.error: case "error": this._level = AlertLevel.error; break; case AlertLevel.confirm: case "confirm": this._level = AlertLevel.confirm; break; case AlertLevel.info: case "info": default: this._level = AlertLevel.info; } this._$alertClass = { 'jigsaw-alert-info': this._level == AlertLevel.info, 'jigsaw-alert-warning': this._level == AlertLevel.warning, 'jigsaw-alert-error': this._level == AlertLevel.error, 'jigsaw-alert-confirm': this._level == AlertLevel.confirm } } private _icon: string; /** * @NoMarkForCheckRequired */ @Input() public get icon(): string { if (!this._icon) { switch (this._level) { case AlertLevel.info: this._icon = "iconfont-e9f9"; break; case AlertLevel.warning: this._icon = "iconfont-e437"; break; case AlertLevel.error: this._icon = "iconfont-e9b9"; break; case AlertLevel.confirm: this._icon = "iconfont-e9ef"; break; default: this._icon = "iconfont-ea39"; break; } } return this._icon; } public set icon(value: string) { this._icon = value; } protected getPopupElement(): HTMLElement { return this.elementRef.nativeElement.parentElement; } protected init() { const iconEl = this.elementRef.nativeElement.querySelector('.jigsaw-alert-icon'); if (!!iconEl) { this.renderer.addClass(iconEl, this.icon); } super.init(); } } @Directive() export abstract class JigsawCommonAlert extends DialogBase { /** * @NoMarkForCheckRequired */ @Input() public set initData(value: any) { if (!value) { return; } this.caption = value.title ? value.title : this._getDefaultTitle(); this.header = value.header ? value.header : this.caption; this.message = value.message ? value.message : ''; this.buttons = value.buttons ? value.buttons : this.buttons; } public abstract get dialog(): JigsawDialog; public abstract set dialog(value: JigsawDialog); public message: string; public header: string; public buttons: ButtonInfo[] = [{label: 'alert.button.ok'}]; public level: AlertLevel = AlertLevel.info; public static showAlert(what: Type<JigsawCommonAlert>, message: string | AlertMessage, callback?: DialogCallback, buttons?: ButtonInfo[], caption?: string, modal: boolean = true, popupOptions?: PopupOptions): PopupInfo { const msg: AlertMessage = typeof message == 'string' ? {header: message} : message; const po: PopupOptions = popupOptions ? popupOptions : { modal: modal, //是否模态 showEffect: PopupEffect.bubbleIn, hideEffect: PopupEffect.bubbleOut, shadowType: 'alert', borderRadius: '3px' }; po.modal = CommonUtils.isUndefined(po.modal) ? modal : po.modal; po.showEffect = CommonUtils.isUndefined(po.showEffect) ? PopupEffect.bubbleIn : po.showEffect; po.hideEffect = CommonUtils.isUndefined(po.hideEffect) ? PopupEffect.bubbleOut : po.hideEffect; po.shadowType = CommonUtils.isUndefined(po.shadowType) ? 'alert' : po.shadowType; po.borderRadius = CommonUtils.isUndefined(po.borderRadius) ? '3px' : po.borderRadius; if (CommonUtils.isDefined(po.size?.height)) { po.size.height = Math.min.apply(Math, [Math.max.apply(Math, [po.size.height, 240]), 600]) } const popupInfo = PopupService.instance.popup(what, po, {message: msg.message, header: msg.header, title: caption, buttons}); popupInfo.answer.subscribe(answer => { CommonUtils.safeInvokeCallback(null, callback, [answer]); popupInfo.answer.unsubscribe(); popupInfo.dispose(); }); return popupInfo; } private _getDefaultTitle(): string { switch (this.level) { case AlertLevel.warning: return 'alert.title.warning'; case AlertLevel.error: return 'alert.title.error'; case AlertLevel.confirm: return 'alert.title.confirm'; case AlertLevel.info: default: return 'alert.title.info'; } } protected constructor(protected _renderer: Renderer2, protected _elementRef: ElementRef) { super(); this._renderer.addClass(this._elementRef.nativeElement, 'jigsaw-common-alert'); } } @Component({ templateUrl: 'common-alert.html', selector: 'jigsaw-info-alert, j-info-alert', changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawInfoAlert extends JigsawCommonAlert { constructor(protected _renderer: Renderer2, protected _elementRef: ElementRef) { super(_renderer, _elementRef); } @ViewChild(JigsawAlert, {static: true}) public dialog: JigsawDialog; /** * @NoMarkForCheckRequired */ @Input() public message: string; /** * @NoMarkForCheckRequired */ @Input() public header: string; /** * @NoMarkForCheckRequired */ @Input() public caption: string; /** * @NoMarkForCheckRequired */ @Input() public level: AlertLevel = AlertLevel.info; /** * @NoMarkForCheckRequired */ @Input() public buttons: ButtonInfo[] = [{label: 'alert.button.ok', 'type': 'primary'}]; public static show(info: string | AlertMessage, callback?: DialogCallback, buttons?: ButtonInfo[], caption?: string, modal: boolean = true, popupOptions?: PopupOptions): PopupInfo { return JigsawCommonAlert.showAlert(JigsawInfoAlert, info, callback, buttons, caption, modal, popupOptions); } } @Component({ templateUrl: 'common-alert.html', selector: 'jigsaw-warning-alert, j-warning-alert', changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawWarningAlert extends JigsawCommonAlert { constructor(protected _renderer: Renderer2, protected _elementRef: ElementRef) { super(_renderer, _elementRef); } @ViewChild(JigsawAlert, {static: true}) public dialog: JigsawDialog; /** * @NoMarkForCheckRequired */ @Input() public message: string; /** * @NoMarkForCheckRequired */ @Input() public header: string; /** * @NoMarkForCheckRequired */ @Input() public caption: string; /** * @NoMarkForCheckRequired */ @Input() public level: AlertLevel = AlertLevel.warning; /** * @NoMarkForCheckRequired */ @Input() public buttons: ButtonInfo[] = [{label: 'alert.button.ok', 'type': 'warning'}]; public static show(info: string | AlertMessage, callback?: DialogCallback, buttons?: ButtonInfo[], caption?: string, modal: boolean = true, popupOptions?: PopupOptions): PopupInfo { return JigsawCommonAlert.showAlert(JigsawWarningAlert, info, callback, buttons, caption, modal, popupOptions); } } @Component({ templateUrl: 'common-alert.html', selector: 'jigsaw-error-alert, j-error-alert', changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawErrorAlert extends JigsawCommonAlert { constructor(protected _renderer: Renderer2, protected _elementRef: ElementRef) { super(_renderer, _elementRef); } @ViewChild(JigsawAlert, {static: true}) public dialog: JigsawDialog; /** * @NoMarkForCheckRequired */ @Input() public message: string; /** * @NoMarkForCheckRequired */ @Input() public header: string; /** * @NoMarkForCheckRequired */ @Input() public caption: string; /** * @NoMarkForCheckRequired */ @Input() public level: AlertLevel = AlertLevel.error; /** * @NoMarkForCheckRequired */ @Input() public buttons: ButtonInfo[] = [{label: 'alert.button.ok', 'type': 'error'}]; public static show(info: string | AlertMessage, callback?: DialogCallback, buttons?: ButtonInfo[], caption?: string, modal: boolean = true, popupOptions?: PopupOptions): PopupInfo { return JigsawCommonAlert.showAlert(JigsawErrorAlert, info, callback, buttons, caption, modal, popupOptions); } } @Component({ templateUrl: 'common-alert.html', selector: 'jigsaw-confirm-alert, j-confirm-alert', changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawConfirmAlert extends JigsawCommonAlert { constructor(protected _renderer: Renderer2, protected _elementRef: ElementRef) { super(_renderer, _elementRef); } @ViewChild(JigsawAlert, {static: true}) public dialog: JigsawDialog; /** * @NoMarkForCheckRequired */ @Input() public message: string; /** * @NoMarkForCheckRequired */ @Input() public header: string; /** * @NoMarkForCheckRequired */ @Input() public caption: string; /** * @NoMarkForCheckRequired */ @Input() public level: AlertLevel = AlertLevel.confirm; /** * @NoMarkForCheckRequired */ @Input() public buttons: ButtonInfo[] = [{label: 'alert.button.yes', 'type': 'primary'}, {label: 'alert.button.no'}]; public static show(info: string | AlertMessage, callback?: DialogCallback, buttons?: ButtonInfo[], caption?: string, modal: boolean = true, popupOptions?: PopupOptions): PopupInfo { return JigsawCommonAlert.showAlert(JigsawConfirmAlert, info, callback, buttons, caption, modal, popupOptions); } } @NgModule({ imports: [JigsawDialogModule, JigsawMovableModule, JigsawButtonModule, CommonModule, PerfectScrollbarModule, TranslateModule.forChild()], declarations: [JigsawAlert, JigsawInfoAlert, JigsawWarningAlert, JigsawErrorAlert, JigsawConfirmAlert], exports: [ JigsawDialogModule, JigsawMovableModule, JigsawAlert, JigsawInfoAlert, JigsawWarningAlert, JigsawErrorAlert, JigsawConfirmAlert ], providers: [TranslateService] }) export class JigsawAlertModule { constructor(translateService: TranslateService) { InternalUtils.initI18n(translateService, 'alert', { zh: { button: { ok: "确定", cancel: "取消", yes: "是", no: "否", abort: "终止", ignore: "忽略", retry: "重试" }, title: { info: "提示", warning: "警告", error: "错误", confirm: "确认" } }, en: { button: { ok: "OK", cancel: "Cancel", yes: "Yes", no: "No", abort: "Abort", ignore: "Ignore", retry: "Retry" }, title: { info: "Information", warning: "Warning", error: "Error", confirm: "Confirm" } } }); translateService.setDefaultLang(translateService.getBrowserLang()); TranslateHelper.languageChangEvent.subscribe(langInfo => { translateService.use(langInfo.curLang); }); } }
the_stack
import { OnInit, AfterViewInit } from '@angular/core'; import { Component } from '@angular/core'; import { ScriptLoaderService } from '../../../../_services/script-loader.service'; import { Ajax } from '../../../../shared/ajax/ajax.service'; declare let $: any; declare let toastr: any; declare let swal: any; @Component({ templateUrl: './env-params.component.html', }) export class EnvParamsComponent implements OnInit, AfterViewInit { formData: any = { type: 'add', pKey: '', pValue: '', }; dataList: any[] = []; datatable: any = null; queryParams: any = {}; constructor(private _script: ScriptLoaderService, private ajax: Ajax) { } ngAfterViewInit(): void { this.initData(); } ngOnInit(): void { } async initData() { await this.initEnvList(); await this.initEnvParamList(); this.initFormValid(); } async initEnvList() { let result = await this.ajax.get('/xhr/env'); let selectData = result.map(item => { return { id: item.id, text: item.name, }; }); $('#m_select2_5').select2({ placeholder: '请选择一个环境', data: selectData, }); $('#m_select2_5').change(() => { this.reCreateTable(); }); } reCreateTable() { this.datatable.destroy(); this.initEnvParamList(); } reloadData() { let envParam = $('#m_select2_5').val(); this.queryParams.envId = envParam; this.datatable.reload(); } async initEnvParamList() { let envParam = $('#m_select2_5').val(); // let result = await this.ajax.get('/xhr/envParam', { // envId: envParam, // }); this.queryParams.envId = envParam; var options = { data: { type: 'remote', source: { read: { url: '/xhr/envParam', method: 'GET', params: this.queryParams, map: function(raw) { // sample data mapping var dataSet = raw; if (typeof raw.data !== 'undefined') { dataSet = raw.data; } return dataSet; }, }, }, pageSize: 10, saveState: { cookie: true, webstorage: true, }, serverPaging: false, serverFiltering: false, serverSorting: false, autoColumns: false, }, layout: { theme: 'default', class: 'm-datatable--brand', scroll: true, height: null, footer: false, header: true, smoothScroll: { scrollbarShown: true, }, spinner: { overlayColor: '#000000', opacity: 0, type: 'loader', state: 'brand', message: true, }, icons: { sort: { asc: 'la la-arrow-up', desc: 'la la-arrow-down' }, pagination: { next: 'la la-angle-right', prev: 'la la-angle-left', first: 'la la-angle-double-left', last: 'la la-angle-double-right', more: 'la la-ellipsis-h', }, rowDetail: { expand: 'fa fa-caret-down', collapse: 'fa fa-caret-right', }, }, }, sortable: true, pagination: true, search: { // enable trigger search by keyup enter onEnter: false, // input text for search input: $('#generalSearch'), // search delay in milliseconds delay: 200, }, rows: { callback: function() { }, // auto hide columns, if rows overflow. work on non locked columns autoHide: false, }, // columns definition columns: [ // { // field: 'id', // title: 'id', // width: 80, // textAlign: 'center', // overflow: 'visible', // template: '{{id}}', // }, { field: 'pKey', title: '配置key', sortable: 'asc', filterable: false, width: 300, responsive: { visible: 'lg' }, template: '{{pKey}}', }, { field: 'pValue', title: '配置value', width: 300, overflow: 'visible', template: '{{pValue}}', }, { field: 'envParams', title: '操作', sortable: false, width: 100, overflow: 'visible', template: `<div class="item-operate" data-info={{id}}> <a class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill modifyItem" title="View"> <i class="la la-edit"></i> </a> <a class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill deleteItem" title="View"> <i class="la la-trash"></i> </a></div>`, }, ], toolbar: { layout: ['pagination', 'info'], placement: ['bottom'], //'top', 'bottom' items: { pagination: { type: 'default', pages: { desktop: { layout: 'default', pagesNumber: 6, }, tablet: { layout: 'default', pagesNumber: 3, }, mobile: { layout: 'compact', }, }, navigation: { prev: true, next: true, first: true, last: true, }, pageSizeSelect: [10, 20, 30, 50, 100], }, info: true, }, }, translate: { records: { processing: '正在获取环境列表', noRecords: '当前还没有配置环境', }, toolbar: { pagination: { items: { default: { first: '首页', prev: '上一页', next: '下一页', last: '末页', more: '更多页', input: 'Page number', select: '请选择每页显示数量', }, info: '显示第 {{start}} - {{end}} 条记录,总共 {{total}} 条', }, }, }, }, }; this.datatable = (<any>$('#m_datatable')).mDatatable(options); let self = this; $('#m_datatable').on('click', '.deleteItem', event => { let id = $(event.target) .parents('.item-operate') .attr('data-info'); self.deleteEnv(id); }); $('#m_datatable').on('click', '.modifyItem', event => { let id = $(event.target) .parents('.item-operate') .attr('data-info'); self.editEnv(id); }); } initFormValid() { /* * Translated default messages for the jQuery validation plugin. * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語) */ $.extend($.validator.messages, { required: '这是必填字段', remote: '请修正此字段', email: '请输入有效的电子邮件地址', url: '请输入有效的网址', date: '请输入有效的日期', dateISO: '请输入有效的日期 (YYYY-MM-DD)', number: '请输入有效的数字', digits: '只能输入数字', creditcard: '请输入有效的信用卡号码', equalTo: '你的输入不相同', extension: '请输入有效的后缀', maxlength: $.validator.format('最多可以输入 {0} 个字符'), minlength: $.validator.format('最少要输入 {0} 个字符'), rangelength: $.validator.format( '请输入长度在 {0} 到 {1} 之间的字符串' ), range: $.validator.format('请输入范围在 {0} 到 {1} 之间的数值'), max: $.validator.format('请输入不大于 {0} 的数值'), min: $.validator.format('请输入不小于 {0} 的数值'), }); $('#env-params-form').validate({ // define validation rules rules: { pKey: { required: true, }, pValue: { required: true, }, }, //display error alert on form submit invalidHandler: function(event, validator) { console.log(event); }, submitHandler: form => { this.saveModal(); }, }); } async deleteEnv(id) { swal({ title: 'Are you sure?', text: '你确定删除这个环境参数吗?', type: 'warning', showCancelButton: !0, confirmButtonText: '确定', cancelButtonText: '取消', }).then(async e => { if (e.value) { try { let result = await this.ajax.delete( '/xhr/envParam?id=' + id, {} ); toastr.success('删除环境参数成功!'); this.reloadData(); } catch (e) { toastr.error('删除环境参数失败!'); } } }); } async editEnv(id) { let allData = this.datatable.getColumn(id).originalDataSet; let result = allData.filter(item => { if (item.id == id) { return true; } else { return false; } }); this.formData.type = 'edit'; this.formData.pKey = result[0].pKey; this.formData.pValue = result[0].pValue; this.formData.id = id; $('#m_modal_1').modal('show'); } createEnvParam() { this.formData.pKey = ''; this.formData.pValue = ''; this.formData.type = 'add'; $('#m_modal_1').modal('show'); } closeModal() { $('#m_modal_1').modal('hide'); } async saveModal() { if (this.formData.type === 'add') { try { let params = { pKey: this.formData.pKey, pValue: this.formData.pValue, }; let result = await this.ajax.post( '/xhr/envParam?envId=' + $('#m_select2_5').val(), params ); toastr.success('新增环境成功!'); $('#m_modal_1').modal('hide'); this.reloadData(); } catch (e) { toastr.error('新增环境失败!'); } } else { try { let params = { pKey: this.formData.pKey, pValue: this.formData.pValue, id: this.formData.id, }; let result = await this.ajax.put('/xhr/envParam', params); toastr.success('编辑环境成功!'); $('#m_modal_1').modal('hide'); this.reloadData(); } catch (e) { toastr.error('编辑环境失败!'); } } } }
the_stack
import F6 from '../../src'; import TreeGraph from '../../src/extends/graph/treeGraph'; import Algorithm from '@antv/algorithm'; import { isNumber } from '@antv/util'; F6.registerGraph('TreeGraph', TreeGraph); const div = document.createElement('div'); div.id = 'container'; document.body.appendChild(div); F6.registerNode( 'tree-node', { draw(cfg, group) { const { style = { fill: '#fff', stroke: '#ccc' } } = cfg; const r = isNumber(cfg.size) ? cfg.size / 2 : 5; group.addShape('circle', { attrs: { x: 0, y: 0, r, ...style, }, name: 'circle-shape', draggable: true, }); if (cfg.label) { this.drawLabel(cfg, group); } const bbox = group.getBBox(); const keyShape = group.addShape('rect', { attrs: { x: bbox.minX - 4, y: bbox.minY - 2, width: bbox.width + 8, height: bbox.height + 2, fill: '#fff', lineWidth: 0, }, draggable: true, name: 'tree-node-keyShape', }); keyShape.toBack(); return keyShape; }, getAnchorPoints(cfg) { return ( cfg.anchorPoints || [ [0, 0.5], [1, 0.5], [0.25, 0], [0.75, 0], [0.2, 1], [0.8, 1], ] ); }, update: undefined, }, 'circle', ); describe('org', () => { it('org', () => { const tips = document.createElement('div'); tips.innerHTML = `Tips: <br/>&nbsp; - 'control'+'f':图内容适应画布大小。 <br/> &nbsp; - '+':放大。 <br/>&nbsp; - '-':缩小。 <br/>&nbsp; - 若您正在使用鼠标, <br/>&nbsp;&nbsp;&nbsp; - 滚轮:上下滚动画布; <br/>&nbsp;&nbsp;&nbsp; - 按住 'shift' 使用滚轮:左右滚动画布。 <br/>&nbsp;&nbsp;&nbsp; - 按住 'control' 使用滚轮:缩放画布。 <br/><br/>`; div.appendChild(tips); const broCheckBox = document.createElement('input'); broCheckBox.type = 'checkbox'; broCheckBox.checked = true; broCheckBox.name = 'broCheckBox'; div.appendChild(broCheckBox); const broCheckLabel = document.createElement('label'); broCheckLabel.for = 'brocCheckLabel'; broCheckLabel.innerHTML = '显示兄弟关系'; div.appendChild(broCheckLabel); const orgCheckBox = document.createElement('input'); orgCheckBox.type = 'checkbox'; orgCheckBox.checked = true; orgCheckBox.style.marginLeft = '8px'; div.appendChild(orgCheckBox); const orgCheckLabel = document.createElement('label'); orgCheckLabel.for = 'brocCheckLabel'; orgCheckLabel.innerHTML = '显示团队关系'; div.appendChild(orgCheckLabel); const wenyaGroupNode = [ // ---- 问崖 group ----- { id: 'wenya', label: '问崖', isTL: true, index: 1, comboId: 'wenya-group', }, { id: 'boyu', label: '柏愚', index: 2, comboId: 'wenya-group', }, { id: 'wuchen', label: '伍沉', index: 8, comboId: 'wenya-group', }, { id: 'yeting', label: '烨亭', index: 7, comboId: 'wenya-group', }, { id: 'beidao', label: '北岛', index: 9, comboId: 'wenya-group', }, { id: 'wenyu', label: '文瑀', index: 3, comboId: 'wenya-group', }, { id: 'canglang', label: '沧浪', index: 1, comboId: 'wenya-group', }, { id: 'cangdong', label: '沧东', index: 6, comboId: 'wenya-group', }, { id: 'juze', label: '聚则', index: 11, comboId: 'wenya-group', }, { id: 'shiwu', label: '十吾', index: 10, comboId: 'wenya-group', }, { id: 'shanguo', label: '山果', index: 5, comboId: 'wenya-group', }, { id: 'duomu', label: '多牧', index: 4, comboId: 'wenya-group', }, ]; const guangzhiGroupNode = [ // ---- 广知 group ----- { id: 'guangzhi', label: '广知', isTL: true, index: 5, comboId: 'guangzhi-group', }, { id: 'kahun', label: '卡魂', index: 1, comboId: 'guangzhi-group', }, { id: 'linyu', label: '麟于', index: 3, comboId: 'guangzhi-group', }, { id: 'yanlin', label: '言凌', index: 5, comboId: 'guangzhi-group', }, { id: 'jianming', label: '涧鸣', index: 2, comboId: 'guangzhi-group', }, { id: 'zimeng', label: '子蒙', index: 4, comboId: 'guangzhi-group', }, ]; const xuanyuGroupNode = [ // ---- 轩与 group ----- { id: 'xuanyu', label: '轩与', isTL: true, index: 0, comboId: 'xuanyu-group', }, { id: 'qingbi', label: '青壁', index: 1, comboId: 'xuanyu-group', }, { id: 'jinxin', label: '谨欣', index: 2, comboId: 'xuanyu-group', }, { id: 'sishu', label: '思澍', index: 5, comboId: 'xuanyu-group', }, { id: 'jiuyao', label: '九瑶', index: 3, comboId: 'xuanyu-group', }, { id: 'yifeng', label: '依枫', index: 2, comboId: 'xuanyu-group', }, ]; const yungangGroupNode = [ // ---- 云冈 group ----- { id: 'yungang', label: '云冈', isTL: true, index: 7, comboId: 'yungang-group', }, { id: 'aiyin', label: '艾因', index: 5, comboId: 'yungang-group', }, { id: 'feimao', label: '飝猫', index: 2, comboId: 'yungang-group', }, { id: 'maosong', label: '茂松', index: 6, comboId: 'yungang-group', }, { id: 'yian', label: '意安', index: 1, comboId: 'yungang-group', }, { id: 'jili', label: '蒺藜', index: 3, comboId: 'yungang-group', }, { id: 'gengsheng', label: '更笙', index: 7, comboId: 'yungang-group', }, { id: 'chenyuan', label: '宸缘', index: 4, comboId: 'yungang-group', }, ]; const qingshengGroupNode = [ // ---- 轻声 group ----- { id: 'qingsheng', label: '轻声', isTL: true, index: 2, comboId: 'qingsheng-group', }, { id: 'baihui', label: '白绘', index: 5, comboId: 'qingsheng-group', }, { id: 'wanmu', label: '万木', index: 13, comboId: 'qingsheng-group', }, { id: 'yingying', label: '缨缨', index: 7, comboId: 'qingsheng-group', }, { id: 'yuxi', label: '羽熙', index: 3, comboId: 'qingsheng-group', }, { id: 'xiangrong', label: '向戎', index: 6, comboId: 'qingsheng-group', }, { id: 'kefu', label: '珂甫', index: 9, comboId: 'qingsheng-group', }, { id: 'guji', label: '顾己', index: 4, comboId: 'qingsheng-group', }, { id: 'fujin', label: '福晋', index: 13, comboId: 'qingsheng-group', }, { id: 'chaokai', label: '朝凯', index: 12, comboId: 'qingsheng-group', }, { id: 'buming', label: '步茗', index: 2, comboId: 'qingsheng-group', }, { id: 'yuyi', label: '羽依', index: 8, comboId: 'qingsheng-group', }, { id: 'yisi', label: '一四', index: 11, comboId: 'qingsheng-group', }, { id: 'xinming', label: '新茗', index: 12, comboId: 'qingsheng-group', }, { id: 'xiaowei', label: '逍为', index: 15, comboId: 'qingsheng-group', }, { id: 'mingshi', label: '明是', index: 1, comboId: 'qingsheng-group', }, ]; const suboGroupNode = [ // ---- 苏泊 group ----- { id: 'subo', label: '苏泊', isTL: true, index: 8, comboId: 'subo-group', }, { id: 'junwen', label: '峻文', index: 5, comboId: 'subo-group', }, { id: 'nantao', label: '南桃', index: 2, comboId: 'subo-group', }, { id: 'zishang', label: '子裳', index: 3, comboId: 'subo-group', }, { id: 'mutu', label: '木兔', index: 4, comboId: 'subo-group', }, { id: 'xiandu', label: '贤渡', index: 6, comboId: 'subo-group', }, { id: 'jiandong', label: '建东', index: 7, comboId: 'subo-group', }, { id: 'qinke', label: '卿珂', index: 1, comboId: 'subo-group', }, ]; const bojunGroupNode = [ // ---- 伯骏 group ----- { id: 'bojun', label: '伯骏', isTL: true, index: 6, comboId: 'bojun-group', }, { id: 'changzhe', label: '长哲', index: 4, comboId: 'bojun-group', }, { id: 'xiaojie', label: '逍杰', index: 7, comboId: 'bojun-group', }, { id: 'xiaoyao', label: '小耀', index: 1, comboId: 'bojun-group', }, { id: 'taotang', label: '陶唐', index: 5, comboId: 'bojun-group', }, { id: 'xingyi', label: '星翊', index: 6, comboId: 'bojun-group', }, { id: 'guangsheng', label: '光生', index: 3, comboId: 'bojun-group', }, { id: 'miaozi', label: '妙子', index: 2, comboId: 'bojun-group', }, ]; const data = { nodes: [ ...wenyaGroupNode, ...qingshengGroupNode, ...xuanyuGroupNode, ...guangzhiGroupNode, ...yungangGroupNode, ...suboGroupNode, ...bojunGroupNode, { id: 'yushu', label: '御术', }, ], edges: [], combos: [ { id: 'wenya-group', label: 'TL 问崖', style: { fill: '#C4E3B2', stroke: '#C4E3B2', opacity: 0.3, }, }, { id: 'guangzhi-group', label: 'TL 广知', style: { stroke: '#99C0ED', fill: '#99C0ED', opacity: 0.3, }, }, { id: 'xuanyu-group', label: 'TL 轩与', style: { stroke: '#99C0ED', fill: '#99C0ED', opacity: 0.3, }, }, { id: 'yungang-group', label: 'TL 云冈', style: { stroke: '#99C0ED', fill: '#99C0ED', opacity: 0.3, }, }, { id: 'qingsheng-group', label: 'TL 轻声', style: { stroke: '#99C0ED', fill: '#99C0ED', opacity: 0.3, }, }, { id: 'subo-group', label: 'TL 苏泊', style: { stroke: '#99C0ED', fill: '#99C0ED', opacity: 0.3, }, }, { id: 'bojun-group', label: 'TL 伯骏', style: { stroke: '#99C0ED', fill: '#99C0ED', opacity: 0.3, }, }, // { // id: 'other-group', // label: '其他组', // style: { // stroke: '#aaa', // fill: '#aaa', // opacity: 0.3 // }, // }, ], }; const otherGroupNodes = [ // ---- 其他 group ----- { id: 'shitiao', label: '十条', // comboId: 'other-group', }, { id: 'bianliu', label: '边柳', // comboId: 'other-group', }, { id: 'shanye', label: '善叶', // comboId: 'other-group', }, { id: 'dongke', label: '东科', // comboId: 'other-group', }, { id: 'jueyun', label: '绝云', // comboId: 'other-group', }, { id: 'yier', label: '翳弭', // comboId: 'other-group', }, { id: 'lingyu', label: '灵玉', // comboId: 'other-group', }, { id: 'lingyi', label: '翎一', // comboId: 'other-group', }, { id: 'wangxiang', label: '望乡', // comboId: 'other-group', }, { id: 'zhiqin', label: '之勤', // comboId: 'other-group', }, { id: 'pianyou', label: '偏右', // comboId: 'other-group', }, { id: 'longcha', label: '龙茶', // comboId: 'other-group', }, { id: 'xiaoqing', label: '萧庆', // comboId: 'other-group', }, { id: 'jiangtianyi', label: '姜天意', // comboId: 'other-group', }, { id: 'qidao', label: '祈祷', // comboId: 'other-group', }, { id: 'daozhu', label: '岛煮', // comboId: 'other-group', }, { id: 'ohuo', label: '哦豁', // comboId: 'other-group', }, { id: 'yuanfeng', label: '远峰', // comboId: 'other-group', }, { id: 'digui', label: '递归', // comboId: 'other-group', }, { id: 'binying', label: '兵营', isLeave: true, }, { id: 'zelu', label: '泽鹿', isLeave: true, }, { id: 'tianzhu', label: '恬竹', isLeave: true, }, ]; const broEdges = [ // wenya { source: 'jueyun', target: 'wenya', }, { source: 'wenya', target: 'boyu', }, { source: 'boyu', target: 'wuchen', }, { source: 'wenya', target: 'yeting', }, { source: 'wenya', target: 'beidao', }, { source: 'boyu', target: 'wenyu', }, { source: 'qingbi', target: 'canglang', }, { source: 'bianliu', target: 'cangdong', }, { source: 'xiaoqing', target: 'juze', }, { source: 'juze', target: 'shiwu', }, { source: 'shanye', target: 'shanguo', }, { source: 'dongke', target: 'duomu', }, // guangzhi { source: 'lingyi', target: 'guangzhi', }, { source: 'wangxiang', target: 'linyu', }, { source: 'kahun', target: 'jianming', }, { source: 'guangzhi', target: 'kahun', }, { source: 'linyu', target: 'zimeng', }, // xuanyu { source: 'boyu', target: 'qingbi', }, { source: 'canglang', target: 'jinxin', }, { source: 'xuanyu', target: 'sishu', }, { source: 'lingyu', target: 'jiuyao', }, { source: 'jinxin', target: 'yifeng', }, // yungang { source: 'zhiqin', target: 'yungang', }, { source: 'yungang', target: 'aiyin', }, { source: 'yungang', target: 'feimao', }, { source: 'yungang', target: 'maosong', }, { source: 'yier', target: 'yian', }, { source: 'feimao', target: 'jili', }, { source: 'yungang', target: 'gengsheng', }, { source: 'feimao', target: 'chenyuan', }, // qingsheng { source: 'jueyun', target: 'qingsheng', }, { source: 'mingshi', target: 'baihui', }, { source: 'xiaowei', target: 'wanmu', }, { source: 'pianyou', target: 'yingying', }, { source: 'wuchen', target: 'yuxi', }, { source: 'mingshi', target: 'xiangrong', }, { source: 'longcha', target: 'kefu', }, { source: 'juze', target: 'guji', }, { source: 'shitiao', target: 'fujin', }, { source: 'yisi', target: 'chaokai', }, { source: 'xiaoqing', target: 'buming', }, { source: 'jiangtianyi', target: 'yuyi', }, { source: 'daozhu', target: 'yisi', }, { source: 'qingsheng', target: 'xinming', }, { source: 'qidao', target: 'xiaowei', }, { source: 'wenya', target: 'mingshi', }, // subo { source: 'qidao', target: 'subo', }, { source: 'subo', target: 'junwen', }, { source: 'subo', target: 'nantao', }, { source: 'nantao', target: 'zishang', }, { source: 'zishang', target: 'mutu', }, { source: 'junwen', target: 'xiandu', }, { source: 'subo', target: 'jiandong', }, { source: 'ohuo', target: 'qinke', }, // bojun { source: 'binying', target: 'bojun', }, { source: 'yuanfeng', target: 'changzhe', }, { source: 'digui', target: 'xiaoyao', }, { source: 'bojun', target: 'xiaojie', }, { source: 'bojun', target: 'xingyi', }, { source: 'changzhe', target: 'taotang', }, { source: 'zelu', target: 'guangsheng', }, { source: 'tianzhu', target: 'miaozi', }, ]; const organizationEdges = [ // TL xuanyu -> members { source: 'xuanyu', target: 'jinxin', }, { source: 'xuanyu', target: 'yifeng', }, { source: 'xuanyu', target: 'jiuyao', }, { source: 'xuanyu', target: 'sishu', }, { source: 'xuanyu', target: 'qingbi', }, // TL bojun -> members { source: 'bojun', target: 'taotang', }, { source: 'bojun', target: 'changzhe', }, { source: 'bojun', target: 'guangsheng', }, { source: 'bojun', target: 'miaozi', }, { source: 'bojun', target: 'xiaoyao', }, { source: 'bojun', target: 'xingyi', }, { source: 'bojun', target: 'xiaojie', }, // TL qingsheng -> members { source: 'qingsheng', target: 'yisi', }, { source: 'qingsheng', target: 'mingshi', }, { source: 'qingsheng', target: 'buming', }, { source: 'qingsheng', target: 'xiaowei', }, { source: 'qingsheng', target: 'yingying', }, { source: 'qingsheng', target: 'yuxi', }, { source: 'qingsheng', target: 'yuyi', }, { source: 'qingsheng', target: 'kefu', }, { source: 'qingsheng', target: 'guji', }, { source: 'qingsheng', target: 'chaokai', }, { source: 'qingsheng', target: 'fujin', }, { source: 'qingsheng', target: 'xinming', }, { source: 'qingsheng', target: 'wanmu', }, { source: 'qingsheng', target: 'baihui', }, { source: 'qingsheng', target: 'xiangrong', }, // TL subo -> members { source: 'subo', target: 'qinke', }, { source: 'subo', target: 'mutu', }, { source: 'subo', target: 'zishang', }, { source: 'subo', target: 'xiandu', }, { source: 'subo', target: 'junwen', }, { source: 'subo', target: 'nantao', }, { source: 'subo', target: 'jiandong', }, // TL wenya -> members { source: 'wenya', target: 'juze', }, { source: 'wenya', target: 'canglang', }, { source: 'wenya', target: 'cangdong', }, { source: 'wenya', target: 'shiwu', }, { source: 'wenya', target: 'duomu', }, { source: 'wenya', target: 'shanguo', }, { source: 'wenya', target: 'boyu', }, { source: 'wenya', target: 'wuchen', }, { source: 'wenya', target: 'wenyu', }, { source: 'wenya', target: 'beidao', }, { source: 'wenya', target: 'yeting', }, // TL yungang -> members { source: 'yungang', target: 'yian', }, { source: 'yungang', target: 'jili', }, { source: 'yungang', target: 'chenyuan', }, { source: 'yungang', target: 'aiyin', }, { source: 'yungang', target: 'maosong', }, { source: 'yungang', target: 'gengsheng', }, { source: 'yungang', target: 'feimao', }, // TL guangzhi -> members { source: 'guangzhi', target: 'kahun', }, { source: 'guangzhi', target: 'linyu', }, { source: 'guangzhi', target: 'yanlin', }, { source: 'guangzhi', target: 'jianming', }, { source: 'guangzhi', target: 'zimeng', }, // yushu -> TL { source: 'yushu', target: 'wenya', }, { source: 'yushu', target: 'xuanyu', }, { source: 'yushu', target: 'guangzhi', }, { source: 'yushu', target: 'qingsheng', }, { source: 'yushu', target: 'bojun', }, { source: 'yushu', target: 'subo', }, { source: 'yushu', target: 'yungang', }, ]; data.edges = organizationEdges; const clusterMap = []; data.combos.forEach((cluster, i) => { clusterMap[cluster.id] = cluster; clusterMap[cluster.id].idx = i; }); const nodeMap = {}; const clusterPos = {}; let newPosIdx = 0; data.nodes.forEach((node) => { node.cluster = node.comboId || `random|||${Math.random()}`; nodeMap[node.id] = node; node.indegree = 0; node.outdegree = 0; node.neighbors = []; if (!clusterPos[node.cluster]) { clusterPos[node.cluster] = { x: ((newPosIdx % 5) + 1) * 100, y: (Math.round(newPosIdx / 5) + 1) * 100, }; newPosIdx += 1; } }); data.edges.forEach((edge) => { nodeMap[edge.source].outdegree++; nodeMap[edge.target].indegree++; nodeMap[edge.source].neighbors.push(edge.target); nodeMap[edge.target].neighbors.push(edge.source); edge.style = { opacity: 0, }; }); const subjectColors = [ '#ed9b65', '#83c4f7', '#a055be', '#f7cc60', '#e36e71', '#83c84a', '#d8824f', ]; // const subjectColors = [ // '#F08BB4', // '#5B63FF', // // '#44E6C1', // '#1BE6B9', // // '#FF5A34', // '#F76C6C', // // '#AE6CFF', // // '#7F86FF', // // '#61DDAA', // '#F6BD16', // // '#7262FD', // // '#78D3F8', // '#9661BC', // '#F6903D', // '#008685', // // '#F08BB4', // ]; const backColor = '#fff'; const theme = 'default'; const disableColor = '#777'; const colorSets = F6.Util.getColorSetsBySubjectColors( subjectColors, backColor, theme, disableColor, ); data.nodes.forEach((node) => { node.size = node.indegree + node.outdegree + 5; if (node.isLeave) { // node.style = { // fill: '#ccc', // stroke:'#ccc', // } node.subjectColor = '#ccc'; } else if (node.cluster.split('|||')[0] === 'random') { // node.style = { // fill: '#999', // stroke: '#999', // } node.subjectColor = '#999'; } else { const colorSet = colorSets[clusterMap[node.cluster].idx % subjectColors.length]; // node.style = { // fill: colorSet.mainFill, // stroke: colorSet.mainStroke, // } node.subjectColor = colorSet.mainStroke; } // if (node.isTL) { // node.style.fill = node.subjectColor//.style.stroke // } }); const { minimumSpanningTree } = Algorithm; const treeEdges = minimumSpanningTree(data); let tree; const establishedNode = {}; data.nodes.forEach((node) => { if (node.indegree === 0) { tree = { ...node }; establishedNode[node.id] = tree; } }); treeEdges.forEach((edge) => { let node; if (!establishedNode[edge.source]) node = { ...nodeMap[edge.source] }; else node = establishedNode[edge.source]; let targetNode; if (!establishedNode[edge.target]) { targetNode = { ...nodeMap[edge.target] }; } else targetNode = establishedNode[edge.target]; if (!node.children) node.children = [targetNode]; else node.children.push(targetNode); establishedNode[edge.source] = node; establishedNode[edge.target] = targetNode; // if (!tree) tree = node }); const sortTreeChildren = (tree) => { if (tree.children) { tree.children.sort((a, b) => { return a.index - b.index; }); tree.children.forEach((child) => { sortTreeChildren(child); }); } return; }; sortTreeChildren(tree); const width = 1200, height = 800; const graph = new F6.TreeGraph({ container: 'container', width, height, fitView: true, minZoom: 0.00001, animate: false, // groupByTypes: false, // linkCenter: true, modes: { default: [ { type: 'lasso-select', trigger: 'drag', selectedState: 'select', }, 'scroll-canvas', { type: 'activate-relations', inactiveState: 'dark', activeState: 'light', }, { type: 'shortcuts-call', combinedKey: 'f', functionName: 'fitView', }, ], }, layout: { type: 'mindmap', direction: 'H', getHeight: () => { return 10; }, getWidth: () => { return 16; }, getVGap: () => { return 6; }, getHGap: () => { return 50; }, getSide: (d) => { if (d.id === 'wenya' || d.id === 'qingsheng' || d.id === 'xuanyu') { return 'right'; } return 'left'; }, }, defaultNode: { // size: [60, 30], // type: 'rect', type: 'tree-node', size: 5, labelCfg: { position: 'right', offset: 5, style: { stroke: '#fff', lineWidth: 3, fontFamily: 'Arial', }, }, // anchorPoints: [[0.5, 0], [0.5, 1]] }, defaultEdge: { type: 'cubic-horizontal', style: { stroke: '#D8D8D8', opacity: 0.4, }, labelCfg: { style: { fontFamily: 'Arial', }, }, }, nodeStateStyles: { light: { 'text-shape': { fontSize: 12, }, }, dark: { opacity: 0.3, 'circle-shape': { opacity: 0.3, }, 'text-shape': { opacity: 0.3, }, }, select: { shadowBlur: 10, }, }, edgeStateStyles: { dark: { opacity: 0.1, }, }, }); let centerX = 0; graph.node((node) => { if (node.id === 'yushu') { centerX = node.x; return { type: 'rect', size: [40, 20], style: { stroke: '#509FEE', fill: '#fff', lineWidth: 2, radius: 4, shadowColor: '#509FEE', }, labelCfg: { position: 'center', style: { stroke: '#fff', lineWidth: 3, fontFamily: 'Arial', fill: '#509FEE', }, }, }; } let position = 'left'; if (node.x > centerX && node.isOtherGroup) position = 'right'; else if (node.x <= centerX && node.isOtherGroup) position = 'left'; else if (node.x > centerX) position = 'left'; else if (node.x <= centerX) position = 'right'; return { style: { stroke: node.isLeave ? '#eee' : '#d8d8d8', fill: node.isTL ? node.subjectColor : node.isLeave ? '#eee' : '#fff', lineWidth: node.isTL ? 0 : 2, shadowColor: node.subjectColor, }, labelCfg: { position, style: { stroke: '#fff', fill: node.isLeave ? '#ccc' : node.subjectColor || '#999', lineWidth: 3, fontFamily: 'Arial', fontSize: node.isTL ? 12 : 10, }, }, }; }); graph.on('afterlayout', (e) => { const otherGroupNodeMap = {}; otherGroupNodes.forEach((oNode) => { oNode.isOtherGroup = true; otherGroupNodeMap[oNode.id] = oNode; }); broEdges.forEach((bEdge) => { bEdge.isBroEdge = true; let sourceNode = graph.findDataById(bEdge.source); const targetNode = graph.findDataById(bEdge.target); if (!sourceNode && graph.findById(bEdge.source)) sourceNode = graph.findById(bEdge.source).getModel(); const newNodeX = targetNode.isTL ? targetNode.x : targetNode.x < centerX ? targetNode.x - 120 : targetNode.x + 120; let newNodeY = targetNode.isTL ? targetNode.y - 50 : targetNode.y; const sourceNodeData = otherGroupNodeMap[bEdge.source]; if (!sourceNode) { sourceNodeData.type = 'tree-node'; sourceNodeData.x = newNodeX; sourceNodeData.y = newNodeY; sourceNodeData.style = { stroke: '#ccc', fill: '#ccc', shadowColor: '#ccc', }; graph.addItem('node', sourceNodeData); sourceNode = sourceNodeData; } else if (sourceNodeData) { newNodeY = (sourceNode.y + newNodeY) / 2; otherGroupNodes.forEach((oNode) => { if (oNode.x === sourceNode.x && Math.abs(newNodeY - oNode.y) < 10) newNodeY += 20; }); graph.updateItem(sourceNode.id, { y: newNodeY, }); // 如果是重复的 isOtherGroup sourceNode,更新相关的边 const relatedEdges = graph.findById(bEdge.source).getEdges(); relatedEdges && relatedEdges.forEach((rEdge) => { const reModel = rEdge.getModel(); const sn = graph.findById(reModel.source).getModel(); const tn = graph.findById(reModel.target).getModel(); let a = 0; const xDiff = sn.x - tn.x; const yDiff = sn.y - tn.y; if (Math.abs(xDiff) < Math.abs(yDiff)) a = yDiff < 0 ? 90 : 270; else a = xDiff < 0 ? 0 : 180; let sourceAnchor = undefined, targetAnchor = undefined; if (!sn.isTL && !tn.isTL) { if (sn.isOtherGroup) sourceAnchor = tn.x < centerX ? 1 : 0; else sourceAnchor = tn.x < centerX ? 0 : 1; targetAnchor = tn.x < centerX ? 0 : 1; } // else if (tn.isTL) { // sourceAnchor = tn.x < centerX ? 5 : 4; // if (tn.y > sn.y) targetAnchor = tn.x < centerX ? 2 : 3; // else targetAnchor = tn.x < centerX ? 4 : 5; // } graph.updateItem(rEdge, { style: { stroke: `l(${a}) 0:${sn.subjectColor || '#d8d8d8'} 1:${ tn.subjectColor || '#d8d8d8' }`, }, sourceAnchor, targetAnchor, }); }); } const sourceColor = sourceNode.subjectColor || '#d8d8d8'; const targetColor = targetNode.subjectColor; let angle = 0; const xDiff = sourceNode.x - targetNode.x; const yDiff = sourceNode.y - targetNode.y; if (Math.abs(xDiff) < Math.abs(yDiff)) angle = yDiff < 0 ? 90 : 270; else angle = xDiff < 0 ? 0 : 180; bEdge.style = { lineDash: [2, 2], lineWidth: 2, opaicty: 0.1, stroke: `l(${angle}) 0:${sourceColor} 1:${targetColor}`, // '#5F95FF' endArrow: { path: F6.Arrow.triangle(6, 8, 0), fill: targetColor, lineWidth: 0.1, }, }; if (sourceNode.x === targetNode.x && !targetNode.isTL) { bEdge.type = 'quadratic'; const yDiff = sourceNode.y - targetNode.y; const sign = (yDiff < 0 ? -1 : 1) * (sourceNode.x > centerX ? -1 : 1); bEdge.curveOffset = -3.5 * sign * Math.sqrt(Math.abs(yDiff)); } else if (sourceNode.x === targetNode.x && targetNode.isTL) { bEdge.type = 'line'; } if (!sourceNode.isTL && !targetNode.isTL) { if (sourceNode.isOtherGroup) { bEdge.sourceAnchor = targetNode.x < centerX ? 1 : 0; } else { bEdge.sourceAnchor = targetNode.x < centerX ? 0 : 1; } bEdge.targetAnchor = targetNode.x < centerX ? 0 : 1; } // else if (targetNode.isTL) { // bEdge.sourceAnchor = targetNode.x < centerX ? 5 : 4; // if (targetNode.y > sourceNode.y) bEdge.targetAnchor = targetNode.x < centerX ? 2 : 3; // else bEdge.targetAnchor = targetNode.x < centerX ? 4 : 5; // } graph.addItem('edge', bEdge); }); graph.getEdges().forEach((edge) => { const model = edge.getModel(); if (model.isBroEdge) return; const color = edge.getTarget().getModel().subjectColor; graph.updateItem(edge, { style: { stroke: color, }, }); }); }); const moveTree = (tree, dx, dy) => { if (!tree) return; tree.x += dx; tree.y += dy; if (tree.children) { tree.children.forEach((subTree) => { moveTree(subTree, dx, dy); }); } }; let previousX, previousY; graph.on('node:dragstart', (e) => { previousX = e.x; previousY = e.y; }); graph.on('node:drag', (e) => { const selectedNodes = graph.findAllByState('node', 'select'); const dx = e.x - previousX; const dy = e.y - previousY; if (selectedNodes && selectedNodes.length) { selectedNodes.forEach((sNode) => { sNode.getModel().x += dx; sNode.getModel().y += dy; }); } else { moveTree(e.item.getModel(), dx, dy); } graph.refreshPositions(); previousX = e.x; previousY = e.y; }); graph.data(tree); graph.render(); let enableBroView = true, enableOrgView = true; broCheckBox.addEventListener('click', (e) => { enableBroView = !enableBroView; graph.getEdges().forEach((edge) => { const model = edge.getModel(); if (!model.isBroEdge) return; if (enableBroView) edge.show(); else edge.hide(); }); graph.getNodes().forEach((node) => { const model = node.getModel(); if (!model.isOtherGroup) return; if (enableBroView) node.show(); else node.hide(); }); }); orgCheckBox.addEventListener('click', (e) => { enableOrgView = !enableOrgView; graph.getEdges().forEach((edge) => { const model = edge.getModel(); if (model.isBroEdge) return; if (enableOrgView) edge.show(); else edge.hide(); }); }); // 按键缩放 document.onkeydown = function (event) { var e = event || window.event || arguments.callee.caller.arguments[0]; if (e && (e.key === '+' || e.key === '=')) { graph.zoom(1.1, { x: width / 2, y: height / 2 }); } if (e && (e.key === '-' || e.key === '_')) { graph.zoom(0.9, { x: width / 2, y: height / 2 }); } }; // legend const rootGroup = graph.getGroup(); const legendBegin = graph.getPointByCanvas(16, graph.getHeight() - 200); const legendNodeR = 3; const legendLabelMargin = 16; const legendItemHeight = 24; // 实心节点 rootGroup.addShape('circle', { attrs: { x: legendBegin.x + 8, y: legendBegin.y, fill: '#509FEE', lineWidth: 2, r: legendNodeR, }, }); rootGroup.addShape('text', { attrs: { x: legendBegin.x + 8 + legendLabelMargin, y: legendBegin.y, text: 'TL 节点', fill: '#509FEE', textBaseline: 'middle', }, }); // 空心节点 rootGroup.addShape('circle', { attrs: { x: legendBegin.x + 8, y: legendBegin.y + legendItemHeight, stroke: '#999', fill: '#fff', lineWidth: 2, r: legendNodeR, }, }); rootGroup.addShape('text', { attrs: { x: legendBegin.x + 8 + legendLabelMargin, y: legendBegin.y + legendItemHeight, text: '成员节点', fill: '#509FEE', textBaseline: 'middle', }, }); // 灰色空心 rootGroup.addShape('circle', { attrs: { x: legendBegin.x + 8, y: legendBegin.y + 2 * legendItemHeight, stroke: '#999', fill: '#fff', lineWidth: 2, r: legendNodeR, }, }); rootGroup.addShape('text', { attrs: { x: legendBegin.x + 8 + legendLabelMargin, y: legendBegin.y + 2 * legendItemHeight, text: '非本团队成员', fill: '#999', textBaseline: 'middle', }, }); // 灰色实心 rootGroup.addShape('circle', { attrs: { x: legendBegin.x + 8, y: legendBegin.y + 3 * legendItemHeight, stroke: '#ccc', fill: '#ccc', lineWidth: 2, r: legendNodeR, }, }); rootGroup.addShape('text', { attrs: { x: legendBegin.x + 8 + legendLabelMargin, y: legendBegin.y + 3 * legendItemHeight, text: '已离职', fill: '#ccc', textBaseline: 'middle', }, }); // 实线边 rootGroup.addShape('line', { attrs: { x1: legendBegin.x, y1: legendBegin.y + 4 * legendItemHeight, x2: legendBegin.x + 16, y2: legendBegin.y + 4 * legendItemHeight, stroke: '#509FEE', lineWidth: 2, }, }); rootGroup.addShape('text', { attrs: { x: legendBegin.x + 16 + legendLabelMargin, y: legendBegin.y + 4 * legendItemHeight, text: '组织架构边', fill: '#509FEE', textBaseline: 'middle', }, }); // 虚线边 rootGroup.addShape('line', { attrs: { x1: legendBegin.x, y1: legendBegin.y + 5 * legendItemHeight, x2: legendBegin.x + 16, y2: legendBegin.y + 5 * legendItemHeight, stroke: '#509FEE', lineWidth: 2, lineDash: [2, 2], endArrow: { path: F6.Arrow.triangle(4, 6, 0), lineWidth: 0.1, fill: '#509FEE', }, }, }); rootGroup.addShape('text', { attrs: { x: legendBegin.x + 16 + legendLabelMargin, y: legendBegin.y + 5 * legendItemHeight, text: '师兄 -> 师弟', fill: '#509FEE', textBaseline: 'middle', }, }); }); });
the_stack
declare const Slick: any; export class GridOption { /* tslint:disable:variable-name function-name */ private _dualSelectionActivate: boolean = false; /** * CellExternalCopyManager 플러그인 사용 여부 * - 그리드 드래그 셀 선택 기능 ( 엑셀 복사 붙여기 ) * 해당 기능은 로우 선택 기능과 동시에 사용할 수 없기때문에 해당 기능을 활성화하면 클릭 이벤트가 동작하지 않는다 */ private _cellExternalCopyManagerActivate: boolean = false; /** * slick.columngroup.js 컬럼 그룹화 플러그인 사용을 위한 옵션 * * @type {boolean} * @private */ private _columnGroup: boolean = false; /** * SlickGrid 기본 옵션이 아니고 커스텀으로 추가한 옵션입니다 * 옵션을 true 로 사용하면 적용되며 그리드에 로우 숫자가 컨텐츠 사이즈를 초과하면 합계 로우를 맨 마지막에 고정 시키고 로우의 숫자가 컨텐츠의 사이즈보다 작을 경우는 로우의 마지막에 표시됩니다 * FrozenTotal 옵션을 사용하면 FrozenBottom, FrozenRow 값은 override 되서 사용할 수 없습니다 * * @type {boolean} * @private */ private _frozenTotal: boolean = false; /** * SlickGrid가 특정 측정을 수행하고 이벤트 리스너를 초기화 할 수 있으려면 그리드가 작성되는 컨테이너가 DOM에 있어야하며 레이아웃에 참여해야합니다 (can be 'visibility:hidden' but not 'display:none') * 일반적으로이 작업은 SlickGrid 인스턴스를 만들 때 수행됩니다. * 선택적으로 위의 조건이 충족 될 때까지 초기화를 연기하고 grid.init() 메서드를 명시 적으로 호출 할 수 있습니다. * 명시적 초기화를 사용하려면 explicitInitialization 옵션을 true로 설정. * * e.g ) * * <script> * var grid; * var columns = [ * {id: "title", name: "Title", field: "title"}, * {id: "duration", name: "Duration", field: "duration"}, * {id: "%", name: "% Complete", field: "percentComplete"}, * {id: "start", name: "Start", field: "start"}, * {id: "finish", name: "Finish", field: "finish"}, * {id: "effort-driven", name: "Effort Driven", field: "effortDriven"} * ]; * var options = { * enableCellNavigation: true, * enableColumnReorder: false, * explicitInitialization: true * }; * $(function () { * var data = []; * for (var i = 0; i < 500; i++) { * data[i] = { * title: "Task " + i, * duration: "5 days", * percentComplete: Math.round(Math.random() * 100), * start: "01/01/2009", * finish: "01/05/2009", * effortDriven: (i % 5 == 0) * }; * } * // create a detached container element * var myGrid = $("<div id='myGrid' style='width:600px;height:500px;'></div>"); * grid = new Slick.Grid(myGrid, data, columns, options); * myGrid.appendTo($("#myTable")); * grid.init(); * }) * </script> * * @type {boolean} * @private */ private _explicitInitialization: boolean = false; /** * * @type {number} * @private */ private _rowHeight: number = 25; /** * * @type {number} * @private */ private _defaultColumnWidth: number = 80; /** * True인 경우 빈 행이 하단에 표시됩니다. * 행의 입력 값은 새 행을 추가합니다. 값을 저장하려면 onAddNewRow를 구독해야 합니다. * * @type {boolean} * @private */ private _enableAddRow: boolean = false; /** * * @type {boolean} * @private */ private _leaveSpaceForNewRows: boolean = false; /** * * @type {boolean} * @private */ private _editable: boolean = false; /** * 작은 지연 후에 셀 편집기 부하를 비동기식으로 만듭니다. 따라서 키보드 탐색 속도가 크게 향상됩니다. * * @type {boolean} * @private */ private _asyncEditorLoading: boolean = false; /** * 셀 편집기가 로드된 후 지연됩니다. * asyncEditorLoading이 true가 아닌 경우 무시됩니다. * * @type {number} * @private */ private _asyncEditorLoadDelay: number = 100; /** * * @type {number} * @private */ private _asyncPostRenderDelay: number = 50; /** * 선택한 경우 셀은 자동으로 편집 모드로 전환되지 않습니다. * * @type {boolean} * @private */ private _autoEdit: boolean = true; /** * 수직 스크롤이 비활성화됩니다. * * @type {boolean} * @private */ private _autoHeight: boolean = false; /** * flashCell() function 을 사용해서 깜박이는 셀에 적용할 CSS 클래스명. * * @type {string} * @private */ private _cellFlashingCssClass: string = 'flashing'; /** * * @type {any} * @private */ private _dataItemColumnValueExtractor: string = null; /** * 다른 formatter가 지정되지 않은 경우 기본 값 formatter 적용. */ private _defaultFormatter: any = Slick.defaultFormatter; /** * 지정된 셀의 에디터를 작성하는 팩토리 객체입니다. * getEditor (column)를 구현해야합니다. * * @type {any} * @private */ private _editorFactory: string = null; /** * 데이터를 동시에 편집 하는 경우 제어를 위해서 사용할 Slick.EditorLock 인스턴스입니다. */ private _editorLock: any = Slick.GlobalEditorLock; /** * True이면 비동기 Post렌더링이 발생하고 열에 대한 asyncPostRender function이 호출됩니다. * * @type {boolean} * @private */ private _enableAsyncPostRender: boolean = false; /** * 대규모 데이터 세트로 최적화 된 속도를 위해 셀 가상화를 가능하게합니다 * * @type {boolean} * @private */ private _enableCellNavigation: boolean = true; /** * * @type {boolean} * @private */ private _enableColumnReorder: boolean = true; /** * * @type {boolean} * @private */ private _enableTextSelectionOnCells: boolean = false; /** * 컬럼 크기를 컨테이너에 맞춥니다 (수평 스크롤 방지) 컬럼 넓이를 조정할 수 있도록 컬럼 넓이를 효과적으로 설정합니다. * 작은 컨테이너에 있는 컬럼은 바람직하지 않을 수 있다. * * @type {boolean} * @private */ private _forceFitColumns: boolean = false; /** * * @type {boolean} * @private */ private _forceSyncScrolling: boolean = false; /** * 지정된 셀의 포맷터를 작성하는 팩토리 객체입니다. * getFormatter(column)을 구현해야 합니다. * * @type {any} * @private */ private _formatterFactory: string = null; /** * 테이블 행 div가 컨테이너의 전체 너비로 확장되고 테이블 셀 div가 왼쪽 정렬됩니다. * * @type {boolean} * @private */ private _fullWidthRows: boolean = false; /** * * @type {number} * @private */ private _headerRowHeight: number = 25; /** * * @type {boolean} * @private */ private _multiColumnSort: boolean = false; /** * * @type {boolean} * @private */ private _multiSelect: boolean = true; /** * * @type {string} * @private */ private _selectedCellCssClass: string = 'selected'; /** * * @type {boolean} * @private */ private _showHeaderRow: boolean = false; /** * * @type {number} * @private */ private _topPanelHeight: number = 25; /** * setHighlightedCells() function 을 사용해서 강조 표시된 셀에 적용할 CSS 클래스명. * * @type {string} * @private */ private _cellHighlightCssClass: string = 'selected'; /** * Not listed as a default under options in slick.grid.js * * e.g) Slick.queueAndExecuteCommand */ private _editCommandHandler: any; /** * WARNING : SlickGrid 2.1에 해당 옵션 deprecated * * @type {any} * @private */ private _enableCellRangeSelection: string = null; /** * WARNING : SlickGrid 2.1에 해당 옵션 deprecated * * @type {any} * @private */ private _enableRowReordering: string = null; /** * True이면 크기가 조정되는 컬럼은 마우스가 드래그하고있을 때 해당 넓이를 변경합니다. 거짓이면 마우스 드래그 끝에 열이 크기 조정됩니다. * * @type {boolean} * @private */ private _syncColumnCellResize: boolean = false; /** * * @type {boolean} * @private */ private _showTopPanel: boolean = false; /** * * @type {boolean} * @private */ private _frozenBottom: boolean = false; /** * * @type {number} * @private */ private _frozenColumn: number = -1; /** * * @type {number} * @private */ private _frozenRow: number = -1; /** * 헤더 클릭 기능 활성 여부 * @type {boolean} : 활성여부 * @private */ private _enableHeaderClick: boolean = false; /** * cell type에 따라서 css 적용 여부 * @type {boolean} : 활성여부 * @private */ private _nullCellStyleActivate: boolean = false; /** * context menu사용 여부 * @type {boolean} : 활성여부 * @private */ private _enableHeaderMenu: boolean = false; /** * enable sort when dualSelectionActivate * @type {boolean} : 활성여부 * @private */ private _enableSeqSort: boolean = true; /** * enable multi selection (header) with ctrl, shift key * @type {boolean} : 활성여부 * @private */ private _enableMultiSelectionWithCtrlAndShift: boolean = false; /** * No. row seleted * @type {boolean} : 활성여부 * @private */ private _enableRowSelected: boolean = false; constructor() { } get rowSelectionActivate(): boolean { return this._enableRowSelected; } RowSelectionActivate(value: boolean): GridOption { this._enableRowSelected = value; return this; } get dualSelectionActivate(): boolean { return this._dualSelectionActivate; } // noinspection JSUnusedGlobalSymbols DualSelectionActivate(value: boolean): GridOption { this._dualSelectionActivate = value; return this; } get cellExternalCopyManagerActivate(): boolean { return this._cellExternalCopyManagerActivate; } // noinspection JSUnusedGlobalSymbols CellExternalCopyManagerActivate(value: boolean): GridOption { this._cellExternalCopyManagerActivate = value; return this; } get columnGroup(): boolean { return this._columnGroup; } //noinspection JSUnusedGlobalSymbols ColumnGroup(value: boolean): GridOption { this._columnGroup = value; return this; } get frozenTotal(): boolean { return this._frozenTotal; } //noinspection JSUnusedGlobalSymbols FrozenTotal(value: boolean): GridOption { this._frozenTotal = value; return this; } get explicitInitialization(): boolean { return this._explicitInitialization; } //noinspection JSUnusedGlobalSymbols ExplicitInitialization(value: boolean): GridOption { this._explicitInitialization = value; return this; } get rowHeight(): number { return this._rowHeight; } //noinspection JSUnusedGlobalSymbols RowHeight(value: number): GridOption { this._rowHeight = value; return this; } get defaultColumnWidth(): number { return this._defaultColumnWidth; } //noinspection JSUnusedGlobalSymbols DefaultColumnWidth(value: number): GridOption { this._defaultColumnWidth = value; return this; } get enableAddRow(): boolean { return this._enableAddRow; } //noinspection JSUnusedGlobalSymbols EnableAddRow(value: boolean): GridOption { this._enableAddRow = value; return this; } get leaveSpaceForNewRows(): boolean { return this._leaveSpaceForNewRows; } //noinspection JSUnusedGlobalSymbols LeaveSpaceForNewRows(value: boolean): GridOption { this._leaveSpaceForNewRows = value; return this; } get editable(): boolean { return this._editable; } //noinspection JSUnusedGlobalSymbols Editable(value: boolean): GridOption { this._editable = value; return this; } get asyncEditorLoading(): boolean { return this._asyncEditorLoading; } //noinspection JSUnusedGlobalSymbols AsyncEditorLoading(value: boolean): GridOption { this._asyncEditorLoading = value; return this; } get asyncEditorLoadDelay(): number { return this._asyncEditorLoadDelay; } //noinspection JSUnusedGlobalSymbols AsyncEditorLoadDelay(value: number): GridOption { this._asyncEditorLoadDelay = value; return this; } get asyncPostRenderDelay(): number { return this._asyncPostRenderDelay; } //noinspection JSUnusedGlobalSymbols AsyncPostRenderDelay(value: number): GridOption { this._asyncPostRenderDelay = value; return this; } get autoEdit(): boolean { return this._autoEdit; } //noinspection JSUnusedGlobalSymbols AutoEdit(value: boolean): GridOption { this._autoEdit = value; return this; } get autoHeight(): boolean { return this._autoHeight; } //noinspection JSUnusedGlobalSymbols AutoHeight(value: boolean): GridOption { this._autoHeight = value; return this; } get cellFlashingCssClass(): string { return this._cellFlashingCssClass; } //noinspection JSUnusedGlobalSymbols CellFlashingCssClass(value: string): GridOption { this._cellFlashingCssClass = value; return this; } get dataItemColumnValueExtractor(): string { return this._dataItemColumnValueExtractor; } //noinspection JSUnusedGlobalSymbols DataItemColumnValueExtractor(value: string): GridOption { this._dataItemColumnValueExtractor = value; return this; } get defaultFormatter(): any { return this._defaultFormatter; } //noinspection JSUnusedGlobalSymbols DefaultFormatter(value: any): GridOption { this._defaultFormatter = value; return this; } get editorFactory(): string { return this._editorFactory; } //noinspection JSUnusedGlobalSymbols EditorFactory(value: string): GridOption { this._editorFactory = value; return this; } get editorLock(): any { return this._editorLock; } //noinspection JSUnusedGlobalSymbols EditorLock(value: any): GridOption { this._editorLock = value; return this; } get enableAsyncPostRender(): boolean { return this._enableAsyncPostRender; } //noinspection JSUnusedGlobalSymbols EnableAsyncPostRender(value: boolean): GridOption { this._enableAsyncPostRender = value; return this; } get enableCellNavigation(): boolean { return this._enableCellNavigation; } //noinspection JSUnusedGlobalSymbols EnableCellNavigation(value: boolean): GridOption { this._enableCellNavigation = value; return this; } get enableColumnReorder(): boolean { return this._enableColumnReorder; } //noinspection JSUnusedGlobalSymbols EnableColumnReorder(value: boolean): GridOption { this._enableColumnReorder = value; return this; } get enableTextSelectionOnCells(): boolean { return this._enableTextSelectionOnCells; } //noinspection JSUnusedGlobalSymbols EnableTextSelectionOnCells(value: boolean): GridOption { this._enableTextSelectionOnCells = value; return this; } get forceFitColumns(): boolean { return this._forceFitColumns; } //noinspection JSUnusedGlobalSymbols ForceFitColumns(value: boolean): GridOption { this._forceFitColumns = value; return this; } get forceSyncScrolling(): boolean { return this._forceSyncScrolling; } //noinspection JSUnusedGlobalSymbols ForceSyncScrolling(value: boolean): GridOption { this._forceSyncScrolling = value; return this; } get formatterFactory(): string { return this._formatterFactory; } //noinspection JSUnusedGlobalSymbols FormatterFactory(value: string): GridOption { this._formatterFactory = value; return this; } get fullWidthRows(): boolean { return this._fullWidthRows; } //noinspection JSUnusedGlobalSymbols FullWidthRows(value: boolean): GridOption { this._fullWidthRows = value; return this; } get headerRowHeight(): number { return this._headerRowHeight; } //noinspection JSUnusedGlobalSymbols HeaderRowHeight(value: number): GridOption { this._headerRowHeight = value; return this; } get multiColumnSort(): boolean { return this._multiColumnSort; } //noinspection JSUnusedGlobalSymbols MultiColumnSort(value: boolean): GridOption { this._multiColumnSort = value; return this; } get multiSelect(): boolean { return this._multiSelect; } //noinspection JSUnusedGlobalSymbols MultiSelect(value: boolean): GridOption { this._multiSelect = value; return this; } get selectedCellCssClass(): string { return this._selectedCellCssClass; } //noinspection JSUnusedGlobalSymbols SelectedCellCssClass(value: string): GridOption { this._selectedCellCssClass = value; return this; } get showHeaderRow(): boolean { return this._showHeaderRow; } //noinspection JSUnusedGlobalSymbols ShowHeaderRow(value: boolean): GridOption { this._showHeaderRow = value; return this; } get topPanelHeight(): number { return this._topPanelHeight; } //noinspection JSUnusedGlobalSymbols TopPanelHeight(value: number): GridOption { this._topPanelHeight = value; return this; } get cellHighlightCssClass(): string { return this._cellHighlightCssClass; } //noinspection JSUnusedGlobalSymbols CellHighlightCssClass(value: string): GridOption { this._cellHighlightCssClass = value; return this; } get editCommandHandler(): any { return this._editCommandHandler; } //noinspection JSUnusedGlobalSymbols EditCommandHandler(value: any): GridOption { this._editCommandHandler = value; return this; } get enableCellRangeSelection(): string { return this._enableCellRangeSelection; } //noinspection JSUnusedGlobalSymbols EnableCellRangeSelection(value: string): GridOption { this._enableCellRangeSelection = value; return this; } get enableRowReordering(): string { return this._enableRowReordering; } //noinspection JSUnusedGlobalSymbols EnableRowReordering(value: string): GridOption { this._enableRowReordering = value; return this; } get syncColumnCellResize(): boolean { return this._syncColumnCellResize; } //noinspection JSUnusedGlobalSymbols SyncColumnCellResize(value: boolean): GridOption { this._syncColumnCellResize = value; return this; } get showTopPanel(): boolean { return this._showTopPanel; } //noinspection JSUnusedGlobalSymbols ShowTopPanel(value: boolean): GridOption { this._showTopPanel = value; return this; } get frozenBottom(): boolean { return this._frozenBottom; } //noinspection JSUnusedGlobalSymbols FrozenBottom(value: boolean): GridOption { this._frozenBottom = value; return this; } get frozenColumn(): number { return this._frozenColumn; } //noinspection JSUnusedGlobalSymbols FrozenColumn(value: number): GridOption { this._frozenColumn = value; return this; } get frozenRow(): number { return this._frozenRow; } //noinspection JSUnusedGlobalSymbols FrozenRow(value: number): GridOption { this._frozenRow = value; return this; } get enableHeaderClick(): boolean { return this._enableHeaderClick; } EnableHeaderClick(value: boolean): GridOption { this._enableHeaderClick = value; return this; } get nullCellStyleActivate(): boolean { return this._nullCellStyleActivate; } NullCellStyleActivate(value: boolean): GridOption { this._nullCellStyleActivate = value; return this; } get enableHeaderMenu(): boolean { return this._enableHeaderMenu; } EnableHeaderMenu(value: boolean): GridOption { this._enableHeaderMenu = value; return this; } get enableSeqSort(): boolean { return this._enableSeqSort; } EnableSeqSort(value: boolean): GridOption { this._enableSeqSort = value; return this; } get enableMultiSelectionWithCtrlAndShift(): boolean { return this._enableMultiSelectionWithCtrlAndShift; } EnableMultiSelectionWithCtrlAndShift(value: boolean): GridOption { this._enableMultiSelectionWithCtrlAndShift = value; return this; } //noinspection JSUnusedGlobalSymbols build(): Option { return new Option(this); } } export class Option { constructor(builder: GridOption) { if (typeof builder.dualSelectionActivate !== 'undefined') { this.dualSelectionActivate = builder.dualSelectionActivate; } if (typeof builder.cellExternalCopyManagerActivate !== 'undefined') { this.cellExternalCopyManagerActivate = builder.cellExternalCopyManagerActivate; } if (typeof builder.columnGroup !== 'undefined') { this.columnGroup = builder.columnGroup; } if (typeof builder.explicitInitialization !== 'undefined') { this.explicitInitialization = builder.explicitInitialization; } if (typeof builder.frozenTotal !== 'undefined') { this.frozenTotal = builder.frozenTotal; } if (typeof builder.rowHeight !== 'undefined') { this.rowHeight = builder.rowHeight; } if (typeof builder.defaultColumnWidth !== 'undefined') { this.defaultColumnWidth = builder.defaultColumnWidth; } if (typeof builder.enableAddRow !== 'undefined') { this.enableAddRow = builder.enableAddRow; } if (typeof builder.leaveSpaceForNewRows !== 'undefined') { this.leaveSpaceForNewRows = builder.leaveSpaceForNewRows; } if (typeof builder.editable !== 'undefined') { this.editable = builder.editable; } if (typeof builder.asyncEditorLoading !== 'undefined') { this.asyncEditorLoading = builder.asyncEditorLoading; } if (typeof builder.asyncEditorLoadDelay !== 'undefined') { this.asyncEditorLoadDelay = builder.asyncEditorLoadDelay; } if (typeof builder.asyncPostRenderDelay !== 'undefined') { this.asyncPostRenderDelay = builder.asyncPostRenderDelay; } if (typeof builder.autoEdit !== 'undefined') { this.autoEdit = builder.autoEdit; } if (typeof builder.autoHeight !== 'undefined') { this.autoHeight = builder.autoHeight; } if (typeof builder.cellFlashingCssClass !== 'undefined') { this.cellFlashingCssClass = builder.cellFlashingCssClass; } if (typeof builder.dataItemColumnValueExtractor !== 'undefined') { this.dataItemColumnValueExtractor = builder.dataItemColumnValueExtractor; } if (typeof builder.defaultFormatter !== 'undefined') { this.defaultFormatter = builder.defaultFormatter; } if (typeof builder.editorFactory !== 'undefined') { this.editorFactory = builder.editorFactory; } if (typeof builder.editorLock !== 'undefined') { this.editorLock = builder.editorLock; } if (typeof builder.enableAsyncPostRender !== 'undefined') { this.enableAsyncPostRender = builder.enableAsyncPostRender; } if (typeof builder.enableCellNavigation !== 'undefined') { this.enableCellNavigation = builder.enableCellNavigation; } if (typeof builder.enableColumnReorder !== 'undefined') { this.enableColumnReorder = builder.enableColumnReorder; } if (typeof builder.enableTextSelectionOnCells !== 'undefined') { this.enableTextSelectionOnCells = builder.enableTextSelectionOnCells; } if (typeof builder.forceFitColumns !== 'undefined') { this.forceFitColumns = builder.forceFitColumns; } if (typeof builder.forceSyncScrolling !== 'undefined') { this.forceSyncScrolling = builder.forceSyncScrolling; } if (typeof builder.formatterFactory !== 'undefined') { this.formatterFactory = builder.formatterFactory; } if (typeof builder.fullWidthRows !== 'undefined') { this.fullWidthRows = builder.fullWidthRows; } if (typeof builder.headerRowHeight !== 'undefined') { this.headerRowHeight = builder.headerRowHeight; } if (typeof builder.multiColumnSort !== 'undefined') { this.multiColumnSort = builder.multiColumnSort; } if (typeof builder.multiSelect !== 'undefined') { this.multiSelect = builder.multiSelect; } if (typeof builder.selectedCellCssClass !== 'undefined') { this.selectedCellCssClass = builder.selectedCellCssClass; } if (typeof builder.showHeaderRow !== 'undefined') { this.showHeaderRow = builder.showHeaderRow; } if (typeof builder.topPanelHeight !== 'undefined') { this.topPanelHeight = builder.topPanelHeight; } if (typeof builder.cellHighlightCssClass !== 'undefined') { this.cellHighlightCssClass = builder.cellHighlightCssClass; } if (typeof builder.editCommandHandler !== 'undefined') { this.editCommandHandler = builder.editCommandHandler; } if (typeof builder.enableCellRangeSelection !== 'undefined') { this.enableCellRangeSelection = builder.enableCellRangeSelection; } if (typeof builder.enableRowReordering !== 'undefined') { this.enableRowReordering = builder.enableRowReordering; } if (typeof builder.syncColumnCellResize !== 'undefined') { this.syncColumnCellResize = builder.syncColumnCellResize; } if (typeof builder.showTopPanel !== 'undefined') { this.showTopPanel = builder.showTopPanel; } if (typeof builder.frozenBottom !== 'undefined') { this.frozenBottom = builder.frozenBottom; } if (typeof builder.frozenColumn !== 'undefined') { this.frozenColumn = builder.frozenColumn; } if (typeof builder.frozenRow !== 'undefined') { this.frozenRow = builder.frozenRow; } if (typeof builder.enableHeaderClick !== 'undefined') { this.enableHeaderClick = builder.enableHeaderClick; } if (typeof builder.nullCellStyleActivate !== 'undefined') { this.nullCellStyleActivate = builder.nullCellStyleActivate; } if (typeof builder.enableHeaderMenu !== 'undefined') { this.enableHeaderMenu = builder.enableHeaderMenu; } if (typeof builder.enableSeqSort !== 'undefined') { this.enableSeqSort = builder.enableSeqSort; } if (typeof builder.enableMultiSelectionWithCtrlAndShift !== 'undefined') { this.enableMultiSelectionWithCtrlAndShift = builder.enableMultiSelectionWithCtrlAndShift; } if (typeof builder.rowSelectionActivate !== 'undefined') { this.rowSelectionActivate = builder.rowSelectionActivate; } } public columnGroup: boolean; public frozenTotal: boolean; public explicitInitialization: boolean; public rowHeight: number; public defaultColumnWidth; public enableAddRow: boolean; public leaveSpaceForNewRows: boolean; public editable: boolean; public asyncEditorLoading: boolean; public asyncEditorLoadDelay: number; public asyncPostRenderDelay: number; public autoEdit: boolean; public autoHeight: boolean; public cellFlashingCssClass: string; public dataItemColumnValueExtractor: string; public defaultFormatter: any; public editorFactory: string; public editorLock: any; public enableAsyncPostRender: boolean; public enableCellNavigation: boolean; public enableColumnReorder: boolean; public enableTextSelectionOnCells: boolean; public forceFitColumns: boolean; public forceSyncScrolling: boolean; public formatterFactory: string; public fullWidthRows: boolean; public headerRowHeight: number; public multiColumnSort: boolean; public multiSelect: boolean; public selectedCellCssClass: string; public showHeaderRow: boolean; public topPanelHeight: number; public cellHighlightCssClass: string; public editCommandHandler: any; public enableCellRangeSelection: string; public enableRowReordering: string; public syncColumnCellResize: boolean; public showTopPanel: boolean; public frozenBottom: boolean; public frozenColumn: number; public frozenRow: number; public enableHeaderClick: boolean; public nullCellStyleActivate: boolean; public enableHeaderMenu: boolean; public enableSeqSort: boolean; public dualSelectionActivate: boolean; public rowSelectionActivate: boolean; public cellExternalCopyManagerActivate: boolean; public enableMultiSelectionWithCtrlAndShift: boolean; }
the_stack
import { ExecutionResult, SourceLocation } from "graphql"; import { take } from "rxjs/operators"; import StarWarsSchema from "./starWarsSchema"; import { graphql as graphqlObservable } from "../../"; const graphql = (schema, query, rootValue?, contextValue?, variableValues?) => { return new Promise(resolve => { graphqlObservable( schema, query, rootValue, contextValue, variableValues ) .pipe(take(1)) .subscribe(resolve); }); }; type SerializedExecutionResult<TData = {[key: string]: unknown }> = { data?: TData | null, errors?: ReadonlyArray<{ message: string, locations?: ReadonlyArray<SourceLocation>, path?: ReadonlyArray<string | number> }> } declare global { namespace jest { interface Matchers<R> { /** * Will test the equality of GraphQL's `ExecutionResult`. * * In opposite to the simple `toEqual` it will test the `errors` field * with `GraphqQLErrors`. Specifically it will test the equlity of the * properties `message`, `locations` and `path`. * @param expected */ toEqualExecutionResult<TData = { [key: string]: any }>(expected: SerializedExecutionResult<TData>): R; } } } expect.extend({ toEqualExecutionResult<TData>(actual: ExecutionResult<TData>, expected: SerializedExecutionResult<TData>) { let actualSerialized: SerializedExecutionResult<TData> = { data: actual.data, }; if(actual.errors) { actualSerialized.errors = actual.errors.map(e => ({ message: e.message, locations: e.locations, path: e.path, })) } expect(actualSerialized).toEqual(expected); return { message: 'ok', pass: true, } } }) describe("Star Wars Query Tests", () => { describe("Basic Queries", () => { it("Correctly identifies R2-D2 as the hero of the Star Wars Saga", async () => { const query = ` query { hero { name } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { hero: { name: "R2-D2" } } }); }); it("Correctly identifies R2-D2 with alias", async () => { const query = ` query { myrobot: hero { name } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { myrobot: { name: "R2-D2" } } }); }); it("Allows us to query for the ID and friends of R2-D2", async () => { const query = ` query HerNameAndFriendsQuery { hero { id name friends { name } } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { hero: { id: "2001", name: "R2-D2", friends: [ { name: "Luke Skywalker" }, { name: "Han Solo" }, { name: "Leia Organa" } ] } } }); }); }); // Requires support to nested queries https://jira.mesosphere.com/browse/DCOS-22358 describe("Nested Queries", () => { it("Allows us to query for the friends of friends of R2-D2", async () => { const query = ` query NestedQuery { hero { name friends { name appearsIn friends { name } } } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { hero: { name: "R2-D2", friends: [ { name: "Luke Skywalker", appearsIn: ["NEWHOPE", "EMPIRE", "JEDI"], friends: [ { name: "Han Solo" }, { name: "Leia Organa" }, { name: "C-3PO" }, { name: "R2-D2" } ] }, { name: "Han Solo", appearsIn: ["NEWHOPE", "EMPIRE", "JEDI"], friends: [ { name: "Luke Skywalker" }, { name: "Leia Organa" }, { name: "R2-D2" } ] }, { name: "Leia Organa", appearsIn: ["NEWHOPE", "EMPIRE", "JEDI"], friends: [ { name: "Luke Skywalker" }, { name: "Han Solo" }, { name: "C-3PO" }, { name: "R2-D2" } ] } ] } } }); }); }); describe("Using IDs and query parameters to refetch objects", () => { it("Allows us to query for Luke Skywalker directly, using his ID", async () => { const query = ` query FetchLukeQuery { human(id: "1000") { name } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { human: { name: "Luke Skywalker" } } }); }); it("Allows us to create a generic query, then use it to fetch Luke Skywalker using his ID", async () => { const query = ` query FetchSomeIDQuery($someId: String!) { human(id: $someId) { name } } `; const params = { someId: "1000" }; const result = await graphql(StarWarsSchema, query, null, null, params); expect(result).toEqualExecutionResult({ data: { human: { name: "Luke Skywalker" } } }); }); it("Allows us to create a generic query, then use it to fetch Han Solo using his ID", async () => { const query = ` query FetchSomeIDQuery($someId: String!) { human(id: $someId) { name } } `; const params = { someId: "1002" }; const result = await graphql(StarWarsSchema, query, null, null, params); expect(result).toEqualExecutionResult({ data: { human: { name: "Han Solo" } } }); }); // Requires support to errors https://jira.mesosphere.com/browse/DCOS-22062 it("Allows us to create a generic query, then pass an invalid ID to get null back", async () => { const query = ` query humanQuery($id: String!) { human(id: $id) { name } } `; const params = { id: "not a valid id" }; const result = await graphql(StarWarsSchema, query, null, null, params); expect(result).toEqualExecutionResult({ data: { human: null } }); }); }); describe("Using aliases to change the key in the response", () => { it("Allows us to query for Luke, changing his key with an alias", async () => { const query = ` query FetchLukeAliased { luke: human(id: "1000") { name } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { luke: { name: "Luke Skywalker" } } }); }); it("Allows us to query for both Luke and Leia, using two root fields and an alias", async () => { const query = ` query FetchLukeAndLeiaAliased { luke: human(id: "1000") { name } leia: human(id: "1003") { name } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { luke: { name: "Luke Skywalker" }, leia: { name: "Leia Organa" } } }); }); }); describe("Uses fragments to express more complex queries", () => { it("Allows us to query using duplicated content", async () => { const query = ` query DuplicateFields { luke: human(id: "1000") { name homePlanet } leia: human(id: "1003") { name homePlanet } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { luke: { name: "Luke Skywalker", homePlanet: "Tatooine" }, leia: { name: "Leia Organa", homePlanet: "Alderaan" } } }); }); // Require support to fragments https://jira.mesosphere.com/browse/DCOS-22356 it("Allows us to use a fragment to avoid duplicating content", async () => { const query = ` query UseFragment { luke: human(id: "1000") { ...HumanFragment } leia: human(id: "1003") { ...HumanFragment } } fragment HumanFragment on Human { name homePlanet } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { luke: { name: "Luke Skywalker", homePlanet: "Tatooine" }, leia: { name: "Leia Organa", homePlanet: "Alderaan" } } }); }); }); // Not supporting introspection describe("Using __typename to find the type of an object", () => { it("Allows us to verify that R2-D2 is a droid", async () => { const query = ` query CheckTypeOfR2 { hero { __typename name } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { hero: { __typename: "Droid", name: "R2-D2" } } }); }); // Requires support to introspection https://jira.mesosphere.com/browse/DCOS-22357 it("Allows us to verify that Luke is a human", async () => { const query = ` query CheckTypeOfLuke { hero(episode: EMPIRE) { __typename name } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { hero: { __typename: "Human", name: "Luke Skywalker" } } }); }); }); // Requires support to errors https://jira.mesosphere.com/browse/DCOS-22062 describe("Reporting errors raised in resolvers", () => { it("Correctly reports error on accessing secretBackstory", async () => { const query = ` query HeroNameQuery { hero { name secretBackstory } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { hero: { name: "R2-D2", secretBackstory: null } }, errors: [ { message: "secretBackstory is secret.", locations: [{ line: 5, column: 13 }], path: ["hero", "secretBackstory"] } ] }); }); it("Correctly reports error on accessing secretBackstory in a list", async () => { const query = ` query HeroNameQuery { hero { name friends { name secretBackstory } } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { hero: { name: "R2-D2", friends: [ { name: "Luke Skywalker", secretBackstory: null }, { name: "Han Solo", secretBackstory: null }, { name: "Leia Organa", secretBackstory: null } ] } }, errors: [ { message: "secretBackstory is secret.", locations: [{ line: 7, column: 15 }], path: ["hero", "friends", 0, "secretBackstory"] }, { message: "secretBackstory is secret.", locations: [{ line: 7, column: 15 }], path: ["hero", "friends", 1, "secretBackstory"] }, { message: "secretBackstory is secret.", locations: [{ line: 7, column: 15 }], path: ["hero", "friends", 2, "secretBackstory"] } ] }); }); it("Correctly reports error on accessing through an alias", async () => { const query = ` query HeroNameQuery { mainHero: hero { name story: secretBackstory } } `; const result = await graphql(StarWarsSchema, query); expect(result).toEqualExecutionResult({ data: { mainHero: { name: "R2-D2", story: null } }, errors: [ { message: "secretBackstory is secret.", locations: [{ line: 5, column: 13 }], path: ["mainHero", "story"] } ] }); }); }); });
the_stack
import { Grammar } from "atom"; import { ChildProcess } from "child_process"; import fs from "fs"; import { Message, Socket } from "@aminya/jmp"; import { v4 } from "uuid"; import { launchSpec, launchSpecFromConnectionInfo } from "spawnteract"; import Config from "./config"; import KernelTransport from "./kernel-transport"; import type { ResultsCallback } from "./kernel-transport"; import { log, js_idx_to_char_idx } from "./utils"; import type { KernelspecMetadata } from "@nteract/types"; export type Connection = { control_port: number; hb_port: number; iopub_port: number; ip: string; key: string; shell_port: number; signature_scheme: string; stdin_port: number; transport: string; version: number; }; export default class ZMQKernel extends KernelTransport { executionCallbacks: Record<string, any> = {}; connection: Connection; connectionFile: string; kernelProcess: ChildProcess; options: Record<string, any>; shellSocket: Socket; stdinSocket: Socket; ioSocket: Socket; constructor( kernelSpec: KernelspecMetadata, grammar: Grammar, options: Record<string, any>, onStarted: ((...args: Array<any>) => any) | null | undefined ) { super(kernelSpec, grammar); this.options = options || {}; // Otherwise spawnteract deletes the file and hydrogen's restart kernel fails options.cleanupConnectionFile = false; launchSpec(kernelSpec, options).then( ({ config, connectionFile, spawn }) => { this.connection = config; this.connectionFile = connectionFile; this.kernelProcess = spawn; this.monitorNotifications(spawn); this.connect(() => { this._executeStartupCode(); if (onStarted) { onStarted(this); } }); } ); } connect(done: ((...args: Array<any>) => any) | null | undefined) { const scheme = this.connection.signature_scheme.slice("hmac-".length); const { key } = this.connection; this.shellSocket = new Socket("dealer", scheme, key); this.stdinSocket = new Socket("dealer", scheme, key); this.ioSocket = new Socket("sub", scheme, key); const id = v4(); this.shellSocket.identity = `dealer${id}`; this.stdinSocket.identity = `dealer${id}`; this.ioSocket.identity = `sub${id}`; const address = `${this.connection.transport}://${this.connection.ip}:`; this.shellSocket.connect(address + this.connection.shell_port); this.ioSocket.connect(address + this.connection.iopub_port); this.ioSocket.subscribe(""); this.stdinSocket.connect(address + this.connection.stdin_port); this.shellSocket.on("message", this.onShellMessage.bind(this)); this.ioSocket.on("message", this.onIOMessage.bind(this)); this.stdinSocket.on("message", this.onStdinMessage.bind(this)); this.monitor(done); } monitorNotifications(childProcess: ChildProcess) { childProcess.stdout.on("data", (data: string | Buffer) => { data = data.toString(); if (atom.config.get("Hydrogen.kernelNotifications")) { atom.notifications.addInfo(this.kernelSpec.display_name, { description: data, dismissable: true, }); } else { log("ZMQKernel: stdout:", data); } }); childProcess.stderr.on("data", (data: string | Buffer) => { atom.notifications.addError(this.kernelSpec.display_name, { description: data.toString(), dismissable: true, }); }); } monitor(done: ((...args: Array<any>) => any) | null | undefined) { try { const socketNames = ["shellSocket", "ioSocket"]; let waitGroup = socketNames.length; const onConnect = ({ socketName, socket }) => { log(`ZMQKernel: ${socketName} connected`); socket.unmonitor(); waitGroup--; if (waitGroup === 0) { log("ZMQKernel: all main sockets connected"); this.setExecutionState("idle"); if (done) { done(); } } }; const monitor = (socketName, socket) => { log(`ZMQKernel: monitor ${socketName}`); socket.on( "connect", onConnect.bind(this, { socketName, socket, }) ); socket.monitor(); }; monitor("shellSocket", this.shellSocket); monitor("ioSocket", this.ioSocket); } catch (err) { log("ZMQKernel:", err); } } interrupt() { if (process.platform === "win32") { atom.notifications.addWarning("Cannot interrupt this kernel", { detail: "Kernel interruption is currently not supported in Windows.", }); } else { log("ZMQKernel: sending SIGINT"); this.kernelProcess.kill("SIGINT"); } } _kill() { log("ZMQKernel: sending SIGKILL"); this.kernelProcess.kill("SIGKILL"); } _executeStartupCode() { const displayName = this.kernelSpec.display_name; let startupCode = Config.getJson("startupCode")[displayName]; if (startupCode) { log("KernelManager: Executing startup code:", startupCode); startupCode += "\n"; this.execute(startupCode, (message, channel) => {}); } } shutdown() { this._socketShutdown(); } restart(onRestarted: ((...args: Array<any>) => any) | null | undefined) { this._socketRestart(onRestarted); } _socketShutdown(restart: boolean | null | undefined = false) { const requestId = `shutdown_${v4()}`; const message = _createMessage("shutdown_request", requestId); message.content = { restart, }; this.shellSocket.send(new Message(message)); } _socketRestart( onRestarted: ((...args: Array<any>) => any) | null | undefined ) { if (this.executionState === "restarting") { return; } this.setExecutionState("restarting"); this._socketShutdown(true); this._kill(); const { spawn } = launchSpecFromConnectionInfo( this.kernelSpec, this.connection, this.connectionFile, this.options ); this.kernelProcess = spawn; this.monitor(() => { this._executeStartupCode(); if (onRestarted) { onRestarted(); } }); } // onResults is a callback that may be called multiple times // as results come in from the kernel execute(code: string, onResults: ResultsCallback) { log("ZMQKernel.execute:", code); const requestId = `execute_${v4()}`; const message = _createMessage("execute_request", requestId); message.content = { code, silent: false, store_history: true, user_expressions: {}, allow_stdin: true, }; this.executionCallbacks[requestId] = onResults; this.shellSocket.send(new Message(message)); } complete(code: string, onResults: ResultsCallback) { log("ZMQKernel.complete:", code); const requestId = `complete_${v4()}`; const message = _createMessage("complete_request", requestId); message.content = { code, text: code, line: code, cursor_pos: js_idx_to_char_idx(code.length, code), }; this.executionCallbacks[requestId] = onResults; this.shellSocket.send(new Message(message)); } inspect(code: string, cursorPos: number, onResults: ResultsCallback) { log("ZMQKernel.inspect:", code, cursorPos); const requestId = `inspect_${v4()}`; const message = _createMessage("inspect_request", requestId); message.content = { code, cursor_pos: cursorPos, detail_level: 0, }; this.executionCallbacks[requestId] = onResults; this.shellSocket.send(new Message(message)); } inputReply(input: string) { const requestId = `input_reply_${v4()}`; const message = _createMessage("input_reply", requestId); message.content = { value: input, }; this.stdinSocket.send(new Message(message)); } onShellMessage(message: Message) { log("shell message:", message); if (!_isValidMessage(message)) { return; } const { msg_id } = message.parent_header; let callback; if (msg_id) { callback = this.executionCallbacks[msg_id]; } if (callback) { callback(message, "shell"); } } onStdinMessage(message: Message) { log("stdin message:", message); if (!_isValidMessage(message)) { return; } // input_request messages are attributable to particular execution requests, // and should pass through the middleware stack to allow plugins to see them const { msg_id } = message.parent_header; let callback; if (msg_id) { callback = this.executionCallbacks[msg_id]; } if (callback) { callback(message, "stdin"); } } onIOMessage(message: Message) { log("IO message:", message); if (!_isValidMessage(message)) { return; } const { msg_type } = message.header; if (msg_type === "status") { const status = message.content.execution_state; this.setExecutionState(status); } const { msg_id } = message.parent_header; let callback; if (msg_id) { callback = this.executionCallbacks[msg_id]; } if (callback) { callback(message, "iopub"); } } destroy() { log("ZMQKernel: destroy:", this); this.shutdown(); this._kill(); fs.unlinkSync(this.connectionFile); this.shellSocket.close(); this.ioSocket.close(); this.stdinSocket.close(); super.destroy(); } } function _isValidMessage(message: Message) { if (!message) { log("Invalid message: null"); return false; } if (!message.content) { log("Invalid message: Missing content"); return false; } if (message.content.execution_state === "starting") { // Kernels send a starting status message with an empty parent_header log("Dropped starting status IO message"); return false; } if (!message.parent_header) { log("Invalid message: Missing parent_header"); return false; } if (!message.parent_header.msg_id) { log("Invalid message: Missing parent_header.msg_id"); return false; } if (!message.parent_header.msg_type) { log("Invalid message: Missing parent_header.msg_type"); return false; } if (!message.header) { log("Invalid message: Missing header"); return false; } if (!message.header.msg_id) { log("Invalid message: Missing header.msg_id"); return false; } if (!message.header.msg_type) { log("Invalid message: Missing header.msg_type"); return false; } return true; } function _getUsername() { return ( process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME ); } function _createMessage(msgType: string, msgId: string = v4()) { const message = { header: { username: _getUsername(), session: "00000000-0000-0000-0000-000000000000", msg_type: msgType, msg_id: msgId, date: new Date(), version: "5.0", }, metadata: {}, parent_header: {}, content: {}, }; return message; }
the_stack
import utils from '@/pages/DataGraph/Common/utils.js'; import { deepClone } from '@/common/js/Utils.ts'; import DataTable from '@/pages/datamart/common/components/DataTable.vue'; import { Component, Prop, Ref, Watch } from 'vue-property-decorator'; import { ICalculationAtomsResults } from '../../Interface/indexDesign'; import DataDetailFold from '../Steps/ChildNodes/DataDetailFold.vue'; import { DataModelManageBase } from '../../Controller/DataModelManageBase'; import { IndexTree } from '../Common/index'; export interface IModelType { master_table: string; fact_table: string; dimension_table: string; calculation_atom: string; indicator: string; } /** * 格式化子节点 * @param {Array} nodes 节点 * @param calculationFormula * @returns 返回格式化后的节点数组 */ const getChildNodes = (nodes: any[] = [], calculationFormula: string) => { const resNodes: any[] = []; nodes.forEach(child => { Object.assign(child, { displayName: `${child.indicatorName}(${child.indicatorAlias})` }); const { indicatorAlias, indicatorName } = child; Object.assign(child, { calculationFormula }); const nodeName = `${indicatorAlias}(${indicatorName})`; const grandSonNode = { name: indicatorName, displayName: nodeName, alias: indicatorAlias, // type为indicator类型 type: child.type, children: [], icon: 'icon-quota', id: indicatorName, sourceData: child, count: child.indicatorCount, }; if (child.subIndicators && child.subIndicators.length) { grandSonNode.children = getChildNodes(child.subIndicators, calculationFormula); } resNodes.push(grandSonNode); }); return resNodes; }; @Component({ components: { DataTable, DataDetailFold, IndexTree, }, }) export default class IndexDesignView extends DataModelManageBase { @Prop({ required: true }) public readonly data!: Array<object>; @Ref() public readonly indexTree!: IndexTree; windowTypeMap = { scroll: $t('滚动窗口'), accumulate: $t('累加窗口'), slide: $t('滑动窗口'), accumulate_by_hour: $t('按小时累加窗口'), fixed: $t('固定窗口'), }; // 表格最多显示数 calcPageSize = 10; searchText = ''; isLoading = false; isIndexLoading = false; indexDetailNameIcons: IModelType = { master_table: 'icon-fact-model', fact_table: 'icon-fact-model', dimension_table: 'icon-dimension-model', calculation_atom: 'icon-statistic-caliber', indicator: 'icon-quota', }; treeData: any[] = []; activeNode: any = null; indexList: any[] = []; unitMap = { s: $t('秒'), min: $t('分钟'), h: $t('小时'), d: $t('天'), w: $t('周'), m: $t('月'), }; // 表格头部的信息会依赖此数据变化,每次只要更改这个数据值来改变表格头部信息 tableInfoValueMap = { type: '', name: '', }; headerTop = 0; calculationAtomProp = {}; localData: any = {}; isOpen = false; get maxHeight() { if (this.tableInfoValueMap.type === 'indicator') { const height = this.isOpen ? 538 : 570; return height; } return 630; } get tableInfoData() { const { data = {} } = this.activeNode || {}; return { displayName: data.displayName, data: data.sourceData, }; } // 统计口径列表 get calculationAtomTableData() { if (this.tableInfoValueMap.type !== 'master_table') { return this.localData; } return this.localData.filter(item => { return item.calculationAtomName.includes(this.searchText) || item.calculationAtomAlias.includes(this.searchText); }); } // 指标列表 get indexTableData() { if (this.tableInfoValueMap.type !== 'calculation_atom') { return this.indexList; } return this.indexList.filter(item => { return item.indicatorName.includes(this.searchText) || item.indicatorAlias.includes(this.searchText); }); } @Watch('data', { immediate: true, deep: true }) handleChangeData() { this.localData = deepClone(this.data); this.initData(); } public getIcon(type: string) { if (type === 'master_table') { const modeType = this.activeModelTabItem.modelType || 'master_table'; return this.indexDetailNameIcons[modeType]; } return this.indexDetailNameIcons[type]; } public handleChangeStatus(status: boolean) { this.isOpen = status; } public initData() { const { name, displayName, modelType } = this.activeModelTabItem; const showName = `${displayName}(${name})`; const rootNode = { name: name, displayName: showName, alias: displayName, count: 0, type: 'master_table', icon: this.indexDetailNameIcons[modelType] || 'icon-fact-model', id: `model_id_${this.modelId}`, children: [], }; this.tableInfoValueMap = { type: 'master_table', name, }; this.treeData = [rootNode]; this.handleSetCalculationAtoms(); } getUnitFirstWord(unit: string) { return unit.split('')[0].toLowerCase(); } scrollEvent(e) { this.headerTop = e.target.scrollTop; } // 表格上方搜索框来搜索指标或统计口径 searchTextChange() { if (this.tableInfoValueMap.type === 'master_table') { this.localData.filter((item: ICalculationAtomsResults) => { return ( item.calculationAtomName.includes(this.searchText) || item.calculationAtomAlias.includes(this.searchText) ); }); } } // 查看统计口径下的指标列表 handleIndexDetail(data: ICalculationAtomsResults) { this.tableInfoValueMap = { type: 'calculation_atom', name: data.calculationAtomName, }; this.indexTree.handleSetTreeSelected(data.calculationAtomName); this.getIndicatorList(data.indicators); } // 指标点击事件回调 goToIndexDetail(indicatorName: string) { this.tableInfoValueMap.type = 'indicator'; this.tableInfoValueMap.name = indicatorName; this.indexTree.handleSetTreeSelected(indicatorName); } goToCalculationAtomDetail(row) { this.tableInfoValueMap.type = 'calculation_atom'; this.tableInfoValueMap.name = row.calculationAtomName; this.indexTree.handleSetTreeSelected(row.calculationAtomName); // 获取统计口径下指标列表 this.getIndicatorList(row.indicators); } /** 节点点击事件回调 */ handleNodeClick(node: any) { const { data = {} } = node; this.tableInfoValueMap = { type: data.type, name: data.name, }; this.activeNode = node; this.calcPageSize = 10; this.isOpen = false; if (data.type === 'calculation_atom') { // 根据统计口径名称获取指标列表,在二级树形 this.getIndicatorList(data.sourceData.indicators); } else if (data.type === 'master_table') { // 一级树形 !this.localData.length && this.handleSetCalculationAtoms(); } else if (data.type === 'indicator') { this.calculationAtomProp = data; this.getIndicatorList(data.sourceData.subIndicators); } } get indicatorDetailData() { const aggregationFieldsStr = this.getAggregationFieldsStr({ aggregationFieldsAlias: this.tableInfoData.data.aggregationFieldsAlias, aggregationFields: this.tableInfoData.data.aggregationFields, }); const { schedulingContent } = this.tableInfoData.data.schedulingContent; const commonParams = [ { label: $t('指标统计口径'), value: `${this.tableInfoData.data.calculationAtomAlias} (${this.tableInfoData.data.calculationAtomName})`, }, { label: $t('口径聚合逻辑'), value: this.tableInfoData.data.calculationFormula || '--', }, { label: $t('聚合字段'), value: aggregationFieldsStr || '--', }, { label: $t('过滤条件'), value: this.tableInfoData.data.filterFormulaStrippedComment || '--', }, { groupDataList: [ { label: $t('计算类型'), value: this.tableInfoData.data.schedulingType === 'stream' ? $t('实时计算') : $t('离线计算'), }, { label: $t('窗口类型'), value: this.windowTypeMap[schedulingContent.windowType], }, ], }, ]; let params1 = []; if (['scroll', 'slide', 'accumulate'].includes(schedulingContent.windowType)) { // 滚动窗口、滑动窗口、累加窗口共用参数 params1 = [ { groupDataList: [ { label: $t('统计频率'), value: schedulingContent.countFreq + $t('秒'), }, { label: $t('窗口长度'), value: schedulingContent.windowTime + $t('分钟'), isHidden: schedulingContent.windowType === 'scroll', }, { label: $t('等待时间'), value: schedulingContent.waitingTime + $t('秒'), }, ], }, { groupDataList: [ { label: $t('依赖计算延迟数据'), value: schedulingContent.windowLateness.allowedLateness ? $t('是') : $t('否'), }, { label: $t('延迟时间'), value: schedulingContent.windowLateness.latenessTime + $t('小时'), isHidden: !schedulingContent.windowLateness.allowedLateness, }, { label: $t('统计频率'), value: schedulingContent.windowLateness.latenessCountFreq + $t('秒'), isHidden: !schedulingContent.windowLateness.allowedLateness, }, ], }, ]; } else { // 固定窗口、按小时累加窗口共用参数 const dependencyRule = { no_failed: $t('无失败'), all_finished: $t('全部成功'), at_least_one_finished: $t('一次成功'), }; let dataStartList: { id: number; name: string; }[] = []; let dataEndList: { id: number; name: string; }[] = []; if (schedulingContent.windowType === 'accumulate_by_hour') { dataStartList = utils.getTimeList(); dataEndList = utils.getTimeList('59'); } const freqIndex = this.getUnitFirstWord(schedulingContent.schedulePeriod); params1 = [ { groupDataList: [ { label: $t('统计频率'), value: `${schedulingContent.countFreq}${this.unitMap[freqIndex]}`, }, { label: $t('统计延迟'), value: schedulingContent.windowType === 'fixed' ? schedulingContent.fixedDelay + $t('小时') : schedulingContent.delay + $t('小时'), }, { label: $t('窗口长度'), value: schedulingContent.formatWindowSize + this.unitMap[schedulingContent.formatWindowSizeUnit], isHidden: schedulingContent.windowType !== 'fixed', }, { label: $t('窗口起点'), value: dataStartList.find(child => child.id === schedulingContent.dataStart) ?.name, isHidden: schedulingContent.windowType === 'fixed', }, { label: $t('窗口终点'), value: dataEndList.find(child => child.id === schedulingContent.dataEnd)?.name, isHidden: schedulingContent.windowType === 'fixed', }, ], }, { label: $t('依赖策略'), value: dependencyRule[schedulingContent.unifiedConfig?.dependencyRule], }, { groupDataList: [ { label: $t('调度失败重试'), value: schedulingContent.advanced.recoveryEnable ? $t('是') : $t('否'), }, { label: $t('重试次数'), value: schedulingContent.advanced.recoveryTimes + $t('小时'), isHidden: !schedulingContent.advanced.recoveryEnable, }, { label: $t('调度间隔'), value: parseInt(schedulingContent.advanced.recoveryInterval) + $t('分钟'), isHidden: !schedulingContent.advanced.recoveryEnable, }, ], }, ]; } return [ ...commonParams, ...params1, { groupDataList: [ { label: $t('更新人'), value: this.tableInfoData.data.updatedBy, }, { label: $t('更新时间'), value: this.tableInfoData.data.updatedAt, }, ], }, ]; } // 获取指标列表 getIndicatorList(list: any[] = []) { this.indexList = list; this.indexList.forEach(item => { this.$set(item, 'displayName', `${item.indicatorName}(${item.indicatorAlias})`); }); this.indexList.length && this.indexList.forEach(item => { this.$set(item, 'aggregationFieldsStr', this.getAggregationFieldsStr(item)); }); } getAggregationFieldsStr(item) { // 聚合字段(aggregationFieldsStr),首先用aggregationFieldsAlias,不存在用aggregationFields let str = ''; let arr: any[]; if (item.aggregationFieldsAlias?.length) { arr = item.aggregationFieldsAlias; } else if (item.aggregationFields?.length) { arr = item.aggregationFields; } if (arr?.length) { arr.forEach(child => { str += child + ','; }); } return str.slice(0, str.length - 1) || '--'; } // 获取统计口径列表 handleSetCalculationAtoms() { this.treeData[0].children = []; this.localData.forEach(item => { this.$set(item, 'displayName', `${item.calculationAtomName}(${item.calculationAtomAlias})`); }); // 总指标数 let totalCount = 0; this.localData.forEach(item => { const { calculationAtomName, calculationAtomAlias, type, indicatorCount } = item; totalCount += indicatorCount; const nodeName = `${calculationAtomAlias}(${calculationAtomName})`; const childNode = { name: calculationAtomName, displayName: nodeName, alias: calculationAtomAlias, type, count: indicatorCount, sourceData: item, icon: 'icon-statistic-caliber', id: calculationAtomName, children: [], }; if (item.indicators && item.indicators.length) { childNode.children.push(...getChildNodes(item.indicators, item.calculationFormulaStrippedComment)); } this.treeData[0].count = totalCount; this.treeData[0].children.push(childNode); }); } handleGoEditIndexDesign(name: string, row) { // 激活指标步骤 this.DataModelTabManage.updateTabActiveStep(3); this.$router.push({ name: 'dataModelEdit', params: Object.assign({}, this.routeParams, { open: { name, row } }), query: this.routeQuery, }); } }
the_stack
import AnchoredDataSerializer from '../../lib/core/versions/latest/AnchoredDataSerializer'; import ErrorCode from '../../lib/core/versions/latest/ErrorCode'; import ITransactionStore from '../../lib/core/interfaces/ITransactionStore'; import JasmineSidetreeErrorValidator from '../JasmineSidetreeErrorValidator'; import MockTransactionStore from '../mocks/MockTransactionStore'; import TransactionModel from '../../lib/common/models/TransactionModel'; import TransactionSelector from '../../lib/core/versions/latest/TransactionSelector'; describe('TransactionSelector', () => { let transactionSelector: TransactionSelector; let transactionStore: ITransactionStore; function getTestTransactionsFor1Block () { return [ { transactionNumber: 1, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash', numberOfOperations: 12 }), transactionFeePaid: 333, normalizedTransactionFee: 1, writer: 'writer1' }, { transactionNumber: 2, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash2', numberOfOperations: 11 }), transactionFeePaid: 998, // second highest fee should come second normalizedTransactionFee: 1, writer: 'writer2' }, { transactionNumber: 3, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash3', numberOfOperations: 8 }), transactionFeePaid: 999, // highest fee should come first normalizedTransactionFee: 1, writer: 'writer3' }, { transactionNumber: 4, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash4', numberOfOperations: 1 }), transactionFeePaid: 14, normalizedTransactionFee: 1, writer: 'writer4' } ]; } beforeEach(() => { transactionStore = new MockTransactionStore(); transactionSelector = new TransactionSelector(transactionStore); // hard set number for ease of testing transactionSelector['maxNumberOfTransactionsPerBlock'] = 10; transactionSelector['maxNumberOfOperationsPerBlock'] = 25; }); describe('selectQualifiedTransactions', () => { it('should return the expected transactions with limit on operation', async () => { // max operation is 25 by default in before each const transactions = getTestTransactionsFor1Block(); const result = await transactionSelector.selectQualifiedTransactions(transactions); const expected = [ { transactionNumber: 3, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash3', numberOfOperations: 8 }), transactionFeePaid: 999, // highest fee should come first normalizedTransactionFee: 1, writer: 'writer3' }, { transactionNumber: 2, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash2', numberOfOperations: 11 }), transactionFeePaid: 998, // second highest fee should come second normalizedTransactionFee: 1, writer: 'writer2' } ]; expect(result).toEqual(expected); }); it('should return the expected transactions with limit on 1 transaction per writer', async () => { // max operation is 25 by default in before each const transactions = getTestTransactionsFor1Block(); // make all transactions the same writer except the last one for (const transaction of transactions) { transaction.writer = 'sameWriterForAllExceptLast'; } transactions[transactions.length - 1].writer = 'aDifferentWriter'; const result = await transactionSelector.selectQualifiedTransactions(transactions); // expect the first and last transaction because the first one is the first from the repeating writer and the last one is from a different writer const expected = [transactions[0], transactions[transactions.length - 1]]; expect(result).toEqual(expected); }); it('should return the expected transactions with limit on transaction', async () => { transactionSelector = new TransactionSelector(transactionStore); // set transactions limit to 1 to see proper limiting, and set operation to 100 so it does not filter. transactionSelector['maxNumberOfTransactionsPerBlock'] = 1; transactionSelector['maxNumberOfOperationsPerBlock'] = 100; const transactions = getTestTransactionsFor1Block(); const result = await transactionSelector.selectQualifiedTransactions(transactions); const expected = [ { transactionNumber: 3, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash3', numberOfOperations: 8 }), transactionFeePaid: 999, // second highest fee should come second normalizedTransactionFee: 1, writer: 'writer3' } ]; expect(result).toEqual(expected); }); it('should return an empty array when an empty array is passed in', async () => { const result = await transactionSelector.selectQualifiedTransactions([]); const expected: TransactionModel[] = []; expect(result).toEqual(expected); }); it('should throw expected error if the array passed in contains transactions from multiple different blocks', async () => { const transactions = getTestTransactionsFor1Block(); transactions[transactions.length - 1].transactionTime = 12324; await JasmineSidetreeErrorValidator.expectSidetreeErrorToBeThrownAsync( () => transactionSelector.selectQualifiedTransactions(transactions), ErrorCode.TransactionsNotInSameBlock ); }); it('should deduct the number of operations if some operations in the current block were already in transactions store', async () => { const extraTransaction = { transactionNumber: 0, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash', numberOfOperations: 16 }), transactionFeePaid: 9999, normalizedTransactionFee: 1, writer: 'writer' }; await transactionStore.addTransaction(extraTransaction); const transactions = getTestTransactionsFor1Block(); const result = await transactionSelector.selectQualifiedTransactions(transactions); const expected = [ { transactionNumber: 3, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash3', numberOfOperations: 8 }), transactionFeePaid: 999, // second highest fee should come second normalizedTransactionFee: 1, writer: 'writer3' } ]; expect(result).toEqual(expected); }); it('should deduct the number of transactions if transactions in the current block were already in transactions store', async () => { transactionSelector = new TransactionSelector(transactionStore); // set to never reach operation limit but can see transaction limiting transactionSelector['maxNumberOfTransactionsPerBlock'] = 2; transactionSelector['maxNumberOfOperationsPerBlock'] = 10000; const extraTransaction = { transactionNumber: 0, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash', numberOfOperations: 1 }), transactionFeePaid: 9999, normalizedTransactionFee: 1, writer: 'writer' }; await transactionStore.addTransaction(extraTransaction); const transactions = getTestTransactionsFor1Block(); const result = await transactionSelector.selectQualifiedTransactions(transactions); const expected = [ { transactionNumber: 3, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: AnchoredDataSerializer.serialize({ coreIndexFileUri: 'file_hash3', numberOfOperations: 8 }), transactionFeePaid: 999, // second highest fee should come second normalizedTransactionFee: 1, writer: 'writer3' } ]; expect(result).toEqual(expected); }); it('should skip transactions that are not parsable', async () => { const transactions = getTestTransactionsFor1Block(); // this makes the parsing fail when reading from db const extraTransaction = { transactionNumber: 0, transactionTime: 1, transactionTimeHash: 'some hash', anchorString: 'thisIsABadString', transactionFeePaid: 9999, normalizedTransactionFee: 1, writer: 'writer' }; await transactionStore.addTransaction(extraTransaction); // this makes the parsing fail when reading new transactions spyOn(AnchoredDataSerializer, 'deserialize').and.throwError('some error'); const result = await transactionSelector.selectQualifiedTransactions(transactions); const expected: TransactionModel[] = []; expect(result).toEqual(expected); }); }); describe('getNumberOfOperationsAndTransactionsAlreadyInTransactionTime', () => { it('should handle when transactions store returns undefined', async () => { spyOn(transactionStore, 'getTransactionsStartingFrom').and.returnValue(new Promise((resolve) => { resolve(undefined); })); const result = await transactionSelector['getNumberOfOperationsAndTransactionsAlreadyInTransactionTime'](1); expect(result).toEqual([0, 0]); }); }); });
the_stack
// // Copyright (C) Microsoft. All rights reserved. // /// <reference path="Interfaces.d.ts"/> module EdgeDiagnosticsAdapter { "use strict"; /** * Class that synchronously iterates through a CSS document and constructs a list of ICssMediaQuery and ICssRuleset objects. * The private members in this class store state used during the parse loop and that state is modified from * the various subroutines executed in the loop. */ export class CssParser { // A list that contains any number of ICssMediaQuery and ICssRuleset objects private _rootNodes: any[]; private _text: string; // Holds the index where text was last extracted from the source text private _lastCheckpoint: number; // Holds a string representing the current type of CSS construct that text is being extracted for private _state: CssToken; // Holds the index into the source text that the parser is currently inspecting at private _index: number; // Holds components of the CSS AST that are still being constructed private _currentRuleset: ICssRuleset; private _currentDeclaration: ICssDeclaration; private _currentMediaQuery: ICssMediaQuery; // Stores state about whether the loop has passed open quotes or open comments private _inComment: boolean; private _currentQuotationMark: string; private _nextCharIsEscaped: boolean; constructor(text: string) { this._rootNodes = []; this._text = text; // Statement control this._inComment = false; this._currentQuotationMark = ""; this._nextCharIsEscaped = false; // Search maintenance state this._lastCheckpoint = 0; this._state = CssToken.Selector; // Storage for under-construction nodes this._currentRuleset = null; this._currentDeclaration = null; this._currentMediaQuery = null; } /** Returns an array containing ICssRuleset and ICssMediaQuery objects */ public parseCss(): any[] { this.parseText(); // Put any text that wasn't valid CSS into it's own node at the end of the file this.handleIncompleteBlocks(); return this._rootNodes; } /** Returns an array containing a single rule, ICssRuleset and ICssMediaQuery objects */ public parseInlineCss(): ICssRuleset { // inline CSS is just a list of properties. Set up the parser state to read them correctly. this._currentRuleset = { originalOffset: this._lastCheckpoint, selector: "DoesNotMatter", declarations: [] }; this._state = CssToken.Property; this.parseText(); Assert.isTrue(this._currentRuleset && this._rootNodes.length === 0, "Text was not valid inline CSS"); this._currentRuleset.endOffset = this._text.length; return this._currentRuleset; } private parseText(): void { for (this._index = 0; this._index < this._text.length; this._index++) { if (this.handleQuoteCharacter()) { } else if (this.handleCommentCharacter()) { } else if (this.handleLeadingWhitespace()) { } else if (this.handleMediaQueryStart()) { } else if (this.handleMediaQueryOpenBracket()) { } else if (this.handleMediaQueryCloseBracket()) { } else if (this.handleSelectorOpenBracket()) { } else if (this.handlePropertyColon()) { } else if (this.handleValueSemicolon()) { } else if (this.handleSelectorCloseBracket()) { } } } private handleMediaQueryStart(): boolean { if (this._state === CssToken.Selector && !this._currentMediaQuery && this._lastCheckpoint >= this._index && this._text[this._index] === "@" && this._text.substr(this._index, 7).toLowerCase() === "@media ") { this._state = CssToken.Media; return true; } return false; } private handleMediaQueryOpenBracket(): boolean { if (this._state === CssToken.Media && this._text[this._index] === "{") { var mediaText = this._text.substring(this._lastCheckpoint, this._index); this._currentMediaQuery = { originalOffset: this._lastCheckpoint, query: mediaText, rulesets: [] }; this._lastCheckpoint = this._index + 1; this._state = CssToken.Selector; return true; } return false; } private handleMediaQueryCloseBracket(): boolean { if (this._state === CssToken.Selector && this._text[this._index] === "}" && this._currentMediaQuery) { this._lastCheckpoint = this._index + 1; this._state = CssToken.Selector; this._currentMediaQuery.endOffset = this._index + 1; this._rootNodes.push(this._currentMediaQuery); this._currentMediaQuery = null; return true; } return false; } private handleSelectorOpenBracket(): boolean { if (this._state === CssToken.Selector && this._text[this._index] === "{") { var selectorText = this._text.substring(this._lastCheckpoint, this._index); this._currentRuleset = { originalOffset: this._lastCheckpoint, selector: selectorText, declarations: [] }; this._lastCheckpoint = this._index + 1; this._state = CssToken.Property; return true; } return false; } private handlePropertyColon(): boolean { if (this._state === CssToken.Property && this._text[this._index] === ":") { var propertyText = this._text.substring(this._lastCheckpoint, this._index); this._currentDeclaration = { originalOffset: this._lastCheckpoint, property: propertyText, value: "" }; this._lastCheckpoint = this._index + 1; this._state = CssToken.Value; return true; } return false; } private handleValueSemicolon(): boolean { if (this._state === CssToken.Value && this._text[this._index] === ";") { var valueText = this._text.substring(this._lastCheckpoint, this._index); this._currentDeclaration.value = valueText; this._currentDeclaration.endOffset = this._index + 1; this._currentRuleset.declarations.push(this._currentDeclaration); this._currentDeclaration = null; this._lastCheckpoint = this._index + 1; this._state = CssToken.Property; return true; } return false; } private handleSelectorCloseBracket(): boolean { if (this._text[this._index] === "}") { if (this._state === CssToken.Property) { var incompleteDeclaration: ICssDeclaration = { originalOffset: this._lastCheckpoint, endOffset: this._index, property: this._text.substring(this._lastCheckpoint, this._index), value: null }; if (incompleteDeclaration.property.trim()) { this._currentRuleset.declarations.push(incompleteDeclaration); } this._lastCheckpoint = this._index + 1; this._state = CssToken.Selector; if (this._currentMediaQuery) { this._currentMediaQuery.endOffset = this._index; this._currentMediaQuery.rulesets.push(this._currentRuleset); } else { this._currentRuleset.endOffset = this._index; this._rootNodes.push(this._currentRuleset); } this._currentRuleset = null; return true; } if (this._state === CssToken.Value) { // No closing semicolon, which is valid syntax var valueText = this._text.substring(this._lastCheckpoint, this._index); this._currentDeclaration.value = valueText; this._currentDeclaration.isMissingSemicolon = true; this._currentDeclaration.endOffset = this._index; this._currentRuleset.declarations.push(this._currentDeclaration); this._currentRuleset.endOffset = this._index; this._currentDeclaration = null; this._lastCheckpoint = this._index + 1; this._state = CssToken.Selector; if (this._currentMediaQuery) { this._currentMediaQuery.rulesets.push(this._currentRuleset); } else { this._rootNodes.push(this._currentRuleset); } this._currentRuleset = null; return true; } } return false; } private handleIncompleteBlocks(): void { if (this._currentMediaQuery) { this._lastCheckpoint = this._currentMediaQuery.originalOffset; } else if (this._currentRuleset) { this._lastCheckpoint = this._currentRuleset.originalOffset; } if (this._lastCheckpoint < this._text.length - 1) { var textNode: ICssRuleset = { selector: this._text.substr(this._lastCheckpoint), originalOffset: this._lastCheckpoint, declarations: null, endOffset: this._index + 1 }; this._rootNodes.push(textNode); } } private handleCommentCharacter(): boolean { if (this._text.substr(this._index, 2) === "/*") { var endOfCommentIndex = this._text.indexOf("*/", this._index); if (endOfCommentIndex === -1) { endOfCommentIndex = this._text.length; } if (this._state === CssToken.Property && !this._text.substring(this._lastCheckpoint, this._index).trim()) { // this case is a disabled property var colonIndex = this._text.indexOf(":", this._index); if (colonIndex === -1 || colonIndex > endOfCommentIndex) { Assert.fail("this is not a disabled property, hanlde this case later"); } var propertyText = this._text.substring(this._index + 2, colonIndex); var semiColonIndex = this._text.indexOf(";", this._index); if (semiColonIndex === -1 || semiColonIndex >= endOfCommentIndex) { var valueText = this._text.substring(colonIndex + 1, endOfCommentIndex); } else { var valueText = this._text.substring(colonIndex + 1, semiColonIndex); } this._currentDeclaration = { originalOffset: this._lastCheckpoint, property: propertyText, value: valueText }; this._currentDeclaration.isDisabled = true; this._currentDeclaration.disabledFullText = this._text.substring(this._index, endOfCommentIndex + 2); this._index = endOfCommentIndex + "*/".length - 1; // Adjust -1 because the loop will increment index by 1 this._currentDeclaration.endOffset = this._index + 1; this._currentRuleset.declarations.push(this._currentDeclaration); this._currentDeclaration = null; this._lastCheckpoint = this._index + 1; } else { // This case is for normal comments this._index = endOfCommentIndex + "*/".length - 1; // Adjust -1 because the loop will increment index by 1 } return true; } return false; } private handleQuoteCharacter(): boolean { if (this._currentQuotationMark) { if (this._nextCharIsEscaped) { this._nextCharIsEscaped = false; } else if (this._text[this._index] === this._currentQuotationMark) { this._currentQuotationMark = ""; } else if (this._text[this._index] === "\\") { this._nextCharIsEscaped = true; } return true; } if (this._text[this._index] === "\"" || this._text[this._index] === "'") { this._currentQuotationMark = this._text[this._index]; return true; } return false; } private handleLeadingWhitespace(): boolean { if (this._lastCheckpoint === this._index && this._text[this._index].trim().length === 0) { this._lastCheckpoint++; return true; } return false; } } enum CssToken { Selector, Media, Property, Value }; }
the_stack
import * as i18n from "i18next"; import * as moment from "moment"; import * as React from "react"; import ContentEditable = require("react-contenteditable"); import { PermissionKind } from "sp-pnp-js"; import { DiscussionPermissionLevel, IDiscussionReply } from "../../../models/IDiscussionReply"; import IDiscussionReplyProps from "./IDiscussionReplyProps"; import { EditMode, IDiscussionReplyState } from "./IDiscussionReplyState"; class DiscussionReply extends React.Component<IDiscussionReplyProps, IDiscussionReplyState> { private readonly REPLY_NESTED_LEVEL_LIMIT = 3; private readonly CHILD_LEFT_PADDING_SIZE = 32; public constructor() { super(); this.state = { editMode: EditMode.NewComment, inputValue: "", isLoading: false, showInput: false, }; // Handlers this.toggleInput = this.toggleInput.bind(this); this.onValueChange = this.onValueChange.bind(this); this.updateReply = this.updateReply.bind(this); this.addNewReply = this.addNewReply.bind(this); this.deleteReply = this.deleteReply.bind(this); this.toggleLikeReply = this.toggleLikeReply.bind(this); } public render() { let renderIsLoading: JSX.Element = null; if (this.state.isLoading) { renderIsLoading = <i className="fa fa-spinner fa-spin"/>; } let renderEdit: JSX.Element = null; if (this.props.reply.UserPermissions.indexOf(DiscussionPermissionLevel.EditAsAuthor) !== -1 || this.props.reply.UserPermissions.indexOf(DiscussionPermissionLevel.Edit) !== -1) { renderEdit = <div><i className="fa fa-pencil-alt"/><a href="#" onClick={ () => { this.toggleInput(true, EditMode.UpdateComment); }}>{ i18n.t("comments_edit") }</a></div>; } let renderDelete: JSX.Element = null; if (this.props.reply.UserPermissions.indexOf(DiscussionPermissionLevel.DeleteAsAuthor) !== -1 || this.props.reply.UserPermissions.indexOf(DiscussionPermissionLevel.Delete) !== -1) { renderDelete = <div><i className="fa fa-trash"/><a href="#" onClick={ () => { this.deleteReply(this.props.reply); }}>{ i18n.t("comments_delete") }</a></div>; } let renderReply: JSX.Element = null; if (this.props.reply.UserPermissions.indexOf(DiscussionPermissionLevel.Add) !== -1 && this.props.replyLevel < this.REPLY_NESTED_LEVEL_LIMIT) { renderReply = <div><i className="fa fa-reply"/><a href="#" onClick={ () => { this.toggleInput(true, EditMode.NewComment); }}>{ i18n.t("comments_reply") }</a></div>; } const renderChildren: JSX.Element[] = []; if (this.props.reply.Children) { this.props.reply.Children.map((childReply, index) => { renderChildren.push( <DiscussionReply key={ childReply.Id } id={ `${this.props.id}${index}`} reply={ childReply } isLikeEnabled={ this.props.isLikeEnabled } addNewReply={this.props.addNewReply} deleteReply={ this.props.deleteReply } updateReply={ this.props.updateReply } toggleLikeReply={ this.props.toggleLikeReply } isChildReply={ true } replyLevel={ this.props.replyLevel + 1 } />, ); }); } let renderLike: JSX.Element = null; if (this.props.isLikeEnabled) { const likeLabel = this.isReplyLikedByCurrentUser(this.props.reply) ? i18n.t("comments_unlike") : i18n.t("comments_like"); renderLike = <div> <i className="fa fa-heart"/> <span>{this.props.reply.LikesCount}</span> <a href="#" onClick={ () => { this.toggleLikeReply(this.props.reply); }}>{ likeLabel }</a> </div>; } const posted = moment(this.props.reply.Posted); const modified = moment(this.props.reply.Edited); const isPosthasBeenEdited: JSX.Element = modified.diff(posted) > 0 ? <span>{`(${i18n.t("comments_edited")})`}</span> : null; const lastUpdate: JSX.Element = isPosthasBeenEdited ? <div>{`${i18n.t("comments_lastUpdate")} ${moment(modified).format("LLL")}`}</div> : null; const rootElementClassName = this.props.isChildReply ? "reply child" : "reply"; const paddingCalc = this.CHILD_LEFT_PADDING_SIZE * this.props.replyLevel; return <div> <div className="reply" style={{ paddingLeft: `${paddingCalc}px`}} key= { this.props.reply.Id }> <div> <img className="reply--user-avatar" src={ this.props.reply.Author.PictureUrl}/> </div> <div className="reply--content"> <div> <div className="reply--content--user-name">{ this.props.reply.Author.DisplayName } { isPosthasBeenEdited }</div> <div className="reply--content--body" dangerouslySetInnerHTML= {{__html: this.props.reply.Body }}></div> <div className="reply--content--date"> <div>{ `${i18n.t("comments_postedOn")} ${moment(this.props.reply.Posted).format("LLL")}`}</div> { lastUpdate } </div> </div> <div className="reply--content--actions"> { renderLike } { renderReply } { renderEdit } { renderDelete } <div> { renderIsLoading } </div> </div> { this.state.showInput ? <div className="reply--input-zone"> <ContentEditable id={`reply-input-${this.props.id}`} html={ this.state.inputValue } disabled={ false } onChange={ this.onValueChange } className="input" role="textbox" /> <button type="button" className="btn" onClick={ async () => { switch (this.state.editMode) { case EditMode.NewComment: await this.addNewReply(this.props.reply.Id, this.state.inputValue); break; case EditMode.UpdateComment: await this.updateReply(this.props.reply); break; } this.toggleInput(false, null); }}>{ this.state.editMode === EditMode.UpdateComment ? i18n.t("comments_update") : i18n.t("comments_post") }</button> <button className="btn" onClick={ () => { this.toggleInput(false, null); }} >{ i18n.t("comments_cancel") }</button> </div> : null } </div> </div> { renderChildren } </div>; } public onValueChange(e: any) { this.setState({ inputValue: e.target.value, }); } public componentDidUpdate() { // Set auto focus to input when replying or updating if (this.state.showInput) { switch (this.state.editMode) { case EditMode.NewComment: if (!this.state.inputValue) { this.setFocus(`reply-input-${this.props.id}`); } break; case EditMode.UpdateComment: if (this.state.inputValue === this.props.reply.Body) { this.setFocus(`reply-input-${this.props.id}`); break; } } } } /** * Adds a new reply * @param parentReplyId the parent reply item id * @param replyBody the reply body text */ public async addNewReply(parentReplyId: number, replyBody: string) { try { this.setState({ isLoading: true, }); await this.props.addNewReply(this.props.reply.Id, this.state.inputValue); this.setState({ isLoading: false, }); } catch (error) { throw error; } } /** * Updates an existing reply * @param replyToUpdate replu object to update */ public async updateReply(replyToUpdate: IDiscussionReply): Promise<void> { try { this.setState({ isLoading: true, }); const reply: IDiscussionReply = { Body: `<div>${this.state.inputValue}</div>`, // Set as HTML to be able to parse it easily afterward Id: replyToUpdate.Id, }; await this.props.updateReply(reply); this.setState({ isLoading: false, }); } catch (error) { throw error; } } /** * Deletes a single or multipels replies * @param replyToDelete the reply to delete */ public async deleteReply(replyToDelete: IDiscussionReply): Promise<void> { try { // We make this verification in the reply component itself to avoid an issue when the user says 'No'. // In this case, the state wouldn't be updated to false (isLoading). if (replyToDelete.Children.length > 0) { if (confirm(i18n.t("comments_delete_hierarchy"))) { this.setState({ isLoading: true, }); await this.props.deleteReply(replyToDelete); } } else { if (confirm(i18n.t("comments_delete_single"))) { this.setState({ isLoading: true, }); await this.props.deleteReply(replyToDelete); } } // After that the element is deleted in the DOM so we can't update the state anymore... } catch (error) { throw error; } } /** * Like or unlike a reply * @param reply the reply to like/unlike */ public async toggleLikeReply(reply: IDiscussionReply) { this.setState({ isLoading: true, }); await this.props.toggleLikeReply(reply, !this.isReplyLikedByCurrentUser(reply)); this.setState({ isLoading: false, }); } /** * Show or hide the input control * @param isVisible true if visible, false otherwise * @param editMode the current edit mode (UpdateComment or NewComment) */ public toggleInput(isVisible: boolean, editMode: EditMode) { let inputValue; switch (editMode) { case EditMode.UpdateComment: inputValue = this.props.reply.Body; break; case EditMode.NewComment: inputValue = ""; break; default: inputValue = ""; break; } this.setState({ editMode, inputValue, showInput: isVisible, }); } /** * Indicates whether or not a reply is liked by the current user * @param reply the reply to check */ private isReplyLikedByCurrentUser(reply: IDiscussionReply): boolean { // If the current user id is in the list ok "liked by" field let isLiked = false; if (reply.LikedBy.indexOf(_spPageContextInfo.userId.toString()) !== -1) { isLiked = true; } return isLiked; } /** * Sets the focus in the content editable div * @param eltId the DOM element id */ private setFocus(eltId: string) { const p = document.getElementById(eltId); const s = window.getSelection(); const r = document.createRange(); r.setStart(p, p.childElementCount); r.setEnd(p, p.childElementCount); s.removeAllRanges(); s.addRange(r); } } export default DiscussionReply;
the_stack
import React from 'react'; import { Story, Meta } from '@storybook/react'; import { CodeBlock } from '@zendeskgarden/react-typography'; import { Col, Grid, Row } from '@zendeskgarden/react-grid'; import { Language } from 'prism-react-renderer'; const CODE: Record<string, string> = { bash: ` #!/bin/sh # Exports. export ZSH="$HOME/.oh-my-zsh" # Aliases. alias ..="cd .." # Tools. if [ -f $(brew --prefix nvm)/nvm.sh ]; then mkdir -p $HOME/.nvm export NVM_DIR="$HOME/.nvm" source $(brew --prefix nvm)/nvm.sh fi`, css: ` button, .button, #button, [role='button'] { display: inline-block; transition: border-color .25s ease-in-out, box-shadow .1s ease-in-out, background-color .25s ease-in-out, color .25s ease-in-out; margin: 0; border: 1px solid transparent; border-radius: 4px; cursor: pointer; overflow: hidden !important; vertical-align: middle; text-align: center; text-decoration: none; /* Anchor tag reset */ text-overflow: ellipsis; white-space: nowrap; font-family: inherit; /* Override for <input> & <button> elements */ font-weight: var(--zd-font-weight-regular); -webkit-font-smoothing: subpixel-antialiased; box-sizing: border-box; user-select: none; -webkit-touch-callout: none; @media print { display: none; } }`, diff: ` @@ -1,3 +1,9 @@ +This is an important +notice! It should +therefore be located at +the beginning of this +document! + This part of the document has stayed the same from version to @@ -8,13 +14,8 @@ compress the size of the changes. -This paragraph contains -text that is outdated. -It will be deleted in the -near future. - It is important to spell !check this document. On the other hand, a misspelled word isn't the end of the world. @@ -22,3 +23,7 @@ this paragraph needs to be changed. Things can be added after it. + +This paragraph contains +important new additions +to this document. `, javascript: ` Prism.languages.markup = { comment: /<!--[\\s\\S]*?-->/, prolog: /<\\?[\\s\\S]+?\\?>/, doctype: { greedy: true }, cdata: /<!\\[CDATA\\[[\\s\\S]*?]]>/i, tag: { greedy: true, inside: { tag: { pattern: /^<\\/?[^\\s>\\/]+/i, inside: { punctuation: /^<\\/?/, namespace: /^[^\\s>\\/:]+:/ } }, 'attr-value': { pattern: /=\\s*(?:"[^"]*"|'[^']*'|[^\\s'">=]+)/i, inside: { punctuation: [ /^=/, { pattern: /^(\\s*)["']|["']$/, lookbehind: true } ] } }, punctuation: /\\/?>/u, 'attr-name': { pattern: /[^\\s>\\/]+/, inside: { namespace: /^[^\\s>\\/:]+:/ } } } }, entity: /&#?[\\da-z]{1,8};/i };`, json: ` { "data": [ { "key": "product", "version": 1, "schema": { "properties": { "id": { "type": "string", "description": "product id" }, "name": { "type": "string", "description": "product name" } }, "required": ["id", "name"] }, "created_at": "2018-01-01T10:20:30Z", "updated_at": "2018-01-01T10:20:30Z" }, { "key": "user", "version": 2, "schema": { "properties": { "id": { "type": "string", "description": "user id" }, "name": { "type": "string", "description": "user name" } }, "required": ["id", "name"] }, "created_at": "2018-01-01T10:20:30Z", "updated_at": "2018-01-01T10:20:30Z" } ] }`, markdown: ` # Title 1 ## Title 2 ### Title 3 #### Title 4 ##### Title 5 ###### Title 6 Our product is an extension of our brand and we want it to feel like Zendesk. We use visual design to shape what Zendesk looks like, and voice and tone to shape what Zendesk sounds like. | Voice | Tone | | ---------- | ---------- | | About us | About them | | Consistent | Variable | *Italic* **Bold** **Bold on multiple lines** *Italic on multiple lines too* * This is * an unordered list 1. This is an 2. ordered list * *List item in italic* * **List item in bold** * [List item as a link](http://example.com "This is an example") > This is a quotation >> With another quotation inside > _italic here_, __bold there__ > And a [link](http://example.com)`, markup: ` <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta property="og:title" content=""> <meta property="og:type" content=""> <meta property="og:url" content=""> <meta property="og:image" content=""> <link rel="manifest" href="site.webmanifest"> <link rel="apple-touch-icon" href="icon.png"> <!-- Place favicon.ico in the root directory --> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <meta name="theme-color" content="#fafafa"> </head> <body> <!-- Add your site or application content here --> <p>Hello world! This is HTML5 Boilerplate.</p> <script src="js/vendor/modernizr-{{MODERNIZR_VERSION}}.min.js"></script> <script src="js/plugins.js"></script> <script src="js/main.js"></script> <!-- Google Analytics: change UA-XXXXX-Y to be your site's ID. --> <script> window.ga = function () { ga.q.push(arguments) }; ga.q = []; ga.l = +new Date; ga('create', 'UA-XXXXX-Y', 'auto'); ga('set', 'anonymizeIp', true); ga('set', 'transport', 'beacon'); ga('send', 'pageview') </script> <script src="https://www.google-analytics.com/analytics.js" async></script> </body> </html>`, python: ` def median(pool): '''Statistical median to demonstrate doctest. >>> median([2, 9, 9, 7, 9, 2, 4, 5, 8]) 7 ''' copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[(size - 1) / 2] else: return (copy[size/2 - 1] + copy[size/2]) / 2 if __name__ == '__main__': import doctest doctest.testmod()`, tsx: ` /** * Copyright Zendesk, Inc. * * Use of this source code is governed under the Apache License, Version 2.0 * found at http://www.apache.org/licenses/LICENSE-2.0. */ import React, { useState, useEffect, useRef } from 'react'; import styled from 'styled-components'; import { Dropdown, Multiselect, Field, Menu, Item, Label } from '@zendeskgarden/react-dropdowns'; import { mediaQuery } from '@zendeskgarden/react-theming'; import { Row, Col } from '@zendeskgarden/react-grid'; import { Tag } from '@zendeskgarden/react-tags'; import debounce from 'lodash.debounce'; const options = [ 'Asparagus', 'Brussel sprouts', 'Cauliflower', 'Garlic', 'Jerusalem artichoke', 'Kale', 'Lettuce', 'Onion', 'Mushroom', 'Potato', 'Radish', 'Spinach', 'Tomato', 'Yam', 'Zucchini' ]; const StyledCol = styled(Col)\` \${p => mediaQuery('down', 'xs', p.theme)} { margin-top: \${p => p.theme.space.sm}; } \`; const initialSelectedItems = [options[0], options[1], options[2], options[3]]; const Example = () => { const [selectedItems, setSelectedItems] = useState(initialSelectedItems); const [compactSelectedItems, setCompactSelectedItems] = useState(initialSelectedItems); const [inputValue, setInputValue] = useState(''); const [compactInputValue, setCompactInputValue] = useState(''); const [isLoading, setIsLoading] = useState(false); const [matchingOptions, setMatchingOptions] = useState(options); const filterMatchingOptionsRef = useRef( debounce((value: string) => { const matchedOptions = options.filter(option => { return option.trim().toLowerCase().indexOf(value.trim().toLowerCase()) !== -1; }); setMatchingOptions(matchedOptions); setIsLoading(false); }, 300) ); useEffect(() => { setIsLoading(true); filterMatchingOptionsRef.current(inputValue); }, [inputValue]); useEffect(() => { setIsLoading(true); filterMatchingOptionsRef.current(compactInputValue); }, [compactInputValue]); const renderOptions = () => { if (isLoading) { return <Item disabled>Loading</Item>; } if (matchingOptions.length === 0) { return <Item disabled>No matches found</Item>; } return matchingOptions.map(option => ( <Item key={option} value={option}> <span>{option}</span> </Item> )); }; return ( <Row> <Col> <Dropdown inputValue={inputValue} selectedItems={selectedItems} onSelect={items => setSelectedItems(items)} downshiftProps={{ defaultHighlightedIndex: 0 }} onStateChange={changes => { if (Object.prototype.hasOwnProperty.call(changes, 'inputValue')) { setInputValue((changes as any).inputValue); } }} > <Field> <Label>Vegetables</Label> <Multiselect renderItem={({ value, removeValue }: any) => ( <Tag> <span>{value}</span> <Tag.Close onClick={() => removeValue()} /> </Tag> )} /> </Field> <Menu>{renderOptions()}</Menu> </Dropdown> </Col> <StyledCol> <Dropdown inputValue={compactInputValue} selectedItems={compactSelectedItems} onSelect={items => setCompactSelectedItems(items)} downshiftProps={{ defaultHighlightedIndex: 0 }} onStateChange={changes => { if (Object.prototype.hasOwnProperty.call(changes, 'inputValue')) { setCompactInputValue((changes as any).inputValue); } }} > <Field> <Label>Vegetables</Label> <Multiselect isCompact renderItem={({ value, removeValue }: any) => ( <Tag> <span>{value}</span> <Tag.Close onClick={() => removeValue()} /> </Tag> )} /> </Field> <Menu isCompact>{renderOptions()}</Menu> </Dropdown> </StyledCol> </Row> ); }; export default Example; `, typescript: ` import { clean, publish } from 'gh-pages'; import commander, { Command } from 'commander'; import { repository as getRepository, token as getToken } from '..'; import { handleErrorMessage, handleSuccessMessage } from '../../utils'; import { Ora } from 'ora'; import execa from 'execa'; interface IGitHubPagesArgs { dir: string; path?: string; message?: string; token?: string; spinner?: Ora; } /** * Execute the \`github-pages\` command. * * @param {string} args.dir Folder to publish. * @param {string} [args.path] Path to a git directory. * @param {string} [args.message] Commit message. * @param {string} [args.token] GitHub personal access token. * @param {Ora} [args.spinner] Terminal spinner. * * @returns {Promise<string>} The GitHub pages URL. */ export const execute = async (args: IGitHubPagesArgs): Promise<string | undefined> => { let retVal: string | undefined; try { const token = args.token || (await getToken(args.spinner)); const repository = await getRepository(args.path || args.dir, args.spinner); const message = args.message || 'Updates [skip ci]'; if (token && repository) { const { owner, repo } = repository; let name: string; let email: string; try { name = (await execa('git', ['config', 'user.name'])).stdout.toString(); email = (await execa('git', ['config', 'user.email'])).stdout.toString(); } catch { name = 'Zendesk Garden'; email = 'garden@zendesk.com'; } clean(); await publish( args.dir, { repo: \`https://\${token}@github.com/\${owner}/\${repo}.git\`, user: { name, email }, message, silent: true }, error => { if (error) { handleErrorMessage(error, 'github-pages', args.spinner); } else { retVal = \`https://\${owner}.github.io/\${repo}/\`; } } ); } else { throw new Error('Invalid git repository'); } } catch (error) { handleErrorMessage(error, 'github-pages', args.spinner); throw error; } return retVal; };` }; export default { title: 'Components/Typography/CodeBlock', component: CodeBlock } as Meta; interface IDefaultStoryProps { language: Language; size: 'small' | 'medium' | 'large' | undefined; isLight: boolean; isNumbered: boolean; highlightLines: number[]; } export const Default: Story<IDefaultStoryProps> = ({ language, size, isLight, isNumbered, highlightLines }) => ( <Grid> <Row> <Col textAlign="center"> <CodeBlock style={{ textAlign: 'left' }} language={language} size={size} isLight={isLight} isNumbered={isNumbered} highlightLines={highlightLines} > {CODE[language]} </CodeBlock> </Col> </Row> </Grid> ); const range = (size: number, start = 0) => [...Array(size).keys()].map(x => x + start); Default.args = { highlightLines: range(15, 17), language: 'tsx' }; Default.argTypes = { language: { control: { type: 'select', options: Object.keys(CODE) } } };
the_stack
"use strict"; import * as fs from "fs"; import { CancellationToken, ConfigurationChangeEvent, Disposable, Hover, HoverProvider, Position, TextDocument, TextEditor, TextEditorDecorationType, window } from "vscode"; import * as vscode from "vscode"; import { CodeStreamDiffUriData } from "@codestream/protocols/agent"; import { SessionStatus, SessionStatusChangedEvent } from "../api/session"; import { Functions, Strings } from "../system"; import { configuration } from "../configuration"; import * as csUri from "../system/uri"; // import { BuiltInCommands } from "../constants"; import { Container } from "../container"; // const emptyArray = (Object.freeze([]) as any) as any[]; // TODO need cache for TextDocument to glyphs const positionStyleMap: { [key: string]: string } = { inline: "display: inline-block; margin: 0 0.5em 0 0; vertical-align: middle;", overlay: "display: inline-block; left: 0; position: absolute; top: 50%; transform: translateY(-50%)" }; const buildDecoration = (position: string) => { const pngPath = Container.context.asAbsolutePath("assets/images/eye.png"); try { const pngBase64 = fs.readFileSync(pngPath, { encoding: "base64" }); const pngInlineUrl = `data:image/png;base64,${pngBase64}`; return { contentText: "", height: "16px", width: "16px", textDecoration: `none; background-image: url(${pngInlineUrl}); background-position: center; background-repeat: no-repeat; background-size: contain; ${positionStyleMap[position]}` }; } catch (e) { return; } }; const MarkerPositions = ["inline", "overlay"]; const MarkerTypes = ["comment"]; const MarkerColors = ["blue", "green", "yellow", "orange", "red", "purple", "aqua", "gray"]; export class InstrumentationDecorationProvider implements HoverProvider, vscode.Disposable { private readonly _disposable: Disposable; private regex: RegExp; private _decorationTypes: { [key: string]: TextEditorDecorationType } | undefined; private _enabledDisposable: Disposable | undefined; private _suspended = false; private _watchedEditorsMap: Map<string, () => void> | undefined; // TODO fix me private _current: any[] = []; constructor() { this._disposable = Disposable.from( configuration.onDidChange(this.onConfigurationChanged, this), Container.session.onDidChangeSessionStatus(this.onSessionStatusChanged, this) ); this.regex = /[Nn]ew[\-_]?[Rr]elic\.([a-zA-Z_]+)\((["'][\w\-\_]+["'])/g; const decorationTypes: { [key: string]: TextEditorDecorationType } = Object.create(null); // window.onDidChangeVisibleTextEditors(this.onEditorVisibilityChanged, this); // vscode.workspace.onDidCloseTextDocument((e: TextDocument) => { // if (this._current.length) { // console.log(e); // this._current.forEach(_ => _.val.dispose()); // } // }); // vscode.workspace.onDidChangeTextDocument((e: vscode.TextDocumentChangeEvent) => { // const editor = window.activeTextEditor; // if (!editor) return; // f(e.document); // }); for (const position of MarkerPositions) { for (const type of MarkerTypes) { for (const color of MarkerColors) { const key = `${position}-${type}-${color}`; const before = buildDecoration(position); if (before) { decorationTypes[key] = window.createTextEditorDecorationType({ before }); } } } } this._decorationTypes = decorationTypes; } dispose() { this.disable(); this._disposable && this._disposable.dispose(); } private onConfigurationChanged(e: ConfigurationChangeEvent) { if (configuration.changed(e, configuration.name("showInstrumentationGlyphs").value)) { this.ensure(true); } } private onSessionStatusChanged(e: SessionStatusChangedEvent) { switch (e.getStatus()) { case SessionStatus.SignedOut: this.disable(); break; case SessionStatus.SignedIn: { this.ensure(); break; } } } private ensure(reset: boolean = false) { if (!Container.config.showMarkerGlyphs || !Container.session.signedIn) { this.disable(); return; } if (reset) { this.disable(); } this.enable(); } private disable() { if (this._enabledDisposable === undefined) return; for (const editor of this.getApplicableVisibleEditors()) { this.clear(editor); } this._enabledDisposable.dispose(); this._enabledDisposable = undefined; } private enable() { if ( this._enabledDisposable !== undefined || Container.session.status !== SessionStatus.SignedIn ) { return; } const decorationTypes: { [key: string]: TextEditorDecorationType } = Object.create(null); if (!this._suspended) { for (const position of MarkerPositions) { for (const type of MarkerTypes) { for (const color of MarkerColors) { const key = `${position}-${type}-${color}`; const before = buildDecoration(position); if (before) { decorationTypes[key] = window.createTextEditorDecorationType({ before }); } } } } } // for (const color of MarkerColors) { // decorationTypes[`overviewRuler-${color}`] = window.createTextEditorDecorationType({ // overviewRulerColor: MarkerOverviewRuler[color], // overviewRulerLane: OverviewRulerLane.Center // }); // decorationTypes[`trap-highlight-${color}`] = window.createTextEditorDecorationType({ // rangeBehavior: DecorationRangeBehavior.OpenOpen, // isWholeLine: true, // backgroundColor: MarkerHighlights[color] // }); // } this._decorationTypes = decorationTypes; const subscriptions: Disposable[] = [ ...Object.values(decorationTypes), Container.session.onDidChangeSessionStatus(this.onSessionStatusChanged, this), window.onDidChangeVisibleTextEditors(this.onEditorVisibilityChanged, this), vscode.workspace.onDidCloseTextDocument(this.onDocumentClosed, this), vscode.workspace.onDidSaveTextDocument((e: TextDocument) => { this.f(e); }) ]; if (!this._suspended) { subscriptions.push(vscode.languages.registerHoverProvider({ scheme: "file" }, this)); subscriptions.push( vscode.languages.registerHoverProvider({ scheme: "codestream-diff" }, this) ); } this._enabledDisposable = Disposable.from(...subscriptions); this.applyToApplicableVisibleEditors(); } applyToApplicableVisibleEditors(editors = window.visibleTextEditors) { const editorsToWatch = new Map<string, () => void>(); for (const e of this.getApplicableVisibleEditors(editors)) { const key = e.document.uri.toString(); editorsToWatch.set( key, (this._watchedEditorsMap && this._watchedEditorsMap.get(key)) || Functions.debounce(() => this.apply(e, true), 1000) ); this.apply(e); } this._watchedEditorsMap = editorsToWatch; } private getApplicableVisibleEditors(editors = window.visibleTextEditors) { return editors.filter(this.isApplicableEditor); } private isApplicableEditor(editor: TextEditor | undefined) { if (!editor || !editor.document) return false; if (editor.document.uri.scheme === "file") return true; // check for review diff const parsedUri = Strings.parseCSReviewDiffUrl(editor.document.uri.toString()); if (parsedUri) { return parsedUri.version === "right"; } // check for PR diff const codeStreamDiff = csUri.Uris.fromCodeStreamDiffUri<CodeStreamDiffUriData>( editor.document.uri.toString() ); if (codeStreamDiff) { return codeStreamDiff.side === "right"; } return false; } private async onDocumentClosed(e: TextDocument) { if (this._current.length) { console.log(e); this._current.forEach(_ => _.val.dispose()); } } async apply(editor: TextEditor | undefined, force: boolean = false) { if ( this._decorationTypes === undefined || !Container.session.signedIn || !this.isApplicableEditor(editor) ) { return; } if (editor && editor.document) { this.f(editor.document!); } console.log(force); // const decorations = await this.provideDecorations(editor!); // if (Object.keys(decorations).length === 0) { // this.clear(editor); // return; // } // for (const [key, value] of Object.entries(this._decorationTypes)) { // editor!.setDecorations(value, (decorations[key] as any) || emptyArray); // } } // findVars(symbols: vscode.DocumentSymbol[]): vscode.DocumentSymbol[] { // const vars = symbols.filter( // symbol => symbol !== undefined // // symbol.kind === vscode.SymbolKind.Method || symbol.kind === vscode.SymbolKind.Function // ); // return vars.concat( // symbols.map(symbol => this.findVars(symbol.children)).reduce((a, b) => a.concat(b), []) // ); // } private async onEditorVisibilityChanged(editors: vscode.TextEditor[]) { for (const e of editors) { this.f(e.document); } } clear(editor: TextEditor | undefined = window.activeTextEditor) { if (editor === undefined || this._decorationTypes === undefined) return; // for (const decoration of Object.values(this._decorationTypes)) { // editor.setDecorations(decoration, emptyArray); // } } f(document: TextDocument) { if (document.languageId === "Log") return; const text = document.getText(); const editor = window.activeTextEditor; if (!editor) return; let matches; let found = false; if (this._current.length) { this._current.forEach(_ => _.val.dispose()); // this._current = []; } while ((matches = this.regex.exec(text)) !== null) { const line = document.lineAt(document.positionAt(matches.index).line); const indexOf = line.text.indexOf(matches[0]); const position = new vscode.Position(line.lineNumber, indexOf); const range = document.getWordRangeAtPosition(position, new RegExp(this.regex)); if (range) { // const v = this._decorationTypes!["inline-comment-yellow"]; // if (this._current.find(_ => _.start === range.start.line)) { // } else { const v = window.createTextEditorDecorationType({ before: buildDecoration("inline") }); this._current.push({ val: v, start: range.start.line }); editor!.setDecorations(v, [ new vscode.Range(range.start.line, 0, range.end.line, range.end.character) ]); // } found = true; // for (const [key, value] of Object.entries(this._decorationTypes!)) { // console.log(key); // e.setDecorations(this._decorationTypes!["inline-comment-yellow"], [range]); // } } } if (!found) { // if (this._current.length) { // this._current.forEach(_ => _.val.dispose()); // // this._current = []; // } } } // private async onEditorVisibilityChanged2(editors: vscode.TextEditor[]) { // for (const e of editors) { // const text = e.document.getText(); // // const foo = (await vscode.commands.executeCommand( // // BuiltInCommands.ExecuteDocumentSymbolProvider, // // e.document.uri // // )) as vscode.DocumentSymbol[]; // // const list = []; // // for (const variable of this.findVars(foo)) { // // list.push(variable.name); // // } // // // const bar = await vscode.commands.executeCommand( // // // BuiltInCommands.ExecuteDocumentHighlights, // // // e.document.uri // // // ); // // console.log(foo); // // const aaa = await vscode.commands.executeCommand( // // "vscode.provideDocumentSemanticTokens", // // e.document.uri // // ); // // console.log(aaa); // const document = e.document; // let matches; // while ((matches = this.regex.exec(text)) !== null) { // const line = document.lineAt(document.positionAt(matches.index).line); // const indexOf = line.text.indexOf(matches[0]); // const position = new vscode.Position(line.lineNumber, indexOf); // const suc = await vscode.commands.executeCommand( // "vscode.executeDefinitionProvider", // e.document.uri, // position // ); // console.log(suc); // const range = document.getWordRangeAtPosition(position, new RegExp(this.regex)); // if (range) { // e.setDecorations(this._decorationTypes!["inline-comment-yellow"], [range]); // // for (const [key, value] of Object.entries(this._decorationTypes!)) { // // console.log(key); // // e.setDecorations(this._decorationTypes!["inline-comment-yellow"], [range]); // // } // } // } // } // } async provideHover( document: TextDocument, position: Position, token: CancellationToken ): Promise<Hover | undefined> { const regex = new RegExp(this.regex); console.log(position, token); const line = document.lineAt(position.line); // // const indexOf = line.text.indexOf(matches[0]); // // const position = new vscode.Position(line.lineNumber, indexOf); // const range = document.getWordRangeAtPosition(position, new RegExp(this.regex)); // const text = document.getText(range); const matches = regex.exec(line.text); if (matches) { let message = ""; message += ` \n\n[__View Custom Transaction \u2197__](command:codestream.instrumentationOpen?${encodeURIComponent( JSON.stringify({ name: matches[2].replace(/['"]/g, "") }) )} " View Custom Transaction")`; const markdown = new vscode.MarkdownString(message, true); markdown.isTrusted = true; return new Hover(markdown, line.range); } return undefined; } }
the_stack
import difference from 'lodash/difference'; import { DataTypeConfig, ReadonlyDataTypeConfig, Maybe, SortOrder, FieldType, DataTypeFields, DataTypeFieldConfig, xLuceneVariables, } from '@terascope/types'; import { Node as xLuceneNode } from 'xlucene-parser'; import { DataEntity, TSError, getTypeOf, isFunction, isPlainObject, trimFP, isInteger, joinList, getHashCodeFrom, } from '@terascope/utils'; import { Column, KeyAggFn, makeUniqueKeyAgg } from '../column'; import { AggregationFrame } from '../aggregation-frame'; import { buildRecords, columnsToBuilderEntries, columnsToDataTypeConfig, concatColumnsToColumns, createColumnsWithIndices, distributeRowsToColumns, getSortedColumnsByValueCount, isEmptyRow, makeKeyForRow, makeUniqueRowBuilder, processFieldFilter, splitOnNewLineIterator } from './utils'; import { Builder, getBuildersForConfig } from '../builder'; import { FieldArg, flattenStringArg, freezeArray, getFieldsFromArg, ReadableData, WritableData, } from '../core'; import { getMaxColumnSize } from '../aggregation-frame/utils'; import { SerializeOptions, Vector } from '../vector'; import { buildSearchMatcherForQuery } from './search'; import { DataFrameHeaderConfig } from './interfaces'; import { convertMetadataFromJSON, convertMetadataToJSON } from './metadata-utils'; /** * An immutable columnar table with APIs for data pipelines. * * @note null/undefined values are treated the same */ export class DataFrame< T extends Record<string, unknown> = Record<string, any>, > { /** * Create a DataFrame from an array of JSON objects */ static fromJSON< R extends Record<string, unknown> = Record<string, any>, >( config: DataTypeConfig|ReadonlyDataTypeConfig, records: R[] = [], options?: DataFrameOptions ): DataFrame<R> { const columns = distributeRowsToColumns(config, records); return new DataFrame(columns, options); } /** * Create an empty DataFrame */ static empty< R extends Record<string, unknown> = Record<string, any>, >( config: DataTypeConfig|ReadonlyDataTypeConfig, options?: DataFrameOptions ): DataFrame<R> { const columns = distributeRowsToColumns<R>(config, []); return new DataFrame(columns, options); } /** * Create a DataFrame from a serialized format, * the first row is data frame metadata, * all of the subsequent rows are serialized columns. * * When using this method, the input should be split by a new line. */ static async deserializeIterator< R extends Record<string, unknown> = Record<string, any>, >(data: Iterable<Buffer|string>|AsyncIterable<Buffer|string>): Promise<DataFrame<R>> { let index = -1; let metadata: Record<string, unknown>|undefined; let name: string|undefined; const columns: Column<any, keyof R>[] = []; for await (const row of data) { // ensure empty rows don't get passed along if (row.length <= 1) continue; index++; if (index === 0) { ({ metadata, name } = JSON.parse(row as string) as DataFrameHeaderConfig); metadata = convertMetadataFromJSON(metadata ?? {}); } else { columns.push(Column.deserialize(row)); } } return new DataFrame<R>(columns, { name, metadata }); } /** * Create a DataFrame from a serialized format, * the first row is data frame metadata, * all of the subsequent rows are serialized columns. * The rows should be joined with a newline. * * When using this method, the whole serialized file should be * passed in. * * For a more advanced steam like processing, see {@see DataFrame.deserializeIterator} * Using that method may be required for deserializing a buffer or string * greater than 1GB. */ static async deserialize< R extends Record<string, unknown> = Record<string, any>, >(data: Buffer|string): Promise<DataFrame<R>> { return DataFrame.deserializeIterator( splitOnNewLineIterator(data) ); } /** * The name of the Frame */ name?: string; /** * The list of columns */ readonly columns: readonly Column<any, keyof T>[]; /** * An array of the column names */ readonly fields: readonly (keyof T)[]; /** * Metadata about the Frame */ readonly metadata: Record<string, any>; /** * Size of the DataFrame */ readonly size: number; /** cached id for lazy loading the id */ #id?: string; /** * Use this to cache the the column index needed, this * should speed things up */ protected _fieldToColumnIndexCache?: Map<(keyof T), number>; constructor( columns: Column<any, keyof T>[]|readonly Column<any, keyof T>[], options?: DataFrameOptions ) { this.name = options?.name; this.metadata = options?.metadata ? { ...options.metadata } : {}; this.columns = freezeArray(columns); this.fields = Object.freeze(this.columns.map((col) => col.name)); const lengths = this.columns.map((col) => col.size); if (new Set(lengths).size > 1) { throw new Error( `All columns in a DataFrame must have the same length, got ${joinList(lengths)}` ); } this.size = lengths[0] ?? 0; if (!isInteger(this.size)) { throw new Error(`Invalid size given to DataFrame, got ${this.size} (${getTypeOf(this.size)})`); } } /** * Iterate over each row, this returns the JSON compatible values. */ * [Symbol.iterator](): IterableIterator<T> { yield* this.rows(true); } /** * Iterate over each index and row, this returns the internal stored values. */ * entries( json?: boolean, options?: SerializeOptions ): IterableIterator<[index: number, row: T]> { for (let i = 0; i < this.size; i++) { const row = this.getRow(i, json, options); if (row) yield [i, row]; } } /** * Iterate each row */ * rows(json?: boolean, options?: SerializeOptions): IterableIterator<T> { if (options?.skipDuplicateObjects) { yield* this.rowsWithoutDuplicates(json, options); return; } for (let i = 0; i < this.size; i++) { const row = this.getRow(i, json, options); if (row) yield row; } } /** * This is more expensive and little more complicated. * In the future we pass in json=false to each column and * the call toJSONCompatibleValue after each generating the hash * to be consistent with hash */ private* rowsWithoutDuplicates( json?: boolean, options?: SerializeOptions ): IterableIterator<T> { const hashes = new Set<string>(); for (let i = 0; i < this.size; i++) { const row = this.getRow(i, json, options); if (row) { const hash = getHashCodeFrom(row); if (!hashes.has(hash)) { hashes.add(hash); yield row; } } } } /** * A Unique ID for the DataFrame * The ID will only change if the columns or data change */ get id(): string { if (this.#id) return this.#id; const long = this.columns .map((col) => `${col.name}(${col.id})`) .sort() .join(':'); const id = getHashCodeFrom(long); this.#id = id; return id; } /** * Create a new DataFrame with the same metadata but with different data */ fork<R extends Record<string, unknown> = T>( columns: Column<any, keyof R>[]|readonly Column<any, keyof R>[] ): DataFrame<R> { return new DataFrame<R>(columns, { name: this.name, metadata: this.metadata, }); } /** * Generate the DataType config from the columns. */ get config(): DataTypeConfig { return columnsToDataTypeConfig(this.columns); } /** * Get a column, or columns by name, returns a new DataFrame */ select<K extends keyof T>(...fieldArg: FieldArg<K>[]): DataFrame<Pick<T, K>> { const fields = [...getFieldsFromArg(this.fields, fieldArg)]; return this.fork(fields.map( (field): Column<any, any> => this.getColumnOrThrow(field) )); } /** * Select fields in a data frame, this will work with nested object * fields. * * Fields that don't exist in the data frame are safely ignored to make * this function handle more suitable for production environments */ deepSelect<R extends T>( fieldSelectors: string[]|readonly string[], ): DataFrame<R> { const columns: Column<any, any>[] = []; const existingFieldsConfig = this.config.fields; const existingFields = Object.keys(existingFieldsConfig); const matchedFields: Record<string, Set<string>> = Object.create(null); for (const field of existingFields) { const matches = fieldSelectors.some((selector) => { if (field === selector) return true; if (field.startsWith(`${selector}.`)) { const baseConfig = existingFieldsConfig[selector]; if (!baseConfig?._allow_empty) return true; } return false; }); if (matches) { const [base] = field.split('.', 1); matchedFields[base] ??= new Set(); if (field !== base) { matchedFields[base].add( // only store the scoped field // because it is easier to look // it up in the childConfig that way field.replace(`${base}.`, '') ); } } } for (const [field, childFields] of Object.entries(matchedFields)) { const col = this.getColumn(field); if (col) { columns.push(col.selectSubFields( childFields, )); } } return this.fork<R>(columns); } /** * Get a column, or columns by index, returns a new DataFrame */ selectAt<R extends Record<string, unknown> = T>(...indices: number[]): DataFrame<R> { return this.fork(indices.map( (index): Column<any, any> => this.getColumnAt(index)! )); } /** * Create a AggregationFrame instance which can be used to run aggregations */ aggregate(): AggregationFrame<T> { return new AggregationFrame<T>(this.columns, { name: this.name, metadata: this.metadata, }); } /** * Order the rows by fields, format of is `field:asc` or `field:desc`. * Defaults to `asc` if none specified */ orderBy(...fieldArgs: FieldArg<string>[]): DataFrame<T>; orderBy(...fieldArgs: FieldArg<keyof T>[]): DataFrame<T>; orderBy(...fieldArgs: (FieldArg<keyof T>[]|FieldArg<string>[])): DataFrame<T> { const fields = flattenStringArg(fieldArgs); const sortBy = [...fields].map( (fieldArg): { field: keyof T; vector: Vector<any>; direction: SortOrder } => { const [field, direction = 'asc'] = `${fieldArg}`.split(':').map(trimFP()); if (direction !== 'asc' && direction !== 'desc') { throw new TSError( `Expected direction ("${direction}") for orderBy field ("${field}") to be either "asc" or "desc"`, { context: { safe: true }, statusCode: 400 } ); } return { field: field as keyof T, direction: direction as SortOrder, vector: this.getColumnOrThrow(field).vector, }; } ); const sortedIndices = Vector.getSortedIndices(sortBy); const len = sortedIndices.length; const builders = getBuildersForConfig<T>(this.config, len); for (let i = 0; i < len; i++) { const moveTo = sortedIndices[i]; for (const col of this.columns) { const val = col.vector.get(i); builders.get(col.name)!.set(moveTo, val); } } return this._forkWithBuilders(builders); } /** * Sort the records by a field, an alias of orderBy. * * @see orderBy */ sort(...fieldArgs: FieldArg<string>[]): DataFrame<T>; sort(...fieldArgs: FieldArg<keyof T>[]): DataFrame<T>; sort(...fieldArgs: (FieldArg<keyof T>[]|FieldArg<string>[])): DataFrame<T> { return this.orderBy(...fieldArgs); } /** * Search the DataFrame using an xLucene query */ search( query: string, variables?: xLuceneVariables, overrideParsedQuery?: xLuceneNode, stopAtMatch?: number ): DataFrame<T> { const matcher = buildSearchMatcherForQuery(this, query, variables, overrideParsedQuery); return this.filterDataFrameRows(matcher, stopAtMatch); } /** * Require specific columns to exist on every row */ require(...fieldArg: FieldArg<keyof T>[]): DataFrame<T> { const fields = getFieldsFromArg(this.fields, fieldArg); const hasRequiredFields = [...fields].reduce( (acc, field): FilterByFn<T> => { if (!acc) return (row: T) => row[field] != null; return (row: T, index: number) => { if (!acc(row, index)) return false; return row[field] != null; }; }, undefined as FilterByFn<T>|undefined )!; return this._filterByFn(hasRequiredFields, false); } /** * Filter the DataFrame by fields, all fields must return true * for a given row to returned in the filtered DataType * * @example * * dataFrame.filter({ * name(val) { * return val != null; * }, * age(val) { * return val != null && val >= 20; * } * }); */ filterBy(filters: FilterByFields<T>|FilterByFn<T>, json?: boolean): DataFrame<T> { if (isFunction(filters)) { return this._filterByFn(filters, json ?? false); } return this._filterByFields(filters, json ?? false); } private _filterByFields(filters: FilterByFields<T>, json: boolean): DataFrame<T> { const indices = new Set<number>(); Object.entries(filters).forEach(([field, filter]) => { processFieldFilter( indices, this.getColumnOrThrow(field), filter, json ); }); if (indices.size === this.size) return this; return this.fork(createColumnsWithIndices( this.columns, indices, indices.size )); } private _filterByFn(fn: FilterByFn<T>, json: boolean): DataFrame<T> { const records: T[] = []; for (const [index, row] of this.entries(json)) { if (fn(row, index)) records.push(row); } if (records.length === this.size) return this; return this.fork( distributeRowsToColumns(this.config, records) ); } /** * This allows you to filter each row more efficiently by * since the rows aren't pulled from the data frame unless they match. * * This was designed to be used in @see DataFrame.search */ filterDataFrameRows(fn: FilterByRowsFn, stopAtMatch?: number): DataFrame<T> { if (stopAtMatch != null && (stopAtMatch < 0 || stopAtMatch > this.size)) { throw new RangeError(`Expected stopAtMatch param to be between 0 and ${this.size}, got ${stopAtMatch}`); } const builders = getBuildersForConfig(this.config, this.size); let returning = 0; for (let i = 0; i < this.size; i++) { if (stopAtMatch != null && returning >= stopAtMatch) { break; } if (fn(i)) { returning++; for (const [name, builder] of builders) { const value = this.getColumnOrThrow(name).vector.get(i); const writeIndex = builder.currentIndex++; if (value != null) { // doing this is faster than append // because we KNOW it is already in a valid format builder.data.set(writeIndex, value); } } } } return this._forkWithBuilders(builders, returning); } /** * Remove the empty rows from the data frame, * this is optimization that won't require moving * around as much memory */ removeEmptyRows(): DataFrame<T> { if (!this.hasEmptyRows()) return this; const len = this.size; let returning = len; const builders = getBuildersForConfig<T>(this.config, len); const sortedColumns = getSortedColumnsByValueCount(this.columns); for (let i = 0; i < len; i++) { if (isEmptyRow(sortedColumns, i)) { returning--; } else { for (const [name, builder] of builders) { const value = this.getColumnOrThrow(name).vector.get(i); const writeIndex = builder.currentIndex++; if (value != null) { // doing this is faster than append // because we KNOW it is already in a valid format builder.data.set(writeIndex, value); } } } } if (returning === this.size) return this; return this._forkWithBuilders(builders, returning); } /** * Count the number of empty rows */ countEmptyRows(): number { if (!this.hasNilValues()) return 0; let empty = 0; const columns = getSortedColumnsByValueCount(this.columns); const len = this.size; for (let i = 0; i < len; i++) { if (isEmptyRow(columns, i)) { empty++; } } return empty; } /** * Check if there are any empty rows at all */ hasEmptyRows(): boolean { if (!this.hasNilValues()) return false; const columns = getSortedColumnsByValueCount(this.columns); const len = this.size; for (let i = 0; i < len; i++) { if (isEmptyRow(columns, i)) { return true; } } return false; } /** * Check if there are any columns with nil values */ hasNilValues(): boolean { for (const column of this.columns) { if (column.vector.hasNilValues()) return true; } return false; } /** * Remove duplicate rows with the same value for select fields */ unique(...fieldArg: FieldArg<keyof T>[]): DataFrame<T> { return this._unique( getFieldsFromArg(this.fields, fieldArg) ); } /** * Alias for unique */ distinct(...fieldArg: FieldArg<keyof T>[]): DataFrame<T> { return this.unique(...fieldArg); } /** * Like unique but will allow passing serialization options */ private _unique( fields: Iterable<keyof T>, serializeOptions?: SerializeOptions ): DataFrame<T> { const buckets = new Set<string>(); const keyAggs = new Map<keyof T, KeyAggFn>(); for (const name of fields) { const column = this.getColumnOrThrow(name); if (column) { keyAggs.set(column.name, makeUniqueKeyAgg( column.vector, serializeOptions )); } } const builders = getBuildersForConfig<T>(this.config, this.size); const rowBuilder = makeUniqueRowBuilder( builders, buckets, (name, i) => { if (!serializeOptions) { return this.getColumnOrThrow(name).vector.get(i); } return this.getColumnOrThrow(name).vector.get( i, true, serializeOptions ); } ); for (let i = 0; i < this.size; i++) { const res = makeKeyForRow(keyAggs, i); if (res && !buckets.has(res.key)) { rowBuilder(res.row, res.key, i); } } return this._forkWithBuilders(builders, buckets.size); } /** * Create a new data frame from the builders */ private _forkWithBuilders(builders: Iterable<[ name: keyof T, builder: Builder<any> ]>, limit?: number): DataFrame<T> { return this.fork([...builders].map(([name, builder]: [keyof T, Builder<any>]) => ( this.getColumnOrThrow(name).fork( limit != null ? builder.resize(limit).toVector() : builder.toVector() ) ))); } /** * Reduce amount of noise in a DataFrame by * removing the amount of duplicates, including * duplicate objects in array values */ compact(): DataFrame<T> { const serializeOptions: SerializeOptions = { skipDuplicateObjects: true, skipEmptyObjects: true, skipNilValues: true, skipNilObjectValues: true, }; return this._unique(this.fields, serializeOptions); } /** * Assign new columns to a new DataFrame. If given a column already exists, * the column will replace the existing one. */ assign<R extends Record<string, unknown> = Record<string, any>>( columns: readonly Column<any>[] ): DataFrame<T & R> { const newColumns = columns.filter((col) => { if (this.getColumn(col.name)) return false; return true; }); return this.fork<T & R>( this.columns.map((col) => { const replaceCol = columns.find((c) => c.name === col.name); if (replaceCol) return replaceCol; return col; }).concat(newColumns) as Column<any>[], ); } /** * Concat rows, or columns, to the end of the existing Columns */ concat(arg: ( Partial<T>[]|Column<any, keyof T>[] )|( readonly Partial<T>[]|readonly Column<any, keyof T>[] )): DataFrame<T> { if (!arg?.length) return this; const isColumns = arg[0] instanceof Column; let len: number; if (isColumns) { len = getMaxColumnSize(arg as Column[]); } else { const valid = DataEntity.isDataEntity(arg[0]) || isPlainObject(arg[0]); if (!valid) { throw new Error( `Unexpected input given to DataFrame.concat, got ${getTypeOf(arg[0])}` ); } len = (arg as T[]).length; } if (!len) return this; const builders = new Map<keyof T, Builder>( columnsToBuilderEntries(this.columns, len + this.size) ); if (isColumns) { return this._forkWithBuilders( concatColumnsToColumns( builders, arg as Column<any, keyof T>[], this.size, ) ); } return this._forkWithBuilders( buildRecords<T>(builders, arg as T[]) ); } /** * Append one or more data frames to the end of this DataFrame. * Useful for incremental building an DataFrame since the cost of * this is relatively low. * * This is more efficient than using DataFrame.concat but comes with less * data type checking and may less safe so use with caution */ appendAll(frames: Iterable<DataFrame<T>>, limit?: number): DataFrame<T> { let { size } = this; for (const frame of frames) { if (limit != null && size >= limit) { break; } size += frame.size; } if (limit != null && size > limit) { size = limit; } // nothing changed if (size === this.size) return this; if (size < this.size || size === 0) { return this.limit(size); } let currIndex = this.size; const columns = this.columns.slice(); const fields = this.fields.slice(); function addMissing(frame: DataFrame<T>) { const missing = difference(fields, frame.fields); for (const field of missing) { const colIndex = columns.findIndex((c) => c.name === field)!; const existingColumn = columns[colIndex]; // ensure that we create a vector with correct // starting length const vector = existingColumn.vector.append( [new ReadableData(new WritableData(currIndex))] ); columns[colIndex] = existingColumn.fork(vector); } } /** * @returns the column index */ function appendNewColumn(column: Column<any, keyof T>): number { // ensure that we create a vector with correct // starting length const backfillVector = column.vector.fork( [new ReadableData(new WritableData(currIndex))] ); const newColumn = column.fork(backfillVector); fields.push(newColumn.name); // subtract one from the new length return (columns.push(newColumn) - 1); } for (const frame of frames) { const remaining = size - currIndex; // no need to process more frames if (remaining <= 0) break; addMissing(frame); for (const column of frame.columns) { let colIndex = columns.findIndex((c) => c.name === column.name); if (colIndex === -1) { colIndex = appendNewColumn(column); } let { vector } = column; if (remaining < vector.size) { vector = vector.slice(0, remaining); } const existingColumn = columns[colIndex]; columns[colIndex] = existingColumn.fork( existingColumn.vector.append(vector.data) ); } currIndex += frame.size; } return this.fork(columns); } /** * Rename an existing column */ rename<K extends keyof T, R extends string>( name: K, renameTo: R, ): DataFrame<Omit<T, K> & Record<R, T[K]>> { return this.fork(this.columns.map((col): Column<any, any> => { if (col.name !== name) return col; return col.rename(renameTo); })); } /** * Rename the data frame */ renameDataFrame( renameTo: string, ): DataFrame<T> { const newFrame = this.fork(this.columns); newFrame.name = renameTo; return newFrame; } /** * Merge two or more columns into a Tuple */ createTupleFrom<R extends string, V = [...unknown[]]>( fields: readonly (keyof T)[], as: R ): DataFrame<T & Record<R, V>> { if (!fields.length) { throw new TSError('Tuples require at least one field', { statusCode: 400 }); } const columns = fields.map((field) => this.getColumnOrThrow(field)); const childConfig: DataTypeFields = Object.create(null); columns.forEach((col, index) => { childConfig[index] = col.config; }); const config: DataTypeFieldConfig = Object.freeze({ type: FieldType.Tuple }); const builder = Builder.make<V>(new WritableData(this.size), { childConfig, config, name: as as string }); for (let index = 0; index < this.size; index++) { builder.set(index, columns.map((col) => col.vector.get(index, false))); } const column = new Column(builder.toVector(), { name: as, version: columns[0].version, }); return this.assign([column]); } /** * Get a column by name */ getColumn<P extends keyof T>(field: P): Column<T[P], P>|undefined { if (this._fieldToColumnIndexCache?.has(field)) { return this.getColumnAt<P>(this._fieldToColumnIndexCache.get(field)!); } const index = this.columns.findIndex((col) => col.name === field); if (!this._fieldToColumnIndexCache) { this._fieldToColumnIndexCache = new Map([[field, index]]); } else { this._fieldToColumnIndexCache.set(field, index); } return this.getColumnAt<P>(index); } /** * Get a column by name or throw if not found */ getColumnOrThrow<P extends keyof T>(field: P): Column<T[P], P> { const column = this.getColumn(field); if (!column) { throw new Error(`Unknown column ${field} in${ this.name ? ` ${this.name}` : '' } ${this.constructor.name}`); } return column; } /** * Get a column by index */ getColumnAt<P extends keyof T>(index: number): Column<T[P], P>|undefined { return this.columns[index] as Column<any, P>|undefined; } /** * Get a row by index, if the row has only null values, returns undefined */ getRow( index: number, json = false, options?: SerializeOptions, ): T|undefined { if (index > (this.size - 1)) return; const nilValue: any = options?.useNullForUndefined ? null : undefined; const row: Partial<T> = Object.create(null); let numKeys = 0; for (const col of this.columns) { const field = col.name as keyof T; const val = col.vector.get( index, json, options ) as Maybe<T[keyof T]>; if (val != null) { numKeys++; row[field] = val; } else if (nilValue === null) { row[field] = nilValue; } } if (options?.skipEmptyObjects && !numKeys) { return nilValue; } return row as T; } /** * Returns a DataFrame with a limited number of rows * * A negative value will select from the ending indices */ limit(num: number): DataFrame<T> { let start: number|undefined; let end: number|undefined; if (num < 0) { start = num; } else { end = num; } if (start == null && end != null && end > this.size) { return this; } return this.slice(start, end); } /** * Returns a DataFrame with a a specific set of rows */ slice(start?: number, end?: number): DataFrame<T> { if (start == null && end == null) return this.fork(this.columns); if (start === 0 && end === this.size) return this.fork(this.columns); return this.fork(this.columns.map( (col) => col.fork(col.vector.slice(start, end)) )); } /** * Convert the DataFrame an array of objects (the output is JSON compatible) */ toJSON(options?: SerializeOptions): T[] { return Array.from(this.rows(true, options)); } /** * Convert the DataFrame an array of objects (the output may not be JSON compatible) */ toArray(): T[] { return Array.from(this.rows(false)); } /** * Converts the DataFrame into an optimized serialized format, * including the metadata. This returns an iterator and requires * external code to join yield chunks with a new line. * * There is 1GB limit per column using this method */ * serializeIterator(): Iterable<string> { const dataFrameConfig: DataFrameHeaderConfig = { v: 1, name: this.name, size: this.size, metadata: convertMetadataToJSON(this.metadata), config: this.config }; yield JSON.stringify(dataFrameConfig); for (const column of this.columns) { yield column.serialize(); } } /** * Converts the DataFrame into an optimized serialized format, * including the metadata. This returns a string that includes * the data frame header and all of columns joined with a new line. * * There is 1GB limit for the whole data frame using this method, * to achieve a 1GB limit per column, use {@see serializeIterator} */ serialize(): string { return Array.from(this.serializeIterator()).join('\n'); } } /** * DataFrame options */ export interface DataFrameOptions { name?: string; metadata?: Record<string, any>; } export type FilterByFields<T> = Partial<{ [P in keyof T]: (value: Maybe<T[P]>) => boolean }>; export type FilterByFn<T> = (row: T, index: number) => boolean; export type FilterByRowsFn = ( index: number ) => boolean;
the_stack
import { MEDIA_QUERIES, SPACING_MAP, SPACING_MAP_INDEX, SPACING_POINTS, WIDTHS } from '@govuk-react/constants'; import * as spacing from '.'; describe('spacing lib', () => { describe('simple', () => { it('returns spacing values from the spacing scale', () => { Object.keys(SPACING_POINTS).forEach((key) => { expect(spacing.simple(Number(key))).toEqual(SPACING_POINTS[key]); }); }); it('returns negative spacing values from the spacing scale', () => { Object.keys(SPACING_POINTS).forEach((key) => { // skip zero, as -0 !== 0 in JS if (`${key}` !== '0') { expect(spacing.simple(-key)).toEqual(-SPACING_POINTS[key]); } }); }); it('throws when not given a size', () => { expect(() => spacing.simple(undefined)).toThrow(); }); it('throws when given a size not in the spacing scale', () => { expect(() => spacing.simple(99999)).toThrow(); }); }); describe('responsive', () => { it('returns spacing styles for given sizes on the spacing scale', () => { SPACING_MAP_INDEX.forEach((size) => { const style = spacing.responsive({ size, property: 'test' }); expect(style).toEqual(expect.objectContaining({ test: SPACING_MAP[size].mobile })); expect(style[MEDIA_QUERIES.TABLET]).toEqual(expect.objectContaining({ test: SPACING_MAP[size].tablet })); }); }); it('returns negative spacing styles for given sizes on the spacing scale', () => { SPACING_MAP_INDEX.forEach((size) => { // skip zero, as -0 !== 0 in JS if (size !== 0) { const style = spacing.responsive({ size: -size, property: 'test' }); expect(style).toEqual(expect.objectContaining({ test: -SPACING_MAP[size].mobile })); expect(style[MEDIA_QUERIES.TABLET]).toEqual(expect.objectContaining({ test: -SPACING_MAP[size].tablet })); } }); }); it('throws when not given a size', () => { expect(() => spacing.responsive(undefined)).toThrow(); }); it('throws when not given a property', () => { expect(() => spacing.responsive({ size: 0, property: undefined })).toThrow(); }); it('throws when given a size not in the spacing scale', () => { expect(() => spacing.responsive({ size: 99999, property: undefined })).toThrow(); }); it('returns spacing style for a given direction', () => { expect(spacing.responsive({ size: 0, property: 'test', direction: 'east' })).toEqual( expect.objectContaining({ 'test-east': SPACING_MAP[0].mobile }) ); }); it('returns spacing style for a given array of direction', () => { const style = spacing.responsive({ size: 0, property: 'test', direction: ['east', 'west'], }); expect(style).toEqual( expect.objectContaining({ 'test-east': SPACING_MAP[0].mobile, 'test-west': SPACING_MAP[0].mobile, }) ); expect(style[MEDIA_QUERIES.TABLET]).toEqual( expect.objectContaining({ 'test-east': SPACING_MAP[0].tablet, 'test-west': SPACING_MAP[0].tablet, }) ); }); it('treats all direction as no direction', () => { expect(spacing.responsive({ size: 0, property: 'test', direction: 'all' })).toEqual( expect.objectContaining({ test: SPACING_MAP[0].mobile }) ); }); it('treats all direction in a direction array as no direction', () => { const style = spacing.responsive({ size: 0, property: 'test', direction: ['all', 'west'], }); expect(style).toEqual( expect.objectContaining({ test: SPACING_MAP[0].mobile, 'test-west': SPACING_MAP[0].mobile, }) ); expect(style[MEDIA_QUERIES.TABLET]).toEqual( expect.objectContaining({ test: SPACING_MAP[0].tablet, 'test-west': SPACING_MAP[0].tablet, }) ); }); it('adjusts a spacing by the adjustment amount', () => { expect(spacing.responsive({ size: 0, property: 'test', adjustment: 7 })).toEqual( expect.objectContaining({ test: SPACING_MAP[0].mobile + 7 }) ); }); }); describe('responsiveMargin', () => { it('returns margin styles for given sizes on the spacing scale', () => { SPACING_MAP_INDEX.forEach((size) => { expect(spacing.responsiveMargin({ size })).toEqual(spacing.responsive({ size, property: 'margin' })); }); }); it('returns margin styles for given sizes on the spacing scale using simple numeric value', () => { SPACING_MAP_INDEX.forEach((size) => { expect(spacing.responsiveMargin(size)).toEqual(spacing.responsive({ size, property: 'margin' })); }); }); }); describe('responsivePadding', () => { it('returns padding styles for given sizes on the spacing scale', () => { SPACING_MAP_INDEX.forEach((size) => { expect(spacing.responsivePadding({ size })).toEqual(spacing.responsive({ size, property: 'padding' })); }); }); it('returns padding styles for given sizes on the spacing scale using simple numeric value', () => { SPACING_MAP_INDEX.forEach((size) => { expect(spacing.responsivePadding(size)).toEqual(spacing.responsive({ size, property: 'padding' })); }); }); }); describe('withWhiteSpace', () => { it('generates an executable white-space styling function with no config', () => { const whiteSpaceFunc = spacing.withWhiteSpace(); expect(() => whiteSpaceFunc()).not.toThrow(); }); describe('marginBottom/mb config and props', () => { it('works with marginBottom config', () => { const whiteSpaceFunc = spacing.withWhiteSpace({ marginBottom: 2 }); expect(whiteSpaceFunc()).toEqual( expect.arrayContaining([expect.objectContaining({ 'margin-bottom': SPACING_MAP[2].mobile })]) ); }); it('when marginBottom config set, mb prop changes marginBottom', () => { const whiteSpaceFunc = spacing.withWhiteSpace({ marginBottom: 2 }); expect(whiteSpaceFunc({ mb: 4 })).toEqual( expect.arrayContaining([expect.objectContaining({ 'margin-bottom': SPACING_MAP[4].mobile })]) ); }); it('when no marginBottom config set, mb prop changes marginBottom', () => { const whiteSpaceFunc = spacing.withWhiteSpace(); expect(whiteSpaceFunc({ mb: 4 })).toEqual( expect.arrayContaining([expect.objectContaining({ 'margin-bottom': SPACING_MAP[4].mobile })]) ); }); }); describe('margin config/props', () => { it('works with simple margin config value', () => { const whiteSpaceFunc = spacing.withWhiteSpace({ margin: 4 }); expect(whiteSpaceFunc()).toEqual( expect.arrayContaining([expect.objectContaining({ margin: SPACING_MAP[4].mobile })]) ); }); it('accepts a margin prop to override config', () => { const whiteSpaceFunc = spacing.withWhiteSpace({ margin: 1 }); expect(whiteSpaceFunc({ margin: 4 })).toEqual( expect.arrayContaining([expect.objectContaining({ margin: SPACING_MAP[4].mobile })]) ); }); it('accepts an array of margins', () => { const whiteSpaceFunc = spacing.withWhiteSpace({ margin: [1, { direction: 'top', size: 3 }], }); // styles need to be flattened for checking const result = [].concat(...whiteSpaceFunc()); expect(result).toEqual(expect.arrayContaining([expect.objectContaining({ margin: SPACING_MAP[1].mobile })])); expect(result).toEqual( expect.arrayContaining([expect.objectContaining({ 'margin-top': SPACING_MAP[3].mobile })]) ); }); }); describe('padding config/props', () => { it('works with simple padding config value', () => { const whiteSpaceFunc = spacing.withWhiteSpace({ padding: 4 }); expect(whiteSpaceFunc()).toEqual( expect.arrayContaining([expect.objectContaining({ padding: SPACING_MAP[4].mobile })]) ); }); it('accepts a padding prop to override config', () => { const whiteSpaceFunc = spacing.withWhiteSpace({ padding: 1 }); expect(whiteSpaceFunc({ padding: 4 })).toEqual( expect.arrayContaining([expect.objectContaining({ padding: SPACING_MAP[4].mobile })]) ); }); it('accepts an array of paddings', () => { const whiteSpaceFunc = spacing.withWhiteSpace({ padding: [1, { direction: 'top', size: 3 }], }); // styles need to be flattened for checking const result = [].concat(...whiteSpaceFunc()); expect(result).toEqual(expect.arrayContaining([expect.objectContaining({ padding: SPACING_MAP[1].mobile })])); expect(result).toEqual( expect.arrayContaining([expect.objectContaining({ 'padding-top': SPACING_MAP[3].mobile })]) ); }); }); }); describe('withWidth', () => { it('generates an executable styling function with no config', () => { const widthFunc = spacing.withWidth(); expect(() => widthFunc()).not.toThrow(); }); it('creates no style when config/prop not provided', () => { const widthFunc = spacing.withWidth(); expect(widthFunc()).toBeUndefined(); }); it('accepts a width config value of a size string', () => { Object.entries(WIDTHS).forEach(([width, value]) => { const widthFunc = spacing.withWidth({ width }); const widthStyle = widthFunc(); expect(widthStyle).toEqual( expect.objectContaining({ width: '100%', [MEDIA_QUERIES.TABLET]: { width: value }, }) ); }); }); it('accepts a setWidth prop', () => { const widthFunc = spacing.withWidth(); ['95%', '200px'].forEach((setWidth) => { const widthStyle = widthFunc({ setWidth }); expect(widthStyle).toEqual( expect.objectContaining({ width: '100%', [MEDIA_QUERIES.TABLET]: { width: setWidth }, }) ); }); Object.entries(WIDTHS).forEach(([setWidth, value]) => { const widthStyle = widthFunc({ setWidth }); expect(widthStyle).toEqual( expect.objectContaining({ width: '100%', [MEDIA_QUERIES.TABLET]: { width: value }, }) ); }); }); it('accepts a setWidth prop to override a width config', () => { const widthFunc = spacing.withWidth({ width: Object.keys(WIDTHS)[0] }); expect(widthFunc()).toEqual( expect.objectContaining({ width: '100%', [MEDIA_QUERIES.TABLET]: { width: Object.values(WIDTHS)[0] }, }) ); ['95%', '200px'].forEach((setWidth) => { const widthStyle = widthFunc({ setWidth }); expect(widthStyle).toEqual( expect.objectContaining({ width: '100%', [MEDIA_QUERIES.TABLET]: { width: setWidth }, }) ); }); Object.entries(WIDTHS).forEach(([setWidth, value]) => { const widthStyle = widthFunc({ setWidth }); expect(widthStyle).toEqual( expect.objectContaining({ width: '100%', [MEDIA_QUERIES.TABLET]: { width: value }, }) ); }); }); it('accepts a noDefault config which removes default 100% width', () => { const widthFunc = spacing.withWidth({ noDefault: true }); ['95%', '200px'].forEach((setWidth) => { const widthStyle = widthFunc({ setWidth }); expect(widthStyle).not.toEqual( expect.objectContaining({ width: '100%', }) ); }); Object.values(WIDTHS).forEach((setWidth) => { const widthStyle = widthFunc({ setWidth }); expect(widthStyle).not.toEqual( expect.objectContaining({ width: '100%', }) ); }); }); }); });
the_stack
import * as chai from 'chai'; import * as chaiAsPromied from 'chai-as-promised'; import { ChaincodeStub } from 'fabric-shim'; import * as sinon from 'sinon'; import * as sinonChai from 'sinon-chai'; import { VehicleManufactureNetContext } from '../utils/context'; import { HistoricState, State } from './state'; import { StateList } from './statelist'; chai.should(); chai.use(sinonChai); chai.use(chaiAsPromied); // tslint:disable:max-classes-per-file describe ('#StateList', () => { let sandbox: sinon.SinonSandbox; let mockContext: sinon.SinonStubbedInstance<VehicleManufactureNetContext>; let mockState: sinon.SinonStubbedInstance<State>; let stateList: StateList<any>; let splitKeyStub: sinon.SinonStub; beforeEach(() => { sandbox = sinon.createSandbox(); mockContext = sinon.createStubInstance(VehicleManufactureNetContext); mockContext.stub = sinon.createStubInstance(ChaincodeStub); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey.returns('some key'); mockState = sinon.createStubInstance(State); mockState.getSplitKey.returns(['some', 'split', 'key']); mockState.getKey.returns('state key'); splitKeyStub = sandbox.stub(State, 'splitKey').returns(['some', 'other', 'split', 'key']); stateList = new StateList(mockContext, 'some list name'); }); afterEach(() => { sandbox.restore(); }); describe ('constructor', () => { it ('should assign values', () => { (stateList as any).ctx.should.deep.equal(mockContext); stateList.name.should.deep.equal('some list name'); stateList.supportedClasses.should.deep.equal(new Map()); }); }); describe ('add', () => { beforeEach(() => { mockState.serialize.returns('some serialized value'); }); it ('should error if already key exists', async () => { const existsStub = sandbox.stub(stateList, 'exists').resolves(true); await stateList.add(mockState).should.be.rejectedWith( 'Cannot add state. State already exists for key state key', ); existsStub.should.have.been.calledOnceWithExactly('state key'); // tslint:disable-next-line:no-unused-expression mockState.getSplitKey.should.not.have.been.called; // tslint:disable-next-line:no-unused-expression (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey .should.not.have.been.called; // tslint:disable-next-line:no-unused-expression mockState.serialize.should.not.have.been.called; // tslint:disable-next-line:no-unused-expression (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).putState.should.not.have.been.called; }); it ('should put to the world state', async () => { const existsStub = sandbox.stub(stateList, 'exists').resolves(false); await stateList.add(mockState); mockState.getSplitKey.should.have.been.calledOnceWithExactly(); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey .should.have.been.calledOnceWithExactly('some list name', ['some', 'split', 'key']); mockState.serialize.should.have.been.calledOnceWithExactly(); existsStub.should.have.been.calledOnceWithExactly('state key'); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).putState .should.have.been.calledOnceWithExactly('some key', 'some serialized value'); }); }); describe ('get', () => { let deserializeStub: sinon.SinonStub; beforeEach(() => { deserializeStub = sandbox.stub(State, 'deserialize').returns({some: 'object'} as any); }); it ('should error when no state exists', async () => { (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).getState.resolves(Buffer.from('')); await stateList.get('my key').should.be.rejectedWith( 'Cannot get state. No state exists for key my key', ); splitKeyStub.should.have.been.calledOnceWithExactly('my key'); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey .should.have.been.calledOnceWithExactly( 'some list name', ['some', 'other', 'split', 'key'], ); // tslint:disable-next-line:no-unused-expression deserializeStub.should.not.have.been.called; }); it ('should return the deserialized state', async () => { const expectedState = Buffer.from('some data'); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).getState.resolves(expectedState); const expectedSupportedClasses = new Map([[1, 2], [2, 3], [4, 5]]); (stateList as any).supportedClasses = expectedSupportedClasses; (await stateList.get('my key')).should.deep.equal({some: 'object'}); splitKeyStub.should.have.been.calledOnceWithExactly('my key'); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey .should.have.been.calledOnceWithExactly('some list name', ['some', 'other', 'split', 'key']); // tslint:disable-next-line:no-unused-expression deserializeStub.should.have.been.calledOnceWithExactly(expectedState, expectedSupportedClasses); }); }); describe ('getHistory', () => { it ('should return the history of a state', async () => { const values = ['some', 'iterable', 'values']; const deserializeStub = sandbox.stub(State, 'deserialize').callsFake((value) => { return value as any; }); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).getHistoryForKey .resolves(getIterable(values)); const expectedSupportedClasses = new Map([[1, 2], [2, 3], [4, 5]]); (stateList as any).supportedClasses = expectedSupportedClasses; const history = await stateList.getHistory('my key'); splitKeyStub.should.have.been.calledOnceWithExactly('my key'); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey .should.have.been.calledOnceWithExactly('some list name', ['some', 'other', 'split', 'key']); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).getHistoryForKey .should.have.been.calledOnceWithExactly('some key'); deserializeStub.callCount.should.deep.equal(values.length); deserializeStub.getCall(0).args.should.deep.equal([values[0], expectedSupportedClasses]); deserializeStub.getCall(1).args.should.deep.equal([values[1], expectedSupportedClasses]); deserializeStub.getCall(2).args.should.deep.equal([values[2], expectedSupportedClasses]); history.should.deep.equal([ new HistoricState(0, 'TX -> 0', values[0] as any), new HistoricState(1, 'TX -> 1', values[1] as any), new HistoricState(2, 'TX -> 2', values[2] as any), ]); }); }); describe ('getAll', () => { it ('should run an empty query', async () => { const queryStub = sandbox.stub(stateList, 'query').returns('some query result' as any); (await stateList.getAll()).should.deep.equal('some query result'); queryStub.should.have.been.calledOnceWithExactly({}); }); }); describe ('count', () => { it ('should return the number of results in state', async () => { const values = ['some', 'iterable', 'values']; (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).getStateByPartialCompositeKey .resolves(getIterable(values)); (await stateList.count()).should.deep.equal(values.length); }); }); describe ('update', () => { beforeEach(() => { mockState.serialize.returns('some serialized value'); }); it ('should throw an error if no state exists', async () => { const existsStub = sandbox.stub(stateList, 'exists').resolves(false); await stateList.update(mockState).should.be.rejectedWith( 'Cannot update state. No state exists for key state key', ); existsStub.should.have.been.calledOnceWithExactly('state key'); // tslint:disable-next-line:no-unused-expression mockState.getSplitKey.should.not.have.been.called; // tslint:disable-next-line:no-unused-expression (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey .should.not.have.been.called; // tslint:disable-next-line:no-unused-expression mockState.serialize.should.not.have.been.called; // tslint:disable-next-line:no-unused-expression (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).putState.should.not.have.been.called; }); it ('should put to the world state', async () => { const existsStub = sandbox.stub(stateList, 'exists').resolves(true); await stateList.update(mockState); mockState.getSplitKey.should.have.been.calledOnceWithExactly(); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey .should.have.been.calledOnceWithExactly('some list name', ['some', 'split', 'key']); mockState.serialize.should.have.been.calledOnceWithExactly(); existsStub.should.have.been.calledOnceWithExactly('state key'); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).putState .should.have.been.calledOnceWithExactly('some key', 'some serialized value'); }); it ('should put to the world state by force', async () => { const existsStub = sandbox.stub(stateList, 'exists').resolves(false); await stateList.update(mockState, true); mockState.getSplitKey.should.have.been.calledOnceWithExactly(); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey .should.have.been.calledOnceWithExactly('some list name', ['some', 'split', 'key']); mockState.serialize.should.have.been.calledOnceWithExactly(); existsStub.should.have.been.calledOnceWithExactly('state key'); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).putState .should.have.been.calledOnceWithExactly('some key', 'some serialized value'); }); }); describe ('delete', () => { it ('should delete the state at key', async () => { await stateList.delete('my key'); splitKeyStub.should.have.been.calledOnceWithExactly('my key'); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).createCompositeKey .should.have.been.calledOnceWithExactly( 'some list name', ['some', 'other', 'split', 'key'], ); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).deleteState .should.have.been.calledOnceWithExactly('some key'); }); }); describe ('exists', () => { it ('should return false when get fails', async () => { const getStub = sandbox.stub(stateList, 'get').rejects('some error'); (await stateList.exists('my key')).should.deep.equal(false); getStub.should.have.been.calledOnceWithExactly('my key'); }); it ('should return true when get fails', async () => { const getStub = sandbox.stub(stateList, 'get').resolves(); (await stateList.exists('my key')).should.deep.equal(true); getStub.should.have.been.calledOnceWithExactly('my key'); }); }); describe ('query', () => { let deserializeStub: sinon.SinonStub; const values = ['some', 'iterable', 'values']; const expectedSupportedClasses = new Map([[1, 2], [2, 3], [4, 5]]); beforeEach(() => { deserializeStub = sandbox.stub(State, 'deserialize').callsFake((value) => { return value as any; }); (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).getQueryResult .resolves(getIterable(values)); (stateList as any).supportedClasses = expectedSupportedClasses; }); it ('should query based on passed query', async () => { const mockQuery = { selector: { some: 'selector', }, }; const queryResult = await stateList.query(mockQuery); const expectedQuery = JSON.parse(JSON.stringify(mockQuery)); expectedQuery.selector._id = { $regex: `.*some list name.*`, }; (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).getQueryResult .should.have.been.calledOnceWithExactly(JSON.stringify(expectedQuery)); deserializeStub.callCount.should.deep.equal(3); deserializeStub.getCall(0).args.should.deep.equal([values[0], expectedSupportedClasses]); deserializeStub.getCall(1).args.should.deep.equal([values[1], expectedSupportedClasses]); deserializeStub.getCall(2).args.should.deep.equal([values[2], expectedSupportedClasses]); queryResult.should.deep.equal(values); }); it ('should query based on passed when selector not passed', async () => { const queryResult = await stateList.query({}); const expectedQuery = { selector: { _id: { $regex: `.*some list name.*`, }, }, }; (mockContext.stub as sinon.SinonStubbedInstance<ChaincodeStub>).getQueryResult .should.have.been.calledOnceWithExactly(JSON.stringify(expectedQuery)); deserializeStub.callCount.should.deep.equal(3); deserializeStub.getCall(0).args.should.deep.equal([values[0], expectedSupportedClasses]); deserializeStub.getCall(1).args.should.deep.equal([values[1], expectedSupportedClasses]); deserializeStub.getCall(2).args.should.deep.equal([values[2], expectedSupportedClasses]); queryResult.should.deep.equal(values); }); }); describe ('use', () => { class BadClass {} class GoodClass extends State { public static getClass() { return 'some class'; } } class AnotherGoodClass extends State { public static getClass() { return 'some other class'; } } it ('should error when passed value is not of type state', () => { (() => { stateList.use(GoodClass as any, BadClass as any); }).should.throw('Cannot use BadClass as type State'); }); it ('should set supported classes', () => { stateList.use(GoodClass as any, AnotherGoodClass as any); stateList.supportedClasses.should.deep.equal( new Map([['some class', GoodClass], ['some other class', AnotherGoodClass]], )); }); }); }); function getIterable(values: any[]) { let iterationCount = 0; return { next: () => { let result; if (iterationCount < values.length) { const curr = iterationCount; result = { done: false, value: { getTimestamp: () => { return { getSeconds: () => { return { toInt: () => curr, }; }, }; }, getTxId: () => 'TX -> ' + curr, getValue: () => { return { toBuffer: () => values[curr], }; }, }, }; iterationCount++; return result; } return { value: null, done: true }; }, }; }
the_stack
import {assert} from 'chai'; import * as fileIO from '../file-io'; let readFile = fileIO.readFile; import * as logger from '../logger'; import * as ast from '../ast'; import * as bolt from '../bolt'; import * as helper from './test-helper'; import {samples} from './sample-files'; let parser = require('../rules-parser'); let parse = parser.parse; // TODO: Test duplicated function, and schema definitions. suite("Rules Parser Tests", function() { test("Empty input", function() { var result = parse(""); assert.ok(result instanceof ast.Symbols); }); suite("Function Samples", function() { var tests: helper.ObjectSpec[] = [ { data: "function f() { return true; }", expect: { f: { params: [], body: ast.boolean(true) } } }, { data: "function longName() { return false; }", expect: { longName: { params: [], body: ast.boolean(false) } } }, { data: "function f(){return true;} function g(){return false;}", expect: { f: { params: [], body: ast.boolean(true) }, g: { params: [], body: ast.boolean(false) } } } ]; helper.dataDrivenTest(tests, function(data, expect) { var result = parse(data); assert.deepEqual(result.functions, expect); }); }); suite("Literals", function() { var tests = [ [ "true", ast.boolean(true) ], [ "false", ast.boolean(false) ], [ "null", ast.nullType() ], [ "1", ast.number(1) ], [ "1.1", ast.number(1.1) ], [ "+3", ast.number(3) ], [ "-3", ast.number(-3) ], [ "0x2", ast.number(2) ], [ "[1, 2, 3]", ast.array([ast.number(1), ast.number(2), ast.number(3)]) ], [ "\"string\"", ast.string("string") ], [ "'string'", ast.string("string") ], [ "''", ast.string('') ], [ "/pattern/", ast.regexp("pattern") ], [ "/pattern/i", ast.regexp("pattern", "i") ], [ "/pat\\ntern/", ast.regexp("pat\\ntern") ], [ "/pat\\/tern/", ast.regexp("pat\\/tern") ], [ "/pat\\tern/", ast.regexp("pat\\tern") ], ]; helper.dataDrivenTest(tests, function(data, expect) { var result = parse("function f() { return " + data + ";}"); assert.deepEqual(result.functions.f.body, expect); }); }); suite("Expressions", function() { var tests = [ [ "a", ast.variable('a') ], [ "a.b", ast.reference(ast.variable('a'), ast.string('b')) ], [ "a['b']", ast.reference(ast.variable('a'), ast.string('b')) ], [ "a[b]", ast.reference(ast.variable('a'), ast.variable('b')) ], [ "a()", ast.call(ast.variable('a'), []) ], [ "a.b()", ast.call(ast.reference(ast.variable('a'), ast.string('b')), []) ], [ "a().b", ast.reference(ast.call(ast.variable('a'), []), ast.string('b')) ], [ "-a", ast.neg(ast.variable('a')) ], // TODO: This should be an error - looks like pre-decrement [ "--a", ast.neg(ast.neg(ast.variable('a'))) ], [ "+a", ast.variable('a') ], [ "!a", ast.not(ast.variable('a')) ], [ "2 * a", ast.mult(ast.number(2), ast.variable('a')) ], [ "2 / a", ast.div(ast.number(2), ast.variable('a')) ], [ "a % 2", ast.mod(ast.variable('a'), ast.number(2)) ], [ "1 + 1", ast.add(ast.number(1), ast.number(1)) ], [ "a - 1", ast.sub(ast.variable('a'), ast.number(1)) ], // Unary precedence [ "a - -b", ast.sub(ast.variable('a'), ast.neg(ast.variable('b'))) ], // Left associative [ "a + b + c", ast.add(ast.add(ast.variable('a'), ast.variable('b')), ast.variable('c')) ], // Multiplcation precedence [ "a + b * c", ast.add(ast.variable('a'), ast.mult(ast.variable('b'), ast.variable('c'))) ], [ "(a + b) * c", ast.mult(ast.add(ast.variable('a'), ast.variable('b')), ast.variable('c')) ], [ "a < 7", ast.lt(ast.variable('a'), ast.number(7)) ], [ "a > 7", ast.gt(ast.variable('a'), ast.number(7)) ], [ "a <= 7", ast.lte(ast.variable('a'), ast.number(7)) ], [ "a >= 7", ast.gte(ast.variable('a'), ast.number(7)) ], [ "a == 3", ast.eq(ast.variable('a'), ast.number(3)) ], [ "a != 0", ast.ne(ast.variable('a'), ast.number(0)) ], [ "a === 3", ast.eq(ast.variable('a'), ast.number(3)) ], [ "a !== 0", ast.ne(ast.variable('a'), ast.number(0)) ], [ "3 * a == b", ast.eq(ast.mult(ast.number(3), ast.variable('a')), ast.variable('b')) ], [ "a == 1 && b <= 2", ast.and(ast.eq(ast.variable('a'), ast.number(1)), ast.lte(ast.variable('b'), ast.number(2))) ], [ "a == 1 || b <= 2", ast.or(ast.eq(ast.variable('a'), ast.number(1)), ast.lte(ast.variable('b'), ast.number(2))) ], // Left associative (even though execution is short-circuited! [ "a && b && c", ast.and(ast.and(ast.variable('a'), ast.variable('b')), ast.variable('c')) ], [ "a || b || c", ast.or(ast.or(ast.variable('a'), ast.variable('b')), ast.variable('c')) ], // && over || precendence [ "a && b || c && d", ast.or(ast.and(ast.variable('a'), ast.variable('b')), ast.and(ast.variable('c'), ast.variable('d'))) ], [ "a ? b : c", ast.ternary(ast.variable('a'), ast.variable('b'), ast.variable('c')) ], [ "a || b ? c : d", ast.ternary(ast.or(ast.variable('a'), ast.variable('b')), ast.variable('c'), ast.variable('d')) ], ]; helper.dataDrivenTest(tests, function(data, expect) { var result = parse("function f() { return " + data + ";}"); assert.deepEqual(result.functions.f.body, expect); }); }); suite("Whitespace", function() { var fn = "function f() { return true; }"; var fnAST: ast.Method = { params: [], body: ast.boolean(true) }; var tests = [ " " + fn, fn + " ", " " + fn + " ", "\t" + fn, "\n" + fn, "\r\n" + fn, fn + "\n", fn + "\r\n", " \t" + fn + " \r\n" ]; helper.dataDrivenTest(tests, function(data) { assert.deepEqual(parse(data).functions.f, fnAST); }); }); suite("Comments", function() { var fn = "function f() { return true; }"; var fnAST: ast.Method = { params: [], body: ast.boolean(true) }; var tests = [ "//Single Line\n" + fn, fn + " // My rule", "// Line 1\n// Line 2\n" + fn, "/* inline */ " + fn, "/* pre */ " + fn + " /* post */" ]; helper.dataDrivenTest(tests, function(data, expect) { assert.deepEqual(parse(data).functions.f, fnAST); }); }); suite("Paths", function() { var tests: helper.ObjectSpec[] = [ { data: "path / {}", expect: [{ template: new ast.PathTemplate(), isType: ast.typeType('Any'), methods: {} }] }, { data: "path /x {}", expect: [{ template: new ast.PathTemplate(['x']), isType: ast.typeType('Any'), methods: {} }] }, { data: "path /p/{$q} { write() { return true; }}", expect: [{ isType: ast.typeType('Any'), template: new ast.PathTemplate(['p', '$q']), methods: {write: {params: [], body: ast.boolean(true)}}}] }, { data: "path /p/{q} { write() { return true; }}", expect: [{ isType: ast.typeType('Any'), template: new ast.PathTemplate(['p', new ast.PathPart('$q', 'q')]), methods: {write: {params: [], body: ast.boolean(true)}}}] }, { data: "path /x/y { read() { true } }", expect: [{ isType: ast.typeType('Any'), template: new ast.PathTemplate(['x', 'y']), methods: {read: {params: [], body: ast.boolean(true)}}}] }, { data: "path /x { read() { true } /y { write() { true } }}", expect: [{ isType: ast.typeType('Any'), template: new ast.PathTemplate(['x']), methods: {read: {params: [], body: ast.boolean(true)}}}, { isType: ast.typeType('Any'), template: new ast.PathTemplate(['x', 'y']), methods: {write: {params: [], body: ast.boolean(true)}}}] }, { data: "path /x { read() { true } /y { write() { true } path /{$id} { validate() { false } }}}", expect: [{ isType: ast.typeType('Any'), template: new ast.PathTemplate(['x']), methods: {read: {params: [], body: ast.boolean(true)}}}, { isType: ast.typeType('Any'), template: new ast.PathTemplate(['x', 'y']), methods: {write: {params: [], body: ast.boolean(true)}}}, { isType: ast.typeType('Any'), template: new ast.PathTemplate(['x', 'y', '$id']), methods: {validate: {params: [], body: ast.boolean(false)}}}, ] }, { data: "path /hyphen-key {}", expect: [ { template: new ast.PathTemplate(['hyphen-key']), isType: ast.typeType('Any'), methods: {} }] }, ]; helper.dataDrivenTest(tests, function(data, expect) { assert.deepEqual(sortPaths(parse(data).paths), sortPaths(expect)); }); }); suite("Schema", function() { var tests: helper.ObjectSpec[] = [ { data: "type Foo { a: Number }", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.typeType('Number')}, methods: {}, params: [], }}, { data: "type Foo { a: Number, b: String }", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.typeType('Number'), b: ast.typeType('String')}, methods: {}, params: [], }}, { data: "type Foo extends Bar {}", expect: { derivedFrom: ast.typeType('Bar'), properties: {}, methods: {}, params: [], }}, { data: "type Foo { a: Number validate() { return true; }}", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.typeType('Number')}, methods: {validate: {params: [], body: ast.boolean(true)}}, params: [], }}, { data: "type Foo { a: Number, validate() { return true; }}", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.typeType('Number')}, methods: {validate: {params: [], body: ast.boolean(true)}}, params: [], }}, { data: "type Foo { a: Number | String }", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.unionType([ast.typeType('Number'), ast.typeType('String')])}, methods: {}, params: [], }}, { data: "type Foo extends Number | String;", expect: { derivedFrom: ast.unionType([ast.typeType('Number'), ast.typeType('String')]), properties: {}, methods: {}, params: [], }}, { data: "type Foo { a: Map<String, Number> }", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.genericType('Map', [ast.typeType('String'), ast.typeType('Number')])}, methods: {}, params: [], }}, { data: "type Foo extends Map<String, Number>;", expect: { derivedFrom: ast.genericType('Map', [ast.typeType('String'), ast.typeType('Number')]), properties: {}, methods: {}, params: [], }}, // Alias for Map<String, Other> { data: "type Foo { a: Other[] }", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.genericType('Map', [ast.typeType('String'), ast.typeType('Other')])}, methods: {}, params: [], }}, { data: "type Foo { a: Multi<String, Number, Boolean> }", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.genericType('Multi', [ast.typeType('String'), ast.typeType('Number'), ast.typeType('Boolean')])}, methods: {}, params: [], }}, { data: "type Foo { a: Gen1<String> }", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.genericType('Gen1', [ast.typeType('String')])}, methods: {}, params: [], }}, { data: "type Foo<T> { a: T }", expect: { derivedFrom: ast.typeType('Object'), properties: {a: ast.typeType('T')}, methods: {}, params: ["T"], }}, { data: "type Foo { name: String, age: Number }", expect: { derivedFrom: ast.typeType('Object'), properties: {name: ast.typeType('String'), age: ast.typeType('Number')}, methods: {}, params: [], }}, { data: "type Foo { name: String; age: Number; }", expect: { derivedFrom: ast.typeType('Object'), properties: {name: ast.typeType('String'), age: ast.typeType('Number')}, methods: {}, params: [], }}, { data: "type Foo { 'hyphen-prop': String }", expect: { derivedFrom: ast.typeType('Object'), properties: {"hyphen-prop": ast.typeType('String')}, methods: {}, params: [], }}, ]; helper.dataDrivenTest(tests, function(data, expect) { var result = parse(data).schema.Foo; assert.deepEqual(result, expect); }); }); suite("Function variations", function() { var tests = [ "function f(x) { return x + 1; }", "function f(x) { return x + 1 }", "function f(x) { x + 1; }", "function f(x) { x + 1 }", ]; helper.dataDrivenTest(tests, function(data, expect) { var result = parse(data); assert.deepEqual(result.functions.f.body, ast.add(ast.variable('x'), ast.number(1))); }); }); suite("Method variations", function() { var tests = [ "validate() { return this; }", "validate() { return this }", "validate() { this; }", "validate() { this }", ]; helper.dataDrivenTest(tests, function(data, expect) { var result = parse("type T {" + data + "}"); assert.deepEqual(result.schema.T.methods.validate.body, ast.variable('this')); }); }); suite("Path variations", function() { var tests = [ "path /p/{c} {}", "/p/{c} {}", "/p/{c};", "path /p/{c} is String {}", "path /p/{c} is String;", "/p/{c} is String {}", "/p/{c} is String;", "/p/{c=*} is String;", "/p/{c = *} is String;", "/p/{c} { validate() { return true; } }", "/p/{c} { validate() { return true } }", "/p/{c} { validate() { true } }", "/p/{c} { validate() { true; } }", ]; helper.dataDrivenTest(tests, function(data, expect) { var result = parse(data); assert.deepEqual(result.paths[0].template, new ast.PathTemplate(['p', new ast.PathPart('$c', 'c')])); }); }); suite("Type variations", function() { var tests = [ "type T extends Any {}", "type T extends Any;", "type T {}", "type T;" ]; helper.dataDrivenTest(tests, function(data, expect) { var result = parse(data); assert.deepEqual(result.schema.T, { derivedFrom: ast.typeType('Any'), methods: {}, properties: {}, params: [], }); }); }); suite("Sample files", function() { helper.dataDrivenTest(samples, function(data) { var filename = 'samples/' + data + '.' + bolt.FILE_EXTENSION; return readFile(filename) .then(function(response) { var result = parse(response.content); assert.ok(result, response.url); return true; }); }); }); suite("Parser Errors", function() { var tests = [ { data: "path /x/y/ is String;", expect: /end in a slash/ }, { data: "path /x//y is String;", expect: /empty part/ }, // BUG: Following errors should expect /empty part/ - PEG parser error? { data: "path //x is String;", expect: /./ }, { data: "path // is String;", expect: /./ }, { data: "path /x { validate() { return this.test(/a/g); } }", expect: /unsupported regexp modifier/i }, { data: "path {}", expect: /missing path template/i }, { data: "path / }", expect: /missing body of path/i }, { data: "function foo { 7 }", expect: /missing parameters/i }, { data: "foo { 7 }", expect: /expected.*function/i }, { data: "foo(x)", expect: /missing.*body/i }, { data: "path /x { foo(x); }", expect: /invalid path or method/i }, { data: "foo(x) { x = 'a' }", expect: /equality/i }, { data: "type X { bad-prop: String; }", expect: /invalid property or method/i }, { data: "type { foo: String;}", expect: /missing type name/i }, ]; helper.dataDrivenTest(tests, function(data, expect) { try { parse(data); } catch (e) { assert.match(e.message, expect); return; } assert.fail(undefined, undefined, "No exception thrown."); }); }); suite("Syntax warnings.", function() { var tests = [ { data: "path /x { read() { true }; }", expect: /extra separator/i }, ]; helper.dataDrivenTest(tests, function(data, expect) { parse(data); assert.match(logger.getLastMessage(), expect); }); }); suite("Deprecation warnings.", function() { var tests = [ { data: "path /x/$y is String;", expect: /path segment is deprecated/ }, { data: "f(x) = x + 1;", expect: /fn\(x\) = exp; format is deprecated/ }, { data: "f(x) = x + 1", expect: /fn\(x\) = exp; format is deprecated/ }, ]; helper.dataDrivenTest(tests, function(data, expect) { parse(data); assert.match(logger.getLastMessage(), expect); }); }); }); function sortPaths(paths: ast.Path[]): ast.Path[] { function cmpStr(a: string, b: string): number { if (a < b) { return -1; } if (a > b) { return 1; } return 0; } paths.sort((a, b) => { return cmpStr(a.template.getLabels().join('~'), b.template.getLabels().join('~')); }); return paths; }
the_stack
import { APIEvent, Categories } from 'homebridge'; // enum import type { API, Characteristic, DynamicPlatformPlugin, Logging, PlatformAccessory, PlatformConfig, Service, WithUUID, } from 'homebridge'; import chalk from 'chalk'; import { satisfies } from 'semver'; import { Client } from 'tplink-smarthome-api'; import type { Sysinfo } from 'tplink-smarthome-api'; import { parseConfig } from './config'; import type { TplinkSmarthomeConfig } from './config'; import Characteristics from './characteristics'; import { PLATFORM_NAME, PLUGIN_NAME } from './settings'; import TplinkAccessory from './tplink-accessory'; import { lookup, lookupCharacteristicNameByUUID, isObjectLike } from './utils'; import type { TplinkDevice } from './utils'; // @ts-ignore: okay for reading json // eslint-disable-next-line @typescript-eslint/no-var-requires const packageConfig = require('../package.json'); export default class TplinkSmarthomePlatform implements DynamicPlatformPlugin { public readonly Service = this.api.hap.Service; public readonly Characteristic = this.api.hap.Characteristic; public customCharacteristics: { [key: string]: WithUUID<new () => Characteristic>; }; public config: TplinkSmarthomeConfig; private readonly homebridgeAccessories: Map< string, PlatformAccessory > = new Map(); private readonly deviceAccessories: Map<string, TplinkAccessory> = new Map(); constructor( public readonly log: Logging, config: PlatformConfig, public readonly api: API ) { this.log.info( '%s v%s, node %s, homebridge v%s, api v%s', packageConfig.name, packageConfig.version, process.version, api.serverVersion, api.version ); if (!satisfies(process.version, packageConfig.engines.node)) { this.log.error( 'Error: not using minimum node version %s', packageConfig.engines.node ); } this.log.debug('config.json: %j', config); this.config = parseConfig(config); this.log.debug('config: %j', this.config); this.customCharacteristics = Characteristics(api.hap.Characteristic); const tplinkApiLogger: Logging = Object.assign(() => {}, this.log, { prefix: `${this.log.prefix || PLATFORM_NAME}.API`, }); const client = new Client({ logger: tplinkApiLogger, defaultSendOptions: this.config.defaultSendOptions, }); client.on('device-new', (device: TplinkDevice) => { this.log.info( `New Device Online: ${chalk.blue(`[${device.alias}]`)} %s [%s]`, device.deviceType, device.id, device.host, device.port ); this.foundDevice(device); }); client.on('device-online', (device: TplinkDevice) => { this.log.debug( `Device Online: ${chalk.blue(`[${device.alias}]`)} %s [%s]`, device.deviceType, device.id, device.host, device.port ); this.foundDevice(device); }); client.on('device-offline', (device: TplinkDevice) => { const deviceAccessory = this.deviceAccessories.get(device.id); if (deviceAccessory !== undefined) { this.log.debug( `Device Offline: ${chalk.blue(`[${device.alias}]`)} %s [%s]`, deviceAccessory.homebridgeAccessory.displayName, device.deviceType, device.id, device.host, device.port ); } }); this.api.on(APIEvent.DID_FINISH_LAUNCHING, () => { this.log.debug(APIEvent.DID_FINISH_LAUNCHING); client.startDiscovery({ ...this.config.discoveryOptions, filterCallback: (si: Sysinfo) => { return si.deviceId != null && si.deviceId.length > 0; }, }); const refreshEmeterForAccessories = async ( accessories: TplinkAccessory[] ) => { for (const acc of accessories) { const device = acc.tplinkDevice; if (device.deviceType === 'plug' && device.supportsEmeter) { this.log.debug( `getEmeterRealtime ${chalk.blue(`[${device.alias}]`)}` ); // eslint-disable-next-line no-await-in-loop await device.emeter.getRealtime().catch((reason) => { this.log.error('[%s] %s', device.alias, 'emeter.getRealtime()'); this.log.error(reason); }); } } }; const refreshEmeter = async () => { this.log.debug('refreshEmeter()'); try { const deviceAccessories = this.deviceAccessoriesByHost; const promises: Promise<unknown>[] = []; for (const accForHost of deviceAccessories.values()) { promises.push(refreshEmeterForAccessories(accForHost)); } await Promise.all(promises); } catch (err) { this.log.error('refreshEmeter()'); this.log.error(err); } finally { this.log.debug( 'Scheduling next run of refreshEmeter() in %d(ms)', this.config.discoveryOptions.discoveryInterval ); setTimeout(() => { refreshEmeter(); }, this.config.discoveryOptions.discoveryInterval); } }; refreshEmeter(); }); this.api.on('shutdown', () => { this.log.debug('shutdown'); client.stopDiscovery(); }); } /** * Return string representation of Service/Characteristic for logging * * @internal */ public lsc( serviceOrCharacteristic: Service | Characteristic | { UUID: string }, characteristic?: Characteristic | { UUID: string } ): string { let serviceName: string | undefined; let characteristicName: string | undefined; if (serviceOrCharacteristic instanceof this.api.hap.Service) { serviceName = this.getServiceName(serviceOrCharacteristic); } else if ( serviceOrCharacteristic instanceof this.api.hap.Characteristic || ('UUID' in serviceOrCharacteristic && typeof serviceOrCharacteristic.UUID === 'string') ) { characteristicName = this.getCharacteristicName(serviceOrCharacteristic); } if (characteristic instanceof this.api.hap.Characteristic) { characteristicName = this.getCharacteristicName(characteristic); } if (serviceName != null && characteristicName != null) { return `[${chalk.yellow(serviceName)}.${chalk.green( characteristicName )}]`; } if (serviceName !== undefined) return `[${chalk.yellow(serviceName)}]`; return `[${chalk.green(characteristicName)}]`; } private get deviceAccessoriesByHost(): Map<string, TplinkAccessory[]> { const byHost: Map<string, TplinkAccessory[]> = new Map(); for (const [, tpLinkAccessory] of this.deviceAccessories) { const { host } = tpLinkAccessory.tplinkDevice; const arr = byHost.get(host); if (arr != null) { arr.push(tpLinkAccessory); } else { byHost.set(host, [tpLinkAccessory]); } } return byHost; } private createTplinkAccessory( accessory: PlatformAccessory | undefined, tplinkDevice: TplinkDevice ): TplinkAccessory { // eslint-disable-next-line @typescript-eslint/no-shadow const { config, Service } = this; const [category, services] = ((): [ Categories, Array<WithUUID<typeof Service>> ] => { if (tplinkDevice.deviceType === 'bulb') { return [Categories.LIGHTBULB, [Service.Lightbulb]]; } // plug if ( config.switchModels && config.switchModels.findIndex((m) => tplinkDevice.model.includes(m)) !== -1 ) { return [Categories.SWITCH, [Service.Switch]]; } if (tplinkDevice.supportsDimmer) { return [Categories.LIGHTBULB, [Service.Lightbulb]]; } return [Categories.OUTLET, [Service.Outlet]]; })(); return new TplinkAccessory( this, this.config, accessory, tplinkDevice, category, services ); } getCategoryName(category: Categories): string | undefined { // @ts-ignore: this should work // eslint-disable-next-line deprecation/deprecation return this.api.hap.Accessory.Categories[category]; } getServiceName(service: { UUID: string }): string | undefined { return lookup( this.api.hap.Service, (thisKeyValue, value) => isObjectLike(thisKeyValue) && 'UUID' in thisKeyValue && thisKeyValue.UUID === value, service.UUID ); } getCharacteristicName( characteristic: WithUUID<{ name?: string; displayName?: string }> ): string | undefined { if ('name' in characteristic && characteristic.name !== undefined) return characteristic.name; if ( 'displayName' in characteristic && characteristic.displayName !== undefined ) return characteristic.displayName; if ('UUID' in characteristic) { return lookupCharacteristicNameByUUID( this.api.hap.Characteristic, characteristic.UUID ); } return undefined; } /** * Registers a Homebridge PlatformAccessory. * * Calls {@link external:homebridge.API#registerPlatformAccessories} */ registerPlatformAccessory(platformAccessory: PlatformAccessory): void { this.log.debug( `registerPlatformAccessory(${chalk.blue( `[${platformAccessory.displayName}]` )})` ); this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [ platformAccessory, ]); } /** * Function invoked when homebridge tries to restore cached accessory */ configureAccessory(accessory: PlatformAccessory): void { this.log.info( `Configuring cached accessory: ${chalk.blue( `[${accessory.displayName}]` )} UUID: ${accessory.UUID} deviceId: %s `, accessory.context?.deviceId ); this.log.debug('%O', accessory.context); this.homebridgeAccessories.set(accessory.UUID, accessory); } /** * Adds a new or existing real device. */ private foundDevice(device: TplinkDevice): void { // TODO: refactor this function const deviceId = device.id; if (deviceId == null || deviceId.length === 0) { this.log.error('Missing deviceId: %s', device.host); return; } let deviceAccessory = this.deviceAccessories.get(deviceId); if (deviceAccessory !== undefined) { return; } this.log.info( `Adding: ${chalk.blue(`[${device.alias}]`)} %s [%s]`, device.deviceType, deviceId ); const uuid = this.api.hap.uuid.generate(deviceId); const homebridgeAccessory = this.homebridgeAccessories.get(uuid); deviceAccessory = this.createTplinkAccessory(homebridgeAccessory, device); this.deviceAccessories.set(deviceId, deviceAccessory); this.homebridgeAccessories.set(uuid, deviceAccessory.homebridgeAccessory); } /** * Removes an accessory and unregisters it from Homebridge */ // @ts-ignore: future use private removeAccessory(homebridgeAccessory: PlatformAccessory): void { this.log.info( `Removing: ${chalk.blue(`[${homebridgeAccessory.displayName}]`)}` ); this.deviceAccessories.delete(homebridgeAccessory.context.deviceId); this.homebridgeAccessories.delete(homebridgeAccessory.UUID); this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [ homebridgeAccessory, ]); } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Topics } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ServiceBusManagementClient } from "../serviceBusManagementClient"; import { SBAuthorizationRule, TopicsListAuthorizationRulesNextOptionalParams, TopicsListAuthorizationRulesOptionalParams, SBTopic, TopicsListByNamespaceNextOptionalParams, TopicsListByNamespaceOptionalParams, TopicsListAuthorizationRulesResponse, TopicsCreateOrUpdateAuthorizationRuleOptionalParams, TopicsCreateOrUpdateAuthorizationRuleResponse, TopicsGetAuthorizationRuleOptionalParams, TopicsGetAuthorizationRuleResponse, TopicsDeleteAuthorizationRuleOptionalParams, TopicsListKeysOptionalParams, TopicsListKeysResponse, RegenerateAccessKeyParameters, TopicsRegenerateKeysOptionalParams, TopicsRegenerateKeysResponse, TopicsListByNamespaceResponse, TopicsCreateOrUpdateOptionalParams, TopicsCreateOrUpdateResponse, TopicsDeleteOptionalParams, TopicsGetOptionalParams, TopicsGetResponse, TopicsListAuthorizationRulesNextResponse, TopicsListByNamespaceNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Topics operations. */ export class TopicsImpl implements Topics { private readonly client: ServiceBusManagementClient; /** * Initialize a new instance of the class Topics class. * @param client Reference to the service client */ constructor(client: ServiceBusManagementClient) { this.client = client; } /** * Gets authorization rules for a topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param options The options parameters. */ public listAuthorizationRules( resourceGroupName: string, namespaceName: string, topicName: string, options?: TopicsListAuthorizationRulesOptionalParams ): PagedAsyncIterableIterator<SBAuthorizationRule> { const iter = this.listAuthorizationRulesPagingAll( resourceGroupName, namespaceName, topicName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, topicName, options ); } }; } private async *listAuthorizationRulesPagingPage( resourceGroupName: string, namespaceName: string, topicName: string, options?: TopicsListAuthorizationRulesOptionalParams ): AsyncIterableIterator<SBAuthorizationRule[]> { let result = await this._listAuthorizationRules( resourceGroupName, namespaceName, topicName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAuthorizationRulesNext( resourceGroupName, namespaceName, topicName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAuthorizationRulesPagingAll( resourceGroupName: string, namespaceName: string, topicName: string, options?: TopicsListAuthorizationRulesOptionalParams ): AsyncIterableIterator<SBAuthorizationRule> { for await (const page of this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, topicName, options )) { yield* page; } } /** * Gets all the topics in a namespace. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param options The options parameters. */ public listByNamespace( resourceGroupName: string, namespaceName: string, options?: TopicsListByNamespaceOptionalParams ): PagedAsyncIterableIterator<SBTopic> { const iter = this.listByNamespacePagingAll( resourceGroupName, namespaceName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByNamespacePagingPage( resourceGroupName, namespaceName, options ); } }; } private async *listByNamespacePagingPage( resourceGroupName: string, namespaceName: string, options?: TopicsListByNamespaceOptionalParams ): AsyncIterableIterator<SBTopic[]> { let result = await this._listByNamespace( resourceGroupName, namespaceName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByNamespaceNext( resourceGroupName, namespaceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByNamespacePagingAll( resourceGroupName: string, namespaceName: string, options?: TopicsListByNamespaceOptionalParams ): AsyncIterableIterator<SBTopic> { for await (const page of this.listByNamespacePagingPage( resourceGroupName, namespaceName, options )) { yield* page; } } /** * Gets authorization rules for a topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param options The options parameters. */ private _listAuthorizationRules( resourceGroupName: string, namespaceName: string, topicName: string, options?: TopicsListAuthorizationRulesOptionalParams ): Promise<TopicsListAuthorizationRulesResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, options }, listAuthorizationRulesOperationSpec ); } /** * Creates an authorization rule for the specified topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param authorizationRuleName The authorization rule name. * @param parameters The shared access authorization rule. * @param options The options parameters. */ createOrUpdateAuthorizationRule( resourceGroupName: string, namespaceName: string, topicName: string, authorizationRuleName: string, parameters: SBAuthorizationRule, options?: TopicsCreateOrUpdateAuthorizationRuleOptionalParams ): Promise<TopicsCreateOrUpdateAuthorizationRuleResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, authorizationRuleName, parameters, options }, createOrUpdateAuthorizationRuleOperationSpec ); } /** * Returns the specified authorization rule. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param authorizationRuleName The authorization rule name. * @param options The options parameters. */ getAuthorizationRule( resourceGroupName: string, namespaceName: string, topicName: string, authorizationRuleName: string, options?: TopicsGetAuthorizationRuleOptionalParams ): Promise<TopicsGetAuthorizationRuleResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, authorizationRuleName, options }, getAuthorizationRuleOperationSpec ); } /** * Deletes a topic authorization rule. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param authorizationRuleName The authorization rule name. * @param options The options parameters. */ deleteAuthorizationRule( resourceGroupName: string, namespaceName: string, topicName: string, authorizationRuleName: string, options?: TopicsDeleteAuthorizationRuleOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, authorizationRuleName, options }, deleteAuthorizationRuleOperationSpec ); } /** * Gets the primary and secondary connection strings for the topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param authorizationRuleName The authorization rule name. * @param options The options parameters. */ listKeys( resourceGroupName: string, namespaceName: string, topicName: string, authorizationRuleName: string, options?: TopicsListKeysOptionalParams ): Promise<TopicsListKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, authorizationRuleName, options }, listKeysOperationSpec ); } /** * Regenerates primary or secondary connection strings for the topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param authorizationRuleName The authorization rule name. * @param parameters Parameters supplied to regenerate the authorization rule. * @param options The options parameters. */ regenerateKeys( resourceGroupName: string, namespaceName: string, topicName: string, authorizationRuleName: string, parameters: RegenerateAccessKeyParameters, options?: TopicsRegenerateKeysOptionalParams ): Promise<TopicsRegenerateKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, authorizationRuleName, parameters, options }, regenerateKeysOperationSpec ); } /** * Gets all the topics in a namespace. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param options The options parameters. */ private _listByNamespace( resourceGroupName: string, namespaceName: string, options?: TopicsListByNamespaceOptionalParams ): Promise<TopicsListByNamespaceResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, options }, listByNamespaceOperationSpec ); } /** * Creates a topic in the specified namespace. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param parameters Parameters supplied to create a topic resource. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, namespaceName: string, topicName: string, parameters: SBTopic, options?: TopicsCreateOrUpdateOptionalParams ): Promise<TopicsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, parameters, options }, createOrUpdateOperationSpec ); } /** * Deletes a topic from the specified namespace and resource group. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param options The options parameters. */ delete( resourceGroupName: string, namespaceName: string, topicName: string, options?: TopicsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, options }, deleteOperationSpec ); } /** * Returns a description for the specified topic. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param options The options parameters. */ get( resourceGroupName: string, namespaceName: string, topicName: string, options?: TopicsGetOptionalParams ): Promise<TopicsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, options }, getOperationSpec ); } /** * ListAuthorizationRulesNext * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param topicName The topic name. * @param nextLink The nextLink from the previous successful call to the ListAuthorizationRules method. * @param options The options parameters. */ private _listAuthorizationRulesNext( resourceGroupName: string, namespaceName: string, topicName: string, nextLink: string, options?: TopicsListAuthorizationRulesNextOptionalParams ): Promise<TopicsListAuthorizationRulesNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, topicName, nextLink, options }, listAuthorizationRulesNextOperationSpec ); } /** * ListByNamespaceNext * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param nextLink The nextLink from the previous successful call to the ListByNamespace method. * @param options The options parameters. */ private _listByNamespaceNext( resourceGroupName: string, namespaceName: string, nextLink: string, options?: TopicsListByNamespaceNextOptionalParams ): Promise<TopicsListByNamespaceNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, nextLink, options }, listByNamespaceNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listAuthorizationRulesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBAuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.topicName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.SBAuthorizationRule }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters3, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.authorizationRuleName, Parameters.topicName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBAuthorizationRule }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.authorizationRuleName, Parameters.topicName ], headerParameters: [Parameters.accept], serializer }; const deleteAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.authorizationRuleName, Parameters.topicName ], headerParameters: [Parameters.accept], serializer }; const listKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}/ListKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.AccessKeys }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.authorizationRuleName, Parameters.topicName ], headerParameters: [Parameters.accept], serializer }; const regenerateKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}/regenerateKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.AccessKeys }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.authorizationRuleName, Parameters.topicName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listByNamespaceOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBTopicListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.skip, Parameters.top], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1 ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.SBTopic }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters11, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.topicName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.topicName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBTopic }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.topicName ], headerParameters: [Parameters.accept], serializer }; const listAuthorizationRulesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBAuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.nextLink, Parameters.topicName ], headerParameters: [Parameters.accept], serializer }; const listByNamespaceNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBTopicListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.skip, Parameters.top], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import * as fs from "fs"; import * as path from "path"; import { assert } from "chai"; import parse from "csv-parse/lib/sync"; import * as helper from "./helper/index"; import { PostcodesioHttpError } from "../src/app/lib/errors"; const seedFilePath = path.resolve(__dirname, "./seed/postcode.csv"); const Postcode = helper.Postcode; import { query } from "../src/app/models/base"; /** * Counts number of postcode records if * - not headers * - not terminated */ const postcodeRecordCount = (seedFilePath: any) => { return parse(fs.readFileSync(seedFilePath)).filter( (row: any) => row[0] !== "pcd" && row[4].length === 0 ).length; }; const postcodeEntriesCount = postcodeRecordCount(seedFilePath); describe("Postcode Model", function () { let testPostcode: string, testOutcode: string; before(async function () { this.timeout(0); await helper.clearPostcodeDb(); await helper.seedPostcodeDb(); }); beforeEach(async () => { const result = await helper.lookupRandomPostcode(); testPostcode = result.postcode; testOutcode = result.outcode; }); after(async () => helper.clearPostcodeDb()); describe("#setupTable", function () { before(async function () { this.timeout(0); await Postcode.destroyRelation(); await Postcode.setupTable(seedFilePath); }); after(async function () { this.timeout(0); await Postcode.destroyRelation(); await Postcode.setupTable(seedFilePath); }); describe("#_createRelation", () => { it(`creates a relation that matches ${Postcode.relation.relation} schema`, async () => { const q = ` SELECT column_name, data_type, character_maximum_length, collation_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '${Postcode.relation.relation}' `; const result = await query(q); const impliedSchema: any = {}; result.rows.forEach((columnInfo) => { const [columnName, dataType] = helper.inferSchemaData(columnInfo); impliedSchema[columnName] = dataType; }); assert.deepEqual(impliedSchema, Postcode.relation.schema); }); }); describe("#seedData", () => { it("loads correct data from data directory", async () => { const q = `SELECT count(*) FROM ${Postcode.relation.relation}`; const result = await query(q); assert.equal(result.rows[0].count, postcodeEntriesCount); }); }); describe("#populateLocation", () => { it("populates location collumn with geohashes", async () => { const q = `SELECT location from ${Postcode.relation.relation} WHERE location IS NOT NULL`; const result = await query(q); result.rows.forEach((row) => assert.equal(row.location.length, 50)); }); }); describe("#createIndexes", () => { it("generates indexes that matches to what's been specified", async () => { const q = ` SELECT indexdef FROM pg_indexes WHERE tablename = '${Postcode.relation.relation}' `; const result = await query(q); const dbIndexes = result.rows .map((row) => helper.inferIndexInfo(row.indexdef)) .filter((r) => r.column !== "id"); const byIndexColumns = helper.sortByIndexColumns; assert.deepEqual( dbIndexes.sort(byIndexColumns), Postcode.relation.indexes.sort(byIndexColumns) ); }); }); }); describe("#toJson", () => { it("formats an address object", () => { const address = { admin_district_id: "admin_district_id", admin_county_id: "admin_county_id", admin_ward_id: "admin_ward_id", parish_id: "parish_id", ccg_id: "ccg_id", nuts_code: "nuts_code", id: 0, location: "location", pc_compact: "pc_compact", }; // @ts-ignore const formatted = Postcode.toJson(address); assert.property(formatted, "codes"); // @ts-ignore assert.equal(formatted.codes.admin_district, address.admin_district_id); // @ts-ignore assert.equal(formatted.codes.admin_county, address.admin_county_id); // @ts-ignore assert.equal(formatted.codes.admin_ward, address.admin_ward_id); // @ts-ignore assert.equal(formatted.codes.parish, address.parish_id); // @ts-ignore assert.equal(formatted.codes.ccg, address.ccg_id); // @ts-ignore assert.equal(formatted.codes.nuts, address.nuts_code); assert.notProperty(formatted, "id"); assert.notProperty(formatted, "location"); assert.notProperty(formatted, "pc_compact"); assert.notProperty(formatted, "admin_district_id"); assert.notProperty(formatted, "admin_county_id"); assert.notProperty(formatted, "admin_ward_id"); assert.notProperty(formatted, "parish_id"); assert.notProperty(formatted, "ccg_id"); assert.notProperty(formatted, "nuts_id"); assert.notProperty(formatted, "nuts_code"); }); }); describe("#find", () => { it("should return postcode with the right attributes", async () => { const result = await Postcode.find(testPostcode); assert.equal(result.postcode, testPostcode); helper.isRawPostcodeObjectWithFC(result); }); it("should return null for null/undefined postcode search", async () => { const result = await Postcode.find(null); assert.isNull(result); }); it("returns null if invalid postcode", async () => { const result = await Postcode.find("1"); assert.isNull(result); }); it("should be insensitive to space", async () => { const result = await Postcode.find(testPostcode.replace(/\s/, "")); assert.equal(result.postcode, testPostcode); }); it("should return null if postcode does not exist", async () => { const result = await Postcode.find("ID11QD"); assert.isNull(result); }); }); describe("loadPostcodeIds", () => { it("loads a complete array of postcode IDs", async () => { await Postcode.loadPostcodeIds(); // @ts-ignore assert.isArray(Postcode.idCache[undefined]); // @ts-ignore assert.isTrue(Postcode.idCache[undefined].length > 0); }); it("loads IDs by outcode if specified", async () => { const outcode = "AB10"; await Postcode.loadPostcodeIds(outcode); assert.isArray(Postcode.idCache[outcode]); assert.isTrue(Postcode.idCache[outcode].length > 0); }); }); describe("#random", () => { it("should return a random postcode", async () => { const postcode = await Postcode.random(); helper.isRawPostcodeObjectWithFC(postcode); }); describe("Outcode filter", () => { it("returns random postcode for within an outcode", async () => { const outcode = "AB10"; const postcode = await Postcode.random(outcode); helper.isRawPostcodeObjectWithFC(postcode); assert.equal(postcode.outcode, outcode); }); it("is case and space insensitive", async () => { const outcode = "aB 10 "; const postcode = await Postcode.random(outcode); helper.isRawPostcodeObjectWithFC(postcode); assert.equal(postcode.outcode, "AB10"); }); it("caches requests", async () => { const outcode = "AB12"; const postcode = await Postcode.random(outcode); helper.isRawPostcodeObjectWithFC(postcode); assert.isTrue(Postcode.idCache[outcode].length > 0); }); it("returns null if invalid outcode", async () => { const outcode = "BOGUS"; const postcode = await Postcode.random(outcode); assert.isNull(postcode); }); }); }); describe("#randomFromIds", () => { before(async () => { await Postcode.loadPostcodeIds(); }); it("should return a random postcode using an in memory ID store", async () => { const postcode = await Postcode.randomFromIds( // @ts-ignore Postcode.idCache[undefined] ); helper.isRawPostcodeObjectWithFC(postcode); }); }); describe("#findOutcode", () => { it("should return the outcode with the right attributes", async () => { const result = await Postcode.findOutcode(testOutcode); assert.equal(result.outcode, testOutcode); assert.property(result, "northings"); assert.property(result, "eastings"); assert.property(result, "longitude"); assert.property(result, "latitude"); assert.isArray(result["admin_ward"]); assert.isArray(result["admin_district"]); assert.isArray(result["admin_county"]); assert.isArray(result["parish"]); assert.isArray(result["country"]); }); it("should return null if no matching outcode", async () => { const result = await Postcode.findOutcode("EZ12"); assert.equal(result, null); }); it("should return null if invalid outcode", async () => { const result = await Postcode.findOutcode("1"); assert.equal(result, null); }); it("should return null if girobank outcode", async () => { const result = await Postcode.findOutcode("GIR"); assert.equal(result, null); }); it("should return null for a plausible but non-existent postcode", async () => { const result = await Postcode.findOutcode("EJ12"); assert.equal(result, null); }); it("should be insensitive to space", async () => { const result = await Postcode.findOutcode(testOutcode + " "); assert.equal(result.outcode, testOutcode); assert.property(result, "northings"); assert.property(result, "eastings"); assert.property(result, "longitude"); assert.property(result, "latitude"); }); it("should be insensitive to case", async () => { const result = await Postcode.findOutcode(testOutcode.toLowerCase()); assert.equal(result.outcode, testOutcode); assert.property(result, "northings"); assert.property(result, "eastings"); assert.property(result, "longitude"); assert.property(result, "latitude"); }); }); describe("#nearestPostcodes", function () { let location: any; beforeEach(async () => { location = await helper.locationWithNearbyPostcodes(); }); it("should return a list of nearby postcodes", async () => { const params = location; const postcodes = await Postcode.nearestPostcodes(params); assert.isArray(postcodes); postcodes.forEach((p) => helper.isRawPostcodeObjectWithFCandDistance(p)); }); it("should be sensitive to limit", async () => { const params = { longitude: location.longitude, latitude: location.latitude, limit: "1", }; const postcodes = await Postcode.nearestPostcodes(params); assert.isArray(postcodes); assert.equal(postcodes.length, 1); postcodes.forEach((p) => helper.isRawPostcodeObjectWithFCandDistance(p)); }); it("should be sensitive to distance param", async () => { const nearby = { longitude: location.longitude, latitude: location.latitude, }; const farAway = { longitude: location.longitude, latitude: location.latitude, radius: "1000", }; const postcodes = await Postcode.nearestPostcodes(nearby); const farawayPostcodes = await Postcode.nearestPostcodes(farAway); assert.isTrue(farawayPostcodes.length >= postcodes.length); }); it("should throw error if limit is invalid", async () => { const params = { longitude: location.longitude, latitude: location.latitude, limit: "Bogus", }; try { await Postcode.nearestPostcodes(params); } catch (error) { assert.instanceOf(error, PostcodesioHttpError); } }); it("should throw error for invalid radius", async () => { const nearby = { longitude: location.longitude, latitude: location.latitude, radius: "BOGUS", }; try { await Postcode.nearestPostcodes(nearby); } catch (error) { assert.instanceOf(error, PostcodesioHttpError); } }); it("should raise an error if invalid longitude", async () => { const params = { longitude: "Bogus", latitude: location.latitude, }; try { await Postcode.nearestPostcodes(params); } catch (error) { assert.isNotNull(error); assert.match(error.message, /Invalid longitude\/latitude submitted/i); } }); it("should raise an error if invalid latitude", async () => { const params = { longitude: location.longitude, latitude: "Bogus", }; try { await Postcode.nearestPostcodes(params); } catch (error) { assert.isNotNull(error); assert.match(error.message, /Invalid longitude\/latitude submitted/i); } }); describe("Wide Search", () => { let params: any; beforeEach(() => { params = { longitude: -2.12659411941741, latitude: 57.2465923827836, }; }); it("performs an incremental search if flag is passed", async () => { const postcodes = await Postcode.nearestPostcodes(params); assert.isNull(postcodes); params.wideSearch = true; const secondPostcodes = await Postcode.nearestPostcodes(params); assert.equal(secondPostcodes.length, 10); }); it("performs an incremental search if 'widesearch' flag is passed", async () => { const postcodes = await Postcode.nearestPostcodes(params); assert.isNull(postcodes); params.widesearch = true; const secondPostcodes = await Postcode.nearestPostcodes(params); assert.equal(secondPostcodes.length, 10); }); it("returns null if point is too far from nearest postcode", async () => { params = { longitude: 0, latitude: 0, wideSearch: true, }; const postcodes = await Postcode.nearestPostcodes(params); assert.isNull(postcodes); }); it("resets limit to a maximum of 10 if it is exceeded", async () => { params.wideSearch = true; params.limit = 20; const postcodes = await Postcode.nearestPostcodes(params); assert.equal(postcodes.length, 10); }); it("maintains limit if less than 10", async () => { const limit = 2; params.wideSearch = true; params.limit = limit; const postcodes = await Postcode.nearestPostcodes(params); assert.equal(postcodes.length, limit); }); }); }); });
the_stack
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { HttpClient } from "@angular/common/http"; import { PenguinService } from 'src/app/service/penguin.service'; import { SelectedService } from 'src/app/service/selected.service'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { Chapter } from 'src/app/interface/Chapter'; import { Item } from 'src/app/interface/Item'; import { MatSnackBar, MatDialog } from '@angular/material'; import { GoogleAnalyticsEventsService } from 'src/app/service/google-analytics-events-service'; import { Limitation, ItemQuantityBounds, Bounds } from 'src/app/util/limitation'; import { ReportWarningDialogComponent } from './dialog.report.component'; import { ActivatedRoute } from '@angular/router'; import { UserControlComponent } from 'src/app/component/user-control/user-control.component'; interface DropDetail { item: Item; quantity: number; }; @Component({ selector: 'app-report', templateUrl: './report.component.html', styleUrls: ['./report.component.scss'] }) export class ReportComponent implements OnInit, OnDestroy { @ViewChild(UserControlComponent) private userControlComponent: UserControlComponent; destroy$: Subject<boolean> = new Subject<boolean>(); itemList: Item[] = []; itemMap: any; limitationMap: any; normalDrops: DropDetail[] = new Array(); specialDrops: DropDetail[] = new Array(); extraDrops: DropDetail[] = new Array(); allDrops: DropDetail[] = new Array(); isReporting: boolean = false; furnitureNum: number = 0; checkDrops: boolean = true; mode: string = null; reportStageFilter: (chapter: Chapter) => boolean = chapter => { const timestamp = Number(new Date()); if (chapter.openTime && chapter.openTime > timestamp) { return false; } if (chapter.closeTime && chapter.closeTime < timestamp) { return false; } return true; }; constructor(private http: HttpClient, public penguinService: PenguinService, public selectedService: SelectedService, public googleAnalyticsEventsService: GoogleAnalyticsEventsService, private _snackBar: MatSnackBar, public dialog: MatDialog, private route: ActivatedRoute) { } ngOnInit() { this.penguinService.itemListData.pipe(takeUntil(this.destroy$)).subscribe(res => { if (res) { this.itemList = res; } }); this.penguinService.itemMapData.pipe(takeUntil(this.destroy$)).subscribe(res => { if (res) { this.itemMap = res; } }); this.penguinService.limitationMapData.pipe(takeUntil(this.destroy$)).subscribe(res => { if (res) { this.limitationMap = res; } }); this.route.paramMap.pipe(takeUntil(this.destroy$)).subscribe(res => { if (res) { this.mode = res.get("mode"); if (this.mode) { console.log("You have entered " + this.mode + " mode."); } } }); if (this.selectedService.selections.report.selectedStage && this.selectedService.selections.report.selectedChapter) { this.clearDrops(); } } ngOnDestroy(): void { this.destroy$.next(true); this.destroy$.unsubscribe(); } onChapterChange($event) { this.selectedService.selections.report.selectedChapter = $event; } onStageChange($event) { this.selectedService.selections.report.selectedStage = $event; this.clearDrops(); } clearDrops() { this.normalDrops = new Array(); this.specialDrops = new Array(); this.extraDrops = new Array(); this.allDrops = new Array(); this.furnitureNum = 0; if (this.itemMap && this.selectedService.selections.report.selectedStage) { this.selectedService.selections.report.selectedStage.normalDrop.forEach(itemId => { this.normalDrops.push({ item: this.itemMap[itemId], quantity: 0 }); }); this.selectedService.selections.report.selectedStage.specialDrop.forEach(itemId => { this.specialDrops.push({ item: this.itemMap[itemId], quantity: 0 }); }); this.selectedService.selections.report.selectedStage.extraDrop.forEach(itemId => { this.extraDrops.push({ item: this.itemMap[itemId], quantity: 0 }); }); this.normalDrops.sort((a, b) => a.item.sortId - b.item.sortId); this.specialDrops.sort((a, b) => a.item.sortId - b.item.sortId); this.extraDrops.sort((a, b) => a.item.sortId - b.item.sortId); } } selectHasFurniture(furnitureNum: number) { this.furnitureNum = furnitureNum; } addQuantity(item: Item, drops: DropDetail[], quantity: number) { if (this.isReporting) { return false; } for (let i = 0; i < drops.length; i++) { if (drops[i].item === item) { drops[i].quantity += quantity; if (drops[i].quantity < 0) { drops[i].quantity = 0; } } } this._updateAllDrops(); return false; } submitDrops() { this.isReporting = true; let finalResult = { stageId: this.selectedService.selections.report.selectedStage.stageId, furnitureNum: this.furnitureNum, drops: this.allDrops.map(drop => ({ itemId: drop.item.itemId, quantity: drop.quantity })), source: this.mode !== 'internal' ? "penguin-stats.io" : "penguin-stats.io(internal)", version: this.penguinService.version }; if (this.checkDrops && !this._checkDrops(finalResult)) { this.googleAnalyticsEventsService.emitEvent("report", "show_warning", this.selectedService.selections.report.selectedStage.stageId, 1); this._openDialog(); this.isReporting = false; } else { this.http.post(this.penguinService.origin + this.penguinService.api.report, finalResult, { responseType: 'text' }) .subscribe( (val) => { this._snackBar.open("上传成功。", "", { duration: 2000 }); this.googleAnalyticsEventsService.emitEvent("report", "submit_single", this.selectedService.selections.report.selectedStage.stageId, 1); this.clearDrops(); if (!this.checkDrops) { this.googleAnalyticsEventsService.emitEvent("report", "ignore_warning", this.selectedService.selections.report.selectedStage.stageId, 1); } this.checkDrops = true; this.userControlComponent.refresh(); }, error => { this._snackBar.open("上传失败。可将以下信息提供给作者以便改进本网站:" + error.message, "x"); this.isReporting = false; this.checkDrops = true; }, () => { this.isReporting = false; this.checkDrops = true; }); } } private _openDialog(): void { const dialogRef = this.dialog.open(ReportWarningDialogComponent, { width: '500px', data: {} }); dialogRef.afterClosed().subscribe(result => { if (result) { this.checkDrops = false; this.submitDrops(); } }); } private _checkDrops(finalResult: any): boolean { try { if (this.mode === 'internal') { return true; } if (!this.limitationMap) { return true; // check from back-end instead } const limitation: Limitation = this.limitationMap[finalResult.stageId]; if (!limitation) { return true; // check from back-end instead } if (limitation.itemTypeBounds) { let typeBounds: Bounds = new Bounds(limitation.itemTypeBounds.lower, limitation.itemTypeBounds.upper, limitation.itemTypeBounds.exceptions); if (!typeBounds.isValid(finalResult.drops.length)) { return false; } } let dropsMap: any = {}; finalResult.drops.forEach(drop => { dropsMap[drop.itemId] = drop; }); if (finalResult.furnitureNum) { dropsMap['furni'] = { itemId: 'furni', quantity: finalResult.furnitureNum }; } const itemQuantityBounds: ItemQuantityBounds[] = limitation.itemQuantityBounds; if (itemQuantityBounds !== null) { for (let i = 0; i < itemQuantityBounds.length; i++) { const oneBounds: ItemQuantityBounds = itemQuantityBounds[i]; const drop = dropsMap[oneBounds.itemId]; let quantity = !drop ? 0 : drop.quantity; if (oneBounds.bounds) { let bounds: Bounds = new Bounds(oneBounds.bounds.lower, oneBounds.bounds.upper, oneBounds.bounds.exceptions); if (!bounds.isValid(quantity)) { return false; } } } } return true; } catch (error) { console.log(error); return true; // check from back-end instead } } private _updateAllDrops() { this.allDrops = new Array(); let dropDict = {}; let combinedDrops = this.normalDrops.concat(this.specialDrops).concat(this.extraDrops); combinedDrops.forEach(drop => { if (drop.quantity !== 0) { if (dropDict[drop.item.itemId] === undefined) { this.allDrops.push({ item: drop.item, quantity: drop.quantity }); dropDict[drop.item.itemId] = this.allDrops.length - 1; } else { this.allDrops[dropDict[drop.item.itemId]].quantity += drop.quantity; } } }); } trackByDropItemId(index: number, drop: DropDetail) { return drop.item.itemId; } // changeValue(drop, value) { // drop.quantity = Number(value); // this._updateAllDrops(); // } }
the_stack
import { BitcoinProtocol } from '../../../src' import { IACMessageDefinitionObject } from '../../../src/serializer/message' import { SignedBitcoinTransaction } from '../../../src/serializer/schemas/definitions/signed-transaction-bitcoin' import { RawBitcoinTransaction } from '../../../src/serializer/types' import { AirGapWalletStatus } from '../../../src/wallet/AirGapWallet' import { TestProtocolSpec } from '../implementations' import { BitcoinProtocolStub } from '../stubs/bitcoin.stub' import { BitcoinTransactionValidator } from './../../../src/serializer/unsigned-transactions/bitcoin-transactions.validator' export class BitcoinProtocolSpec extends TestProtocolSpec { public name = 'Bitcoin' public lib = new BitcoinProtocol() public stub = new BitcoinProtocolStub() public validAddresses = [ '37XuVSEpWW4trkfmvWzegTHQt7BdktSKUs', '19165VoETh1ZAcwNN5pjeXgMCJbmt4rbUB', '3JcJdozCssqB1RUGhhZPCSCFeSAE21sep9', '3CzQRvFBARhR14mfL6Dcm1XgzTRnvLwhjs' ] public wallet = { privateKey: 'xprv9yzvjXeHEDMMM2x8H6btZjyVaB9YBpvR7wdqQhGAEQbsvjrQejHhPdqdMRcAE3MqdZcfrSkCGk96YVqPhFHwJqY7VxgPgmMWMehcmHdQJ5h', publicKey: 'xpub6CzH93BB4aueZX2bP88tvsvE8Cz2bHeGVAZSD5fmnk8roYBZCGbwwSA7ChiRr65jncuPH8qBQA9nBwi2Qtz1Uqt8wuHvof9SAcPpFxpe1GV', addresses: ['15B2gX2x1eqFKgR44nCe1i33ursGKP4Qpi', '1QKqr9wjki9K9tF9NxigbwgHeLXHT682sc'], masterFingerprint: '', status: AirGapWalletStatus.ACTIVE } public txs = [ { from: ['15B2gX2x1eqFKgR44nCe1i33ursGKP4Qpi', '1QKqr9wjki9K9tF9NxigbwgHeLXHT682sc'], to: ['15B2gX2x1eqFKgR44nCe1i33ursGKP4Qpi'], amount: '10', fee: '27000', unsignedTx: { ins: [ { txId: '8a10220812842e93b7263491cf664b36fece9861b39ca762b57ac46bb7a7cd7b', value: '10', vout: 0, address: '15B2gX2x1eqFKgR44nCe1i33ursGKP4Qpi', derivationPath: '0/0' }, { txId: 'cc69b832b6d922a04bf9653bbd12335a78f82fc09be7536f2378bbad8554039d', value: '32418989', vout: 0, address: '1QKqr9wjki9K9tF9NxigbwgHeLXHT682sc', derivationPath: '1/2' } ], outs: [ { derivationPath: '', recipient: '15B2gX2x1eqFKgR44nCe1i33ursGKP4Qpi', isChange: false, value: '10' }, { derivationPath: '3', recipient: '1KVA7HX16cef46Lpsi67v8ZV4y6bAiTmLt', isChange: true, value: '32391989' } ] }, signedTx: `01000000027bcda7b76bc47ab562a79cb36198cefe364b66cf913426b7932e84120822108a000000006a473044022020196ef19bf59e57334f679a725d8e4ead38121d70da56ff3cb09e96fd3eef49022077f11913dc6c4feca173079578729efa814745e7baa6dce8cda668277c15501501210311a202c95426b8aafdd7b482e53a363935eb6491b8bcd8991f16abc810f68868ffffffff9d035485adbb78236f53e79bc02ff8785a3312bd3b65f94ba022d9b632b869cc000000006a4730440220278602b82b439124b2bffe2e7e14ddaf1ab3ab2fc96bafcd91240c5cbffeaf5102207f27fab5172d9159af1f5ad974e73e1b8c5faffffab83ec9211d24f08cece18d012102f5ec5458a1d3ce47e87e606df057e6efdfa4c3190b492b115418376865682cacffffffff020a000000000000001976a9142dc610f6d5bfca59507d0dddb986eacfe5c3ed8b88ac3543ee01000000001976a914cac583a9ff2b5c2ac8ea3d5d0a37cc56e99d16f488ac00000000` } ] public validRawTransactions: RawBitcoinTransaction[] = [ { ins: [ { txId: '8a10220812842e93b7263491cf664b36fece9861b39ca762b57ac46bb7a7cd7b', value: '10', vout: 0, address: '34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo', // Mainnet Address derivationPath: '0/0' }, { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: '385cR5DM96n1HvBDMzLHPYcw89fZAXULJP', derivationPath: '1/3' } ], outs: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: false, value: '10' }, { recipient: '1LdRcdxfbSnmCYYNdeYpUnztiYzVfBEQeC', isChange: true, value: '64973000' } ] } ] public invalidUnsignedTransactionValues: { property: string; testName: string; values: { value: any; expectedError: any }[] }[] = [ { property: 'ins', testName: 'Ins', values: [ // not a valid txId { value: [ { txId: '0x', value: '10', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' not a valid txId'] }, { value: [ { txId: '', value: '10', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' not a valid txId'] }, { value: [ { txId: 0x0, value: '10', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' not a valid txId'] }, { value: [ { txId: 1, value: '10', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' not a valid txId'] }, { value: [ { txId: -1, value: '10', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' not a valid txId'] }, { value: [ { txId: undefined, value: '10', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' not a valid txId'] }, { value: [ { txId: null, value: '10', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' not a valid txId'] }, // value not a valid BigNumber { value: [ { txId: '8a10220812842e93b7263491cf664b36fece9861b39ca762b57ac46bb7a7cd7b', value: '0x', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' value not a valid BigNumber'] }, { value: [ { txId: '8a10220812842e93b7263491cf664b36fece9861b39ca762b57ac46bb7a7cd7b', value: '', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' value not a valid BigNumber'] }, { value: [ { txId: '8a10220812842e93b7263491cf664b36fece9861b39ca762b57ac46bb7a7cd7b', value: 0x0, vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' value not a valid BigNumber'] }, { value: [ { txId: '8a10220812842e93b7263491cf664b36fece9861b39ca762b57ac46bb7a7cd7b', value: 1, vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' value not a valid BigNumber'] }, { value: [ { txId: '8a10220812842e93b7263491cf664b36fece9861b39ca762b57ac46bb7a7cd7b', value: -1, vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' value not a valid BigNumber'] }, { value: [ { txId: '8a10220812842e93b7263491cf664b36fece9861b39ca762b57ac46bb7a7cd7b', value: undefined, vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' value not a valid BigNumber'] }, { value: [ { txId: '8a10220812842e93b7263491cf664b36fece9861b39ca762b57ac46bb7a7cd7b', value: null, vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0/0' } ], expectedError: [' value not a valid BigNumber'] }, // vout is not a number { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: '0x0', address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '1/3' } ], expectedError: [' vout is not a number'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: '', address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '1/3' } ], expectedError: [' vout is not a number'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0x0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '1/3' } ], expectedError: undefined }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 1, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '1/3' } ], expectedError: undefined }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: -1, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '1/3' } ], expectedError: [' vout is not a positive value'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: undefined, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '1/3' } ], expectedError: [' vout is not a number'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: null, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '1/3' } ], expectedError: [' vout is not a number'] }, // not a valid bitcoin address { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: '0x', derivationPath: '1/3' } ], expectedError: [' not a valid bitcoin address'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: '', derivationPath: '1/3' } ], expectedError: [' not a valid bitcoin address'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: 0x0, derivationPath: '1/3' } ], expectedError: [' not a valid bitcoin address'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: 1, derivationPath: '1/3' } ], expectedError: [' not a valid bitcoin address'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: -1, derivationPath: '1/3' } ], expectedError: [' not a valid bitcoin address'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: undefined, derivationPath: '1/3' } ], expectedError: [' not a valid bitcoin address'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: null, derivationPath: '1/3' } ], expectedError: [' not a valid bitcoin address'] }, // TODO check for derivation paths { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '0x' } ], expectedError: [' invalid derivation path'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: '' } ], expectedError: [' invalid derivation path'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: 0x0 } ], expectedError: [' invalid derivation path'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: 1 } ], expectedError: [' invalid derivation path'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: -1 } ], expectedError: [' invalid derivation path'] }, { value: [ { txId: 'e7ab576fd222c7c5d463497e3eb54789abebca2c48efcc1a2e93e8ab5c066eac', value: '65000000', vout: 0, address: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', derivationPath: undefined } ], expectedError: [' invalid derivation path'] } ] }, { property: 'outs', testName: 'Outs', values: [ // invalid Bitcoin address { value: [ { recipient: '0x0', isChange: false, value: '10' } ], expectedError: [' invalid Bitcoin address'] }, { value: [ { recipient: '', isChange: false, value: '10' } ], expectedError: [' invalid Bitcoin address'] }, { value: [ { recipient: 0x0, isChange: false, value: '10' } ], expectedError: [' invalid Bitcoin address'] }, { value: [ { recipient: 1, isChange: false, value: '10' } ], expectedError: [' invalid Bitcoin address'] }, { value: [ { recipient: -1, isChange: false, value: '10' } ], expectedError: [' invalid Bitcoin address'] }, { value: [ { recipient: undefined, isChange: false, value: '10' } ], expectedError: [' invalid Bitcoin address'] }, { value: [ { recipient: null, isChange: false, value: '10' } ], expectedError: [' invalid Bitcoin address'] }, // change is not a boolean { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: '0x0', value: '10' } ], expectedError: [' change is not a boolean'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: '', value: '10' } ], expectedError: [' change is not a boolean'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: 0x0, value: '10' } ], expectedError: [' change is not a boolean'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: 1, value: '10' } ], expectedError: [' change is not a boolean'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: -1, value: '10' } ], expectedError: [' change is not a boolean'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: undefined, value: '10' } ], expectedError: [' change is not a boolean'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: null, value: '10' } ], expectedError: [' change is not a boolean'] }, // value is not BigNumber { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: true, value: '0x0' } ], expectedError: [' value is not BigNumber'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: true, value: '' } ], expectedError: [' value is not BigNumber'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: true, value: 0x0 } ], expectedError: [' value is not BigNumber'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: true, value: 1 } ], expectedError: [' value is not BigNumber'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: true, value: -1 } ], expectedError: [' value is not BigNumber'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: true, value: undefined } ], expectedError: [' value is not BigNumber'] }, { value: [ { recipient: '3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', isChange: true, value: null } ], expectedError: [' value is not BigNumber'] } ] } ] public validSignedTransactions: SignedBitcoinTransaction[] = [ { from: ['3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', '385cR5DM96n1HvBDMzLHPYcw89fZAXULJP'], to: [], amount: '1008', fee: '27000', accountIdentifier: 'xpub6CzH93BB4aueZX2bP88tvsvE8Cz2bHeGVAZSD5fmnk8roYBZCGbwwSA7ChiRr65jncuPH8qBQA9nBwi2Qtz1Uqt8wuHvof9SAcPpFxpe1GV', transaction: '01000000027bcda7b76bc47ab562a79cb36198cefe364b66cf913426b7932e84120822108a000000006b483045022100b08a74de56349455c7444acd4eba9e46aa4777eb4925203ba601f5d8765304e202205cafd944b3c92add0ed38a9603e19bac938e9bec6490b33d82d4b36d615df8210121024fd3380540fcc9ca541259ecbdf1b6c649d2be04f76d17d685ab63a8e75c4b0effffffffac6e065cabe8932e1accef482ccaebab8947b53e7e4963d4c5c722d26f57abe7000000006b483045022100d589a6c9a3c8cc4f7d05600b7d5e8a37ab7482671bc0d889671ab420fa2359210220635944edcea9947b7e40396ae41d1f0853deeef8f576a4112ace3366fe1b6453012102f75fcf06cbe5726214e6199dd7720230083fd3c4f5a984c209373684b1e010feffffffff020a000000000000001976a9141b6d966bb9c605b984151da9bed896145698c44288acc868df03000000001976a9143c95ddf9b6baf3086f3880b15900b21d970ddc9d88ac00000000' } ] public invalidSignedTransactionValues: { property: string; testName: string; values: { value: any; expectedError: any }[] }[] = [ { property: 'from', testName: 'From', values: [ { value: ['3E35SFZkfLMGo4qX5aVs1bBDSnAuGgBH33', '385cR5DM96n1HvBDMzLHPYcw89fZAXULJP'], expectedError: undefined } // { // value: '0x0', // expectedError: [" can't be blank", ' not a valid Bitcoin account'] // } // TODO: Valid? // { // value: '', // expectedError: [" can't be blank", ' invalid tx format'] // }, // { // value: 0x0, // expectedError: [' is not of type "String"', " isn't base64 encoded"] // }, // { // value: 1, // expectedError: [' is not of type "String"', " isn't base64 encoded"] // }, // { // value: -1, // expectedError: [' is not of type "String"', " isn't base64 encoded"] // }, // { // value: undefined, // expectedError: [" can't be blank"] // }, // { // value: null, // expectedError: [" can't be blank"] // } ] } ] public validator: BitcoinTransactionValidator = new BitcoinTransactionValidator() public signedTransaction(tx: any): IACMessageDefinitionObject[] { const protocol: IACMessageDefinitionObject[] = super.signedTransaction(tx) const payload = protocol[0].payload as SignedBitcoinTransaction payload.amount = this.txs[0].amount payload.fee = this.txs[0].fee payload.from = this.wallet.addresses return protocol } public messages = [ { message: 'example message', signature: 'IBktb5pV1sOtX15/qK8IyocO0i1Bbxf+v+ZqCryg477QVYykBA4U4iXcpgjfJwagHi+OaXXpOStd8v86VVp87j0=' } ] public encryptAsymmetric = [ { message: 'example message', encrypted: '04304d211a7dd38b49e8bddf0c5b28f813f398927effab15e394c8bb21801003fd7f2e2846d09325c04b8f979f133d75e32f73f3faca761305fa01c021d931e901b9989df63b2845d87de830696311bc73b19997aee66ed129a92745d1714c0734d7171f15af3e64a1f62be46a455b9c' } ] public encryptAES = [ { message: 'example message', encrypted: '0d19df9aa03a6b1f743f87f3b76031fb!5b1912552bf8f16ebc6cd038c2813a!249df7a0583417db3f02bd934084d2fa' } ] public transactionResult = { transactions: [ { hash: 'e5785a893c7fc3adb7b5c31026cbf8abb59bab1a09989d8f4fff67963de1064b', from: ['1NDyJtNTjmwk5xPNhjgAMu4HDHigtobu1s', '1NDyJtNTjmwk5xPNhjgAMu4HDHigtobu1s'], to: [ '1EWYGkA7WfvJxBFwk4B4qNtjXHinbBG7Um', '3Qa1qpKGmBcEQXVRFhjKGdVVNhuuRKdcS4', '38ziQS6rVB7DCvvocswEPJkc5vH2zzg8DQ', '3FVhYoGQDR1qtYiLY26zvivQQNyqXb81XD', '12Gffh8SVQEHt1KgyuKpL9JfTe84K5k8mu', '3G1oSVGiB5WDDAuK4yNXFrVNRGHWHsK5aZ', '3AMA8TRLx7LRvgaPMXDvKS14TQrg36QijU', '1KPBHXiCQ9yZ2CJmLo7HpBG1vs675ivz3o', '1JgLnhs6eB6b5dtNEDDaX8LDzrfEzSkZVW', '3NiRhh4V4Pm4wCuLqLJN1NGHwVmQq7rM5z', '1AMaW6fzuz6Np2KB7eRrv1dSEYeffXNfn1', '39KoX6qxHHGcGUAooAA5a9AW6W1g5CQBKf', '16GGJpscpKPXeuRwWtR1HbGmKkkaVDgMq9' ], isInbound: true, amount: '9584316', fee: '79600', blockHeight: 649920, protocolIdentifier: 'btc', network: { name: 'Mainnet', type: 'MAINNET', rpcUrl: '', blockExplorer: { blockExplorer: 'https://live.blockcypher.com/btc' }, extras: {} }, timestamp: 1601034739 }, { hash: '8859b4c7a8d1b5ce921301630203b3b58703c4c324fa568c73a8ea7cdfa8630d', from: ['3FVhYoGQDR1qtYiLY26zvivQQNyqXb81XD', '3PswdY2pgWBrbx2Eg5kmJLV3HgTBA6z2jF'], to: ['14sdXZcacodeg1TV992xhpXb51FnF6eJ6G', '3QpMdwyHJAiwTrap8Q4foKXso3sBSniD1t'], isInbound: false, amount: '147958402', fee: '4512', blockHeight: 620423, protocolIdentifier: 'btc', network: { name: 'Mainnet', type: 'MAINNET', rpcUrl: '', blockExplorer: { blockExplorer: 'https://live.blockcypher.com/btc' }, extras: {} }, timestamp: 1583466141 } ], cursor: { offset: 2 } } public nextTransactionResult = { transactions: [ { hash: '72df92f031ee47f75ce3e1fcf5377a844fc636e359a9338c70920ccea939a785', from: ['14xKAdxwvjCAyzhPZvRZRHMdpUqKbnetVD', '38nbkw1c5kVJvE6ZzuKBYdKfMQd5MYNusX', '1KT7JVS92BkRkEPWGwAD9pAgQrJKmnUR1F'], to: ['3HDS7wmufAvmRLfEh48CjCB2XqqHN2M3YJ', '3FVhYoGQDR1qtYiLY26zvivQQNyqXb81XD'], isInbound: true, amount: '147920000', fee: '1395', blockHeight: 617775, protocolIdentifier: 'btc', network: { name: 'Mainnet', type: 'MAINNET', rpcUrl: '', blockExplorer: { blockExplorer: 'https://live.blockcypher.com/btc' }, extras: { indexerApi: 'https://insight.bitpay.com', network: { messagePrefix: '\u0018Bitcoin Signed Message:\n', bech32: 'bc', bip32: { public: 76067358, private: 76066276 }, pubKeyHash: 0, scriptHash: 5, wif: 128, coin: 'btc', hashFunctions: {} } } }, timestamp: 1581943495 }, { hash: '1eb83fb1d61e07968bc0f5daf7c1586293df222947a1c320254da7a93babfdc7', from: ['31vBBCBPkCPHpCV618Lr61myaFzQs35cm8', '3FVhYoGQDR1qtYiLY26zvivQQNyqXb81XD'], to: ['159PiitWiC7q3wYXYx5qmPr4xcpJjjkhS5', '3PswdY2pgWBrbx2Eg5kmJLV3HgTBA6z2jF'], isInbound: false, amount: '148042914', fee: '8460', blockHeight: 617204, protocolIdentifier: 'btc', network: { name: 'Mainnet', type: 'MAINNET', rpcUrl: '', blockExplorer: { blockExplorer: 'https://live.blockcypher.com/btc' }, extras: {} }, timestamp: 1581598043 } ], cursor: { offset: 4 } } }
the_stack
import React from 'react'; import {StreamEvent} from '../../Event/StreamEvent'; import {IssueRepo} from '../../Repository/IssueRepo'; import {IssueEvent} from '../../Event/IssueEvent'; import {UserPrefRepo} from '../../Repository/UserPrefRepo'; import {StreamPolling} from '../../Repository/Polling/StreamPolling'; import {SubscriptionIssuesRepo} from '../../Repository/SubscriptionIssuesRepo'; import {StreamEntity} from '../../Library/Type/StreamEntity'; import {SortQueryEntity} from './IssuesHeaderFragment'; import {IssueEntity} from '../../Library/Type/IssueEntity'; import styled from 'styled-components'; import {IssueRow} from '../../Library/View/IssueRow'; import {IssueUpdatedBannerFragment} from './IssueUpdatedBannerFragment'; import {TimerUtil} from '../../Library/Util/TimerUtil'; import {ScrollView} from '../../Library/View/ScrollView'; import {Loading} from '../../Library/View/Loading'; import {appTheme} from '../../Library/Style/appTheme'; import {IssueIPC} from '../../../IPC/IssueIPC'; import {border, fontWeight, space} from '../../Library/Style/layout'; import {StreamId, StreamRepo} from '../../Repository/StreamRepo'; import {View} from '../../Library/View/View'; import {IssuesHeaderFragment} from './IssuesHeaderFragment'; import {Icon} from '../../Library/View/Icon'; import {color} from '../../Library/Style/color'; import {Text} from '../../Library/View/Text'; import {ClickView} from '../../Library/View/ClickView'; import {BrowserEvent} from '../../Event/BrowserEvent'; import {HorizontalResizer} from '../../Library/View/HorizontalResizer'; import {StreamIconLoadingAnim} from '../../Library/View/StreamRow'; type Props = { className?: string; } type State = { stream: StreamEntity | null; filterQuery: string; sortQuery: SortQueryEntity; page: number; end: boolean; issues: IssueEntity[]; totalCount: number, selectedIssue: IssueEntity; loading: boolean; updatedIssueIds: number[]; fadeInIssueIds: number[]; findingForSelectedIssue: boolean, width: number; } const MIN_WIDTH = 320; export class IssuesFragment extends React.Component<Props, State> { static defaultProps = {className: ''}; state: State = { stream: null, filterQuery: '', sortQuery: 'sort:updated', page: -1, end: false, issues: [], totalCount: 0, selectedIssue: null, loading: false, findingForSelectedIssue: false, updatedIssueIds: [], fadeInIssueIds: [], width: UserPrefRepo.getPref().general.style.issuesWidth || MIN_WIDTH, }; private scrollView: ScrollView; private lock: boolean = false; private issueRowRefs: {[issueId: number]: IssueRow} = {}; componentDidMount() { StreamEvent.onSelectStream(this, (stream, issue, noEmitSelectIssue) => { this.setState({stream, page: -1, end: false, filterQuery: stream.userFilter, selectedIssue: null, updatedIssueIds: []}, async () => { await this.loadIssues(); if (issue) await this.handleSelectIssue(issue, noEmitSelectIssue); }); }); StreamEvent.onFinishFirstSearching(this, async (streamId) => { if (this.state.stream?.id === streamId) { const {error, stream} = await StreamRepo.getStream(streamId); if (error) return console.error(error); this.setState({stream}); } }); // IssueEvent.onSelectIssue(this, (issue) => this.handleSelectIssue(issue)); IssueEvent.onUpdateIssues(this, (issues) => this.handleUpdateIssues(issues)); IssueEvent.onReadAllIssues(this, () => this.handleReloadIssuesWithUnselectIssue()); IssueIPC.onReloadIssues(() => this.handleReloadIssuesWithUnselectIssue()); IssueIPC.onSelectNextIssue(() => this.handleSelectNextPrevIssue(1)); IssueIPC.onSelectNextUnreadIssue(() => this.handleSelectNextPrevIssue(1, true)); IssueIPC.onSelectPrevIssue(() => this.handleSelectNextPrevIssue(-1)); IssueIPC.onSelectPrevUnreadIssue(() => this.handleSelectNextPrevIssue(-1, true)); IssueIPC.onToggleRead(() => this.handleToggleRead(this.state.selectedIssue)); IssueIPC.onToggleArchive(() => this.handleToggleArchive(this.state.selectedIssue)); IssueIPC.onToggleMark(() => this.handleToggleMark(this.state.selectedIssue)); IssueIPC.onFilterToggleUnread(() => this.handleToggleFilter('is:unread')); IssueIPC.onFilterToggleOpen(() => this.handleToggleFilter('is:open')); IssueIPC.onFilterToggleMark(() => this.handleToggleFilter('is:bookmark')); IssueIPC.onFilterToggleAuthor(() => this.handleToggleFilter(`author:${UserPrefRepo.getUser().login}`)); IssueIPC.onFilterToggleAssignee(() => this.handleToggleFilter(`assignee:${UserPrefRepo.getUser().login}`)); IssueIPC.onClearFilter(() => this.handleExecFilterQuery('')); } componentWillUnmount() { StreamEvent.offAll(this); IssueEvent.offAll(this); } private async loadIssues() { if (this.lock) return; if (!this.state.stream) return; if (this.state.end) return; const stream = this.state.stream; const page = this.state.page + 1; // note: filterQueryに`sort:ORDER`が含まれる場合もがある。 // なのでsortQueryよりもfilterQueryを優先するために、filterQueryを後ろにしてある。 const filters = [ stream.defaultFilter, this.state.sortQuery, this.state.filterQuery, ]; if (UserPrefRepo.getPref().general.onlyUnreadIssue) filters.push('is:unread'); this.setState({loading: true}); this.lock = true; const {error, issues, totalCount} = await IssueRepo.getIssuesInStream(stream.queryStreamId, filters.join(' '), '', page); this.lock = false; this.setState({loading: false}); if (error) return console.error(error); const end = issues.length === 0; if (page === 0) { this.scrollView.scrollTop(); this.setState({issues, page, end, totalCount}); } else { // streamの更新タイミングによってはissueが重複してしまう。 // なので現在のissueから重複するものを除外しておく const newIssueIds = issues.map(issue => issue.id); const currentIssues = this.state.issues.filter(issue => !newIssueIds.includes(issue.id)); const allIssues = [...currentIssues, ...issues]; this.setState({issues: allIssues, page, end, totalCount}); } } // 外部から指定されたissueを選択状態にする場合、読み込み済みのissuesの中にない可能性がある。 // なので追加のページを読み込み、issueを探すメソッドを用意した。 private async findSelectedIssue(selectedIssueId: number): Promise<IssueEntity | null> { let selectedIssue: IssueEntity = null; do { selectedIssue = this.state.issues.find(issue => issue.id === selectedIssueId); if (selectedIssue) { this.setState({findingForSelectedIssue: false}); return selectedIssue; } this.setState({findingForSelectedIssue: true}); await this.loadIssues(); } while(!this.state.end) return null; } private handleReloadIssuesWithUnselectIssue() { this.setState({page: -1, end: false, selectedIssue: null, updatedIssueIds: []}, () => { this.loadIssues(); }); } private async handleReloadWithUpdatedIssueIds() { const fadeInIssueIds = this.state.updatedIssueIds; this.setState({page: -1, end: false, updatedIssueIds: []}, async () => { await this.loadIssues(); this.setState({fadeInIssueIds}); await TimerUtil.sleep(1000); this.setState({fadeInIssueIds: []}); }); } private handleLoadMore() { this.loadIssues(); } private handleUpdateIssues(updatedIssues: IssueEntity[]) { const issues = this.state.issues.map(issue => { const updatedIssue = updatedIssues.find(updatedIssue => updatedIssue.id === issue.id); return updatedIssue || issue; }); this.setState({issues}); } private async handleUpdateIssueIdsFromBanner(updatedIssueIds: number[]) { this.setState({updatedIssueIds}); const {error, issues} = await IssueRepo.getIssues(updatedIssueIds); if (error) return console.error(error); this.handleUpdateIssues(issues); } private async handleSelectIssue(targetIssue: IssueEntity, noEmitSelectIssue: boolean = false, throttling: boolean = false) { const selectedIssue = await this.findSelectedIssue(targetIssue.id); if (!selectedIssue) { return console.error(`not found targetIssue. targetIssue.id = ${targetIssue.id}, stream.id = ${this.state.stream.id}`); } this.setState({selectedIssue}); const {error, issue: updatedIssue} = await IssueRepo.updateRead(targetIssue.id, new Date()); if (error) return console.error(error); // issuesにある古いissueを差し替える const issues = this.state.issues.map(issue => issue.id === updatedIssue.id ? updatedIssue : issue); // issueを見たので、更新通知(updatedIssueIds)から除外する const updatedIssueIds = this.state.updatedIssueIds.filter(issueId => issueId !== updatedIssue.id); this.setState({issues, updatedIssueIds}); IssueEvent.emitUpdateIssues([updatedIssue], [targetIssue], 'read'); if (!noEmitSelectIssue) { // J/Kのキーリピートによって高速でissue選択された場合を考慮して、スロットリングする if (throttling) { await TimerUtil.sleep(100); if (this.state.selectedIssue.id === targetIssue.id) { IssueEvent.emitSelectIssue(updatedIssue, targetIssue.read_body); } } else { IssueEvent.emitSelectIssue(updatedIssue, targetIssue.read_body); } } } private async handleSelectNextPrevIssue(direction: 1 | -1, skipReadIssue?: boolean) { if (!this.state.issues.length) return; // まだissueが選択されていない場合、最初のissueを選択状態にする if (!this.state.selectedIssue) { await this.handleSelectIssue(this.state.issues[0]); return; } const currentIndex = this.state.issues.findIndex(issue => issue.id === this.state.selectedIssue.id); if (currentIndex < 0) return; let targetIndex; if (skipReadIssue) { for (let i = currentIndex + direction; this.state.issues[i]; i += direction) { const issue = this.state.issues[i]; if (IssueRepo.isRead(issue)) continue; targetIndex = i; break; } } else { targetIndex = currentIndex + direction; } const issue = this.state.issues[targetIndex]; if (issue) await this.handleSelectIssue(issue, false, true); } private handleExecFilterQuery(filterQuery: string) { this.setState({filterQuery, page: -1, end: false}, () => this.loadIssues()); } private handleExecSortQuery(sortQuery: SortQueryEntity) { this.setState({sortQuery, page: -1, end: false}, () => this.loadIssues()); } private handleToggleFilter(filter: string) { const regExp = new RegExp(` *${filter} *`); const matched = this.state.filterQuery.match(regExp); let filterQuery: string; if (matched) { filterQuery = this.state.filterQuery.replace(regExp, ' ').trim(); } else { filterQuery = `${this.state.filterQuery} ${filter}`.trim(); } this.setState({filterQuery, end: false, page: -1, selectedIssue: null, updatedIssueIds: []}, () => { this.loadIssues(); }); } private handleToggleFilterIssueType(issue: IssueEntity) { const filters: string[] = [ `is:${issue.type}`, `is:${issue.closed_at ? 'closed' : 'open'}`, ]; if (issue.type === 'pr') { filters.push(`is:${issue.draft ? 'draft' : 'undraft'}`); filters.push(`is:${issue.merged_at ? 'merged' : 'unmerged'}`); } this.handleToggleFilter(filters.join(' ')); } private handleFilterProject(_issue: IssueEntity, projectName: string, projectColumn: string) { const filter1 = projectName.includes(' ') ? `project-name:"${projectName}"` : `project-name:${projectName}`; const filter2 = projectColumn?.includes(' ') ? `project-column:"${projectColumn}"` : `project-column:${projectColumn}`; if (projectColumn) { this.handleToggleFilter(`${filter1} ${filter2}`); } else { this.handleToggleFilter(`${filter1}`); } } private handleFilterMilestone(issue: IssueEntity) { const milestone = issue.value.milestone.title; let filter: string; if (milestone.includes(' ')) { filter = `milestone:"${milestone}"`; } else { filter = `milestone:${milestone}`; } this.handleToggleFilter(filter); } private handleFilterLabel(_issue: IssueEntity, label: string) { let filter: string; if (label.includes(' ')) { filter = `label:"${label}"`; } else { filter = `label:${label}`; } this.handleToggleFilter(filter); } private handleFilterAuthor(issue: IssueEntity) { this.handleToggleFilter(`author:${issue.author}`); } private handleFilterAssignee(_issue: IssueEntity, assignee: string) { this.handleToggleFilter(`assignee:${assignee}`); } private handleFilterReviewRequested(_issue: IssueEntity, loginName: string) { this.handleToggleFilter(`review-requested:${loginName}`); } private handleFilterReview(_issue: IssueEntity, loginName: string) { this.handleToggleFilter(`review:${loginName}`); } private handleFilterRepoOrg(issue: IssueEntity) { this.handleToggleFilter(`org:${issue.user}`); } private handleFilterRepoName(issue: IssueEntity) { this.handleToggleFilter(`repo:${issue.repo}`); } private handleFilterIssueNumber(issue: IssueEntity) { this.handleToggleFilter(`number:${issue.number}`); } private async handleToggleMark(targetIssue: IssueEntity | null) { if (!targetIssue) return; const date = targetIssue.marked_at ? null : new Date(); const {error, issue: updatedIssue} = await IssueRepo.updateMark(targetIssue.id, date); if (error) return console.error(error); this.handleUpdateIssues([updatedIssue]); if (this.state.selectedIssue?.id === updatedIssue.id) this.setState({selectedIssue: updatedIssue}); IssueEvent.emitUpdateIssues([updatedIssue], [targetIssue], 'mark'); } private async handleToggleRead(targetIssue: IssueEntity | null) { if (!targetIssue) return; const date = IssueRepo.isRead(targetIssue) ? null : new Date(); const {error, issue: updatedIssue} = await IssueRepo.updateRead(targetIssue.id, date); if (error) return console.error(error); this.handleUpdateIssues([updatedIssue]); if (this.state.selectedIssue?.id === updatedIssue.id) this.setState({selectedIssue: updatedIssue}); IssueEvent.emitUpdateIssues([updatedIssue], [targetIssue], 'read'); } private async handleToggleArchive(targetIssue: IssueEntity | null) { if (!targetIssue) return; const date = targetIssue.archived_at ? null : new Date(); const {error, issue: updatedIssue} = await IssueRepo.updateArchive(targetIssue.id, date); if (error) return console.error(error); const issues = this.state.issues.filter(issue => issue.id !== updatedIssue.id); this.setState({issues}); if (this.state.selectedIssue?.id === updatedIssue.id) this.setState({selectedIssue: updatedIssue}); IssueEvent.emitUpdateIssues([updatedIssue], [targetIssue], 'archive'); } private async handleUnsubscribe(targetIssue: IssueEntity) { const url = targetIssue.value.html_url; const {error} = await SubscriptionIssuesRepo.unsubscribe(url); if (error) return console.error(error); const issues = this.state.issues.filter(issue => issue.id !== targetIssue.id); this.setState({issues}); await StreamPolling.refreshStream(StreamId.subscription); StreamEvent.emitReloadAllStreams(); } private async handleCreateFilterStream() { StreamEvent.emitCreateFilterStream(this.state.stream.queryStreamId, this.state.filterQuery); } private async handleReadAll() { if (confirm(`Would you like to mark "${this.state.stream.name}" all as read?`)) { const stream = this.state.stream; const {error} = await IssueRepo.updateReadAll(stream.queryStreamId, stream.defaultFilter, stream.userFilter); if (error) return console.error(error); IssueEvent.emitReadAllIssues(stream.id); } } private async handleReadCurrent() { if (confirm('Would you like to mark current issues as read?')) { const oldIssues = [...this.state.issues]; const issueIds = this.state.issues.map(issue => issue.id); const {error, issues} = await IssueRepo.updateReads(issueIds, new Date()); if (error) return console.error(error); const newIssues = oldIssues.map(oldIssue => { const newIssue = issues.find(issue => issue.id === oldIssue.id); return newIssue || oldIssue; }); this.setState({issues: newIssues}); IssueEvent.emitUpdateIssues(issues, oldIssues, 'read'); } } private handleOpenProjectBoard() { if (this.state.stream?.type === 'ProjectStream') BrowserEvent.emitOpenProjectBoard(this.state.stream); } private handleResize(diff: number) { const width = Math.max(this.state.width + diff, MIN_WIDTH); this.setState({width}); } private handleWriteWidth() { const pref = UserPrefRepo.getPref(); pref.general.style.issuesWidth = this.state.width; UserPrefRepo.updatePref(pref); } render() { const loadingClassName = this.state.loading && this.state.page === -1 ? 'issues-first-page-loading' : ''; const findingClassName = this.state.findingForSelectedIssue ? 'issues-finding-selected-issue' : ''; return ( <Root className={`${loadingClassName} ${findingClassName} ${this.props.className}`} style={{width: this.state.width}}> <IssuesHeaderFragment stream={this.state.stream} issueCount={this.state.totalCount} filterQuery={this.state.filterQuery} sortQuery={this.state.sortQuery} onExecFilter={filterQuery => this.handleExecFilterQuery(filterQuery)} onExecToggleFilter={filterQuery => this.handleToggleFilter(filterQuery)} onExecSort={sortQuery => this.handleExecSortQuery(sortQuery)} /> {this.renderInitialLoadingBanner()} {this.renderProjectBanner()} <IssuesScrollView onEnd={() => this.handleLoadMore()} ref={ref => this.scrollView = ref} > {this.renderUpdatedBanner()} {this.renderIssues()} {this.renderLoading()} </IssuesScrollView> <HorizontalResizer onResize={diff => this.handleResize(diff)} onEnd={() => this.handleWriteWidth()}/> </Root> ); } private renderInitialLoadingBanner() { if (!this.state.stream) return; if (!['UserStream', 'SystemStream', 'ProjectStream'].includes(this.state.stream.type)) return; if (this.state.stream.searchedAt) return; return ( <InitialLoadingBanner> <StreamIconLoadingAnim className='stream-first-loading'> <Icon name={this.state.stream.iconName} color={color.white}/> </StreamIconLoadingAnim> <InitialLoadingBannerText>Currently initial loading...</InitialLoadingBannerText> </InitialLoadingBanner> ); } private renderProjectBanner() { if (this.state.stream?.type !== 'ProjectStream') return; return ( <ProjectBanner onClick={() => this.handleOpenProjectBoard()}> <ProjectBannerLabel>Browse "</ProjectBannerLabel> <Icon name={this.state.stream.iconName} color={color.white}/> <ProjectBannerLabel>{this.state.stream.name}"</ProjectBannerLabel> </ProjectBanner> ); } private renderUpdatedBanner() { return ( <IssueUpdatedBannerFragment stream={this.state.stream} filter={this.state.filterQuery} updatedIssueIds={this.state.updatedIssueIds} onChange={updatedIssueIds => this.handleUpdateIssueIdsFromBanner(updatedIssueIds)} onClick={() => this.handleReloadWithUpdatedIssueIds()} /> ); } private renderIssues() { return this.state.issues.map(issue => { const fadeIn = this.state.fadeInIssueIds.includes(issue.id); const selected = issue.id === this.state.selectedIssue?.id; let onUnsubscribe = null; if (this.state.stream.id === StreamId.subscription) { onUnsubscribe = (issue: IssueEntity) => this.handleUnsubscribe(issue); } let onCreateFilterStream = null; if (this.state.stream.type === 'UserStream' || this.state.stream.type === 'FilterStream') { onCreateFilterStream = () => this.handleCreateFilterStream(); } return ( <IssueRow key={issue.id} issue={issue} selected={selected} fadeIn={fadeIn} skipHandlerSameCheck={true} scrollIntoViewIfNeededWithCenter={true} onSelect={issue => this.handleSelectIssue(issue)} onToggleIssueType={issue => this.handleToggleFilterIssueType(issue)} onToggleProject={(issue, projectName, projectColumn) => this.handleFilterProject(issue, projectName, projectColumn)} onToggleMilestone={issue => this.handleFilterMilestone(issue)} onToggleLabel={(issue, label) => this.handleFilterLabel(issue, label)} onToggleAuthor={issue => this.handleFilterAuthor(issue)} onToggleAssignee={(issue, assignee) => this.handleFilterAssignee(issue, assignee)} onToggleReviewRequested={(issue, loginName) => this.handleFilterReviewRequested(issue, loginName)} onToggleReview={(issue, loginName) => this.handleFilterReview(issue, loginName)} onToggleRepoOrg={issue => this.handleFilterRepoOrg(issue)} onToggleRepoName={issue => this.handleFilterRepoName(issue)} onToggleIssueNumber={issue => this.handleFilterIssueNumber(issue)} onToggleMark={issue => this.handleToggleMark(issue)} onToggleArchive={issue => this.handleToggleArchive(issue)} onToggleRead={issue => this.handleToggleRead(issue)} onReadAll={() => this.handleReadAll()} onReadCurrentAll={() => this.handleReadCurrent()} onUnsubscribe={onUnsubscribe} onCreateFilterStream={onCreateFilterStream} ref={ref => this.issueRowRefs[issue.id] = ref} /> ); }); } private renderLoading() { const show = this.state.loading && this.state.page > -1; return <Loading show={show}/>; } } const Root = styled(View)` position: relative; height: 100%; background: ${() => appTheme().bg.primary}; border-right: solid ${border.medium}px ${() => appTheme().border.normal}; `; const InitialLoadingBanner = styled(View)` border-bottom: solid ${border.medium}px ${() => appTheme().border.normal}; flex-direction: row; align-items: center; color: ${color.white}; background: ${() => appTheme().accent.normal}; padding: ${space.medium}px ${space.medium2}px; `; const InitialLoadingBannerText = styled(Text)` padding-left: ${space.medium}px; color: ${color.white}; `; const ProjectBanner = styled(ClickView)` flex-direction: row; align-items: center; justify-content: center; background: ${() => appTheme().accent.normal}; padding: ${space.medium}px; border-bottom: solid ${border.medium}px ${() => appTheme().border.normal}; `; const ProjectBannerLabel = styled(Text)` color: ${color.white}; font-weight: ${fontWeight.bold}; `; const IssuesScrollView = styled(ScrollView)` flex: 1; .issues-first-page-loading & { opacity: 0.3; } .issues-finding-selected-issue & { opacity: 0.3; } `;
the_stack
import { common, ContractParameterTypeJSON, scriptHashToAddress, StorageItem, StorageItemJSON, } from '@neo-one/client-common'; import { Modifiable } from '@neo-one/utils'; import { toArray } from '@reactivex/ix-es2015-cjs/asynciterable/toarray'; import { data, factory, keys, verifyDataProvider as verify } from '../../__data__'; import { convertAction, JSONRPCClient, JSONRPCHTTPProvider, NEOONEDataProvider } from '../../provider'; jest.mock('../../provider/JSONRPCClient'); describe('NEOONEDataProvider', () => { const network = 'local'; const rpcURL = 'https://neotracker.io/rpc'; let client: Modifiable<JSONRPCClient>; let provider: NEOONEDataProvider; beforeEach(() => { provider = new NEOONEDataProvider({ network, rpcURL }); // tslint:disable-next-line no-any client = (provider as any).mutableClient; }); test('setRPCURL', () => { const currentClient = client; provider.setRPCURL('http://localhost:1340'); // tslint:disable-next-line no-any expect(currentClient).not.toBe((provider as any).mutableClient); }); test('getUnclaimed', async () => { client.getUnclaimedGas = jest.fn(async () => Promise.resolve({ unclaimed: data.bigNumbers.a.toString(10), address: keys[0].address }), ); const result = await provider.getUnclaimed(keys[0].address); expect(result).toEqual(data.bigNumbers.a); }); test('relayTransaction', async () => { const transactionWithInvocationDataJSON = factory.createTransactionWithInvocationDataJSON(); client.relayTransaction = jest.fn(async () => Promise.resolve({ transaction: transactionWithInvocationDataJSON, }), ); const result = await provider.relayTransaction(factory.createTransactionModel()); verify.verifyTransaction(result.transaction, transactionWithInvocationDataJSON); }); test('verifyConvertTransaction', async () => { const transactionJSON = factory.createTransactionWithInvocationDataJSON(); const actionJSON = factory.createLogActionJSON(); const verificationScriptJSON = factory.createVerifyScriptResultJSON({ failureMessage: 'test', actions: [actionJSON], }); const verifyResultJSON = factory.createVerifyTransactionResultJSON({ verifications: [verificationScriptJSON], }); client.relayTransaction = jest.fn(async () => Promise.resolve({ transaction: transactionJSON, verifyResult: verifyResultJSON, }), ); const result = await provider.relayTransaction(factory.createTransactionModel()); if (result.verifyResult === undefined) { throw new Error('for TS'); } expect(result.verifyResult.verifications).toEqual([ { failureMessage: 'test', witness: verificationScriptJSON.witness, address: scriptHashToAddress(verificationScriptJSON.hash), actions: [ convertAction(common.uInt256ToString(common.ZERO_UINT256), -1, transactionJSON.hash, -1, 0, actionJSON), ], }, ]); }); test('getTransactionReceipt', async () => { const transactionReceipt = factory.createTransactionReceipt(); // tslint:disable-next-line:no-any client.getTransactionReceipt = jest.fn(async () => Promise.resolve(transactionReceipt) as any); const result = await provider.getTransactionReceipt(data.hash256s.a); expect(result).toEqual(transactionReceipt); }); test('getInvocationData', async () => { const transactionJSON = factory.createTransactionWithInvocationDataJSON(); const invocationData = transactionJSON.invocationData; const transactionData = transactionJSON.data; if (invocationData === undefined || transactionData === undefined) { throw new Error('Something went wrong'); } client.getInvocationData = jest.fn(async () => Promise.resolve(invocationData)); client.getTransaction = jest.fn(async () => Promise.resolve(transactionJSON)); const result = await provider.getInvocationData(data.hash256s.a); verify.verifyDefaultActions( result.actions, invocationData.actions, transactionData.blockIndex, transactionData.blockHash, transactionData.transactionIndex, transactionJSON.hash, ); const notificationAction = result.actions[0]; const notificationActionJSON = invocationData.actions[0]; if (notificationAction.type !== 'Notification' || notificationActionJSON.type !== 'Notification') { throw new Error('For TS'); } expect(notificationAction.args.length).toEqual(notificationActionJSON.args.length); const firstArg = notificationAction.args[0]; const firstArgJSON = notificationActionJSON.args[0]; if (firstArg.type !== 'Integer' || firstArgJSON.type !== 'Integer') { throw new Error('For TS'); } expect(firstArg.value.toString(10)).toEqual(firstArgJSON.value); const logAction = result.actions[1]; const logActionJSON = invocationData.actions[1]; if (logAction.type !== 'Log' || logActionJSON.type !== 'Log') { throw new Error('For TS'); } expect(logAction.message).toEqual(logActionJSON.message); expect(result.contracts.length).toEqual(invocationData.contracts.length); verify.verifyContract(result.contracts[0], invocationData.contracts[0]); expect(result.deletedContractAddresses.length).toEqual(invocationData.deletedContractHashes.length); expect(result.deletedContractAddresses[0]).toEqual(scriptHashToAddress(invocationData.deletedContractHashes[0])); expect(result.migratedContractAddresses.length).toEqual(invocationData.migratedContractHashes.length); expect(result.migratedContractAddresses[0][0]).toEqual( scriptHashToAddress(invocationData.migratedContractHashes[0][0]), ); expect(result.migratedContractAddresses[0][1]).toEqual( scriptHashToAddress(invocationData.migratedContractHashes[0][1]), ); verify.verifyInvocationResultSuccess(result.result, invocationData.result); }); test('getInvocationData - missing transaction data', async () => { const { data: _data, ...transactionJSON } = factory.createTransactionWithInvocationDataJSON(); // tslint:disable:no-any client.getInvocationData = jest.fn(async () => Promise.resolve(transactionJSON.invocationData) as any); client.getTransaction = jest.fn((async () => Promise.resolve(transactionJSON)) as any); // tslint:enable:no-any await expect(provider.getInvocationData(data.hash256s.a)).rejects.toMatchSnapshot(); }); test('testInvoke', async () => { const callReceiptJSON = factory.createCallReceiptJSON(); client.testInvocation = jest.fn(async () => Promise.resolve(callReceiptJSON)); const result = await provider.testInvoke(factory.createTransactionModel()); verify.verifyCallReceipt(result, callReceiptJSON); }); test('getBlock', async () => { const blockJSON = factory.createBlockJSON(); client.getBlock = jest.fn(async () => Promise.resolve(blockJSON)); const result = await provider.getBlock(10); expect(result.version).toEqual(blockJSON.version); expect(result.previousBlockHash).toEqual(blockJSON.previousblockhash); expect(result.merkleRoot).toEqual(blockJSON.merkleroot); expect(result.time).toEqual(blockJSON.time); expect(result.index).toEqual(blockJSON.index); expect(result.nextConsensus).toEqual(blockJSON.nextconsensus); expect(result.witnesses.length).toEqual(blockJSON.witnesses.length); expect(result.witnesses).toEqual(blockJSON.witnesses); expect(result.hash).toEqual(blockJSON.hash); expect(result.witness).toEqual(blockJSON.witnesses[0]); expect(result.size).toEqual(blockJSON.size); expect(result.transactions.length).toEqual(blockJSON.tx.length); verify.verifyTransaction(result.transactions[0], blockJSON.tx[0]); verify.verifyConfirmedTransaction(result.transactions[0], blockJSON.tx[0]); }); test('iterBlocks', async () => { const blockJSON = factory.createBlockJSON(); client.getBlockCount = jest.fn(async () => Promise.resolve(2)); client.getBlock = jest.fn(async () => Promise.resolve(blockJSON)); const result = await toArray(provider.iterBlocks({ indexStart: 1, indexStop: 2 })); expect(result.length).toEqual(1); }); test('getBestBlockHash', async () => { const hash = data.hash256s.a; client.getBestBlockHash = jest.fn(async () => Promise.resolve(hash)); const result = await provider.getBestBlockHash(); expect(result).toEqual(hash); }); test('getBlockCount', async () => { const count = 2; client.getBlockCount = jest.fn(async () => Promise.resolve(count)); const result = await provider.getBlockCount(); expect(result).toEqual(count); }); test('getContract', async () => { const contractJSON = factory.createContractJSON(); client.getContract = jest.fn(async () => Promise.resolve(contractJSON)); const result = await provider.getContract(keys[0].address); verify.verifyContract(result, contractJSON); }); const convertedContractParameterTypes = [ ['Any', 'Any'], ['Signature', 'Signature'], ['Boolean', 'Boolean'], ['Integer', 'Integer'], ['Hash160', 'Hash160'], ['Hash256', 'Hash256'], ['ByteArray', 'Buffer'], ['PublicKey', 'PublicKey'], ['String', 'String'], ['Array', 'Array'], ['InteropInterface', 'InteropInterface'], ['Void', 'Void'], ]; convertedContractParameterTypes.forEach(([from, to]) => { test(`getContract - ${from} -> ${to}`, async () => { const contractJSON = factory.createContractJSON({ manifest: { abi: { methods: [ { name: `test ${from}`, returnType: from as ContractParameterTypeJSON, offset: 0, parameters: [] }, ], }, // tslint:disable-next-line: no-any } as any, }); client.getContract = jest.fn(async () => Promise.resolve(contractJSON)); const result = await provider.getContract(keys[0].address); verify.verifyContract(result, contractJSON, to); }); }); test('getMemPool', async () => { const memPool = [data.hash256s.a]; client.getMemPool = jest.fn(async () => Promise.resolve(memPool)); const result = await provider.getMemPool(); expect(result).toEqual(memPool); }); test('getTransaction', async () => { const transactionJSON = factory.createTransactionJSON(); client.getTransaction = jest.fn(async () => Promise.resolve(transactionJSON)); const result = await provider.getTransaction(transactionJSON.hash); verify.verifyTransaction(result, transactionJSON); }); test('getConnectedPeers', async () => { const peersJSON = [factory.createPeerJSON()]; client.getConnectedPeers = jest.fn(async () => Promise.resolve(peersJSON)); const result = await provider.getConnectedPeers(); expect(result).toEqual(peersJSON); }); test('getNetworkSettings', async () => { const networkSettingsJSON = factory.createNetworkSettingsJSON(); client.getNetworkSettings = jest.fn(async () => Promise.resolve(networkSettingsJSON)); const result = await provider.getNetworkSettings(); expect(result.issueGASFee.toString(10)).toEqual(networkSettingsJSON.issueGASFee); }); const verifyStorage = (item: StorageItem, itemJSON: StorageItemJSON) => { expect(item.address).toEqual(keys[0].address); expect(item.key).toEqual(data.buffers.a); expect(item.value).toEqual(itemJSON.value); }; test('iterStorage', async () => { const storageItemJSON = factory.createStorageItemJSON(); client.getAllStorage = jest.fn(async () => Promise.resolve([storageItemJSON])); const result = await toArray(provider.iterStorage(keys[0].address)); expect(result).toHaveLength(1); verifyStorage(result[0], storageItemJSON); }); test('iterActionsRaw', async () => { const blockJSON = factory.createBlockJSON(); client.getBlockCount = jest.fn(async () => Promise.resolve(2)); client.getBlock = jest.fn(async () => Promise.resolve(blockJSON)); const result = await toArray(provider.iterActionsRaw({ indexStart: 1, indexStop: 2 })); expect(result.length).toEqual(2); const transactionJSON = blockJSON.tx[4]; if (transactionJSON.data === undefined || transactionJSON.invocationData === undefined) { throw new Error('For TS'); } verify.verifyDefaultActions( result, transactionJSON.invocationData.actions, transactionJSON.data.blockIndex, transactionJSON.data.blockHash, transactionJSON.data.transactionIndex, transactionJSON.hash, ); }); test('call', async () => { const callReceiptJSON = factory.createCallReceiptJSON(); client.testInvocation = jest.fn(async () => Promise.resolve(callReceiptJSON)); const result = await provider.call(keys[0].address, 'foo', []); verify.verifyCallReceipt(result, callReceiptJSON); }); test('runConsensusNow', async () => { const runConsensusNow = jest.fn(async () => Promise.resolve()); client.runConsensusNow = runConsensusNow; await provider.runConsensusNow(); expect(runConsensusNow).toHaveBeenCalled(); }); test('updateSettings', async () => { const updateSettings = jest.fn(async () => Promise.resolve()); client.updateSettings = updateSettings; const options = { secondsPerBlock: 10 }; await provider.updateSettings(options); expect(updateSettings).toHaveBeenCalledWith(options); }); test('fastForwardOffset', async () => { const fastForwardOffset = jest.fn(async () => Promise.resolve()); client.fastForwardOffset = fastForwardOffset; const options = 10; await provider.fastForwardOffset(options); expect(fastForwardOffset).toHaveBeenCalledWith(options); }); test('fastForwardToTime', async () => { const fastForwardToTime = jest.fn(async () => Promise.resolve()); client.fastForwardToTime = fastForwardToTime; const options = 10; await provider.fastForwardToTime(options); expect(fastForwardToTime).toHaveBeenCalledWith(options); }); test('reset', async () => { const reset = jest.fn(async () => Promise.resolve()); client.reset = reset; await provider.reset(); expect(reset).toHaveBeenCalled(); }); test('construction with rpcURL provider works', () => { provider = new NEOONEDataProvider({ network, rpcURL: new JSONRPCHTTPProvider(rpcURL) }); expect(provider).toBeDefined(); }); });
the_stack
import * as db from '../util/db'; export type SchemaKindType = 'primary'|'app'|'category'|'discovery'|'other'; export interface Row { id : number; kind : string; kind_type : SchemaKindType; owner : number; developer_version : number; approved_version : number|null; kind_canonical : string; } export type OptionalFields = 'kind_type' | 'owner' | 'approved_version' | 'kind_canonical'; export interface ChannelRow { schema_id : number; version : number; name : string; channel_type : 'trigger'|'action'|'query'; extends : string|null; types : string; argnames : string; required : string; is_input : string; string_values : string; doc : string; is_list : boolean; is_monitorable : boolean; confirm : boolean; } export type ChannelOptionalFields = 'is_list' | 'is_monitorable' | 'confirm'; export interface ChannelCanonicalRow { schema_id : number; version : number; language : string; name : string; canonical : string; confirmation : string|null; confirmation_remote : string|null; formatted : string|null; questions : string; argcanonicals : string; } export type ChannelCanonicalOptionalFields = 'language' | 'confirmation' | 'confirmation_remote' | 'formatted'; export interface TranslationRecord { canonical : string; confirmation : string; confirmation_remote ?: string; formatted : unknown[]; argcanonicals : unknown[]; questions : string[]; } export async function insertTranslations(dbClient : db.Client, schemaId : number, version : number, language : string, translations : Record<string, TranslationRecord>) { const channelCanonicals : Array<[number, number, string, string, string, string, string, string, string, string]> = []; for (const name in translations) { const meta = translations[name]; channelCanonicals.push([schemaId, version, language, name, meta.canonical, meta.confirmation, meta.confirmation_remote || meta.confirmation, JSON.stringify(meta.formatted), JSON.stringify(meta.argcanonicals), JSON.stringify(meta.questions)]); } if (channelCanonicals.length === 0) return Promise.resolve(); return db.insertOne(dbClient, 'replace into device_schema_channel_canonicals(schema_id, version, language, name, ' + 'canonical, confirmation, confirmation_remote, formatted, argcanonicals, questions) values ?', [channelCanonicals]); } export interface SchemaChannelMetadata { canonical : string; confirmation : string|null; confirmation_remote : string|null; doc : string; extends : string[]|null; types : string[]; args : string[]; required : boolean[]; is_input : boolean[]; string_values : Array<string|null>; formatted : unknown[]; argcanonicals : unknown[]; questions : string[]; is_list : boolean; is_monitorable : boolean; confirm : boolean; } export interface SchemaMetadata { kind : string; kind_type : SchemaKindType; kind_canonical : string; triggers : Record<string, SchemaChannelMetadata>; queries : Record<string, SchemaChannelMetadata>; actions : Record<string, SchemaChannelMetadata>; } export interface SchemaChannelTypes { extends ?: string[]; types : string[]; args : string[]; required : boolean[]; is_input : boolean[]; is_list : boolean; is_monitorable : boolean; } export interface SchemaTypes { kind : string; kind_type : SchemaKindType; triggers : Record<string, SchemaChannelTypes>; queries : Record<string, SchemaChannelTypes>; actions : Record<string, SchemaChannelTypes>; } export async function insertChannels(dbClient : db.Client, schemaId : number, schemaKind : string, kindType : SchemaKindType|undefined, version : number, language : string, metas : SchemaMetadata) { const channels : Array<[number, number, string, 'trigger'|'query'|'action', string, string|null, string, string, string, string, string, boolean, boolean, boolean]> = []; const channelCanonicals : Array<[number, number, string, string, string, string|null, string|null, string, string, string]> = []; function makeList(what : 'trigger'|'query'|'action', from : Record<string, SchemaChannelMetadata>) { for (const name in from) { const meta = from[name]; channels.push([schemaId, version, name, what, meta.doc, meta.extends && meta.extends.length ? JSON.stringify(meta.extends) : null, JSON.stringify(meta.types), JSON.stringify(meta.args), JSON.stringify(meta.required), JSON.stringify(meta.is_input), JSON.stringify(meta.string_values), !!meta.is_list, !!meta.is_monitorable, !!meta.confirm]); channelCanonicals.push([schemaId, version, language, name, meta.canonical, meta.confirmation, meta.confirmation_remote, JSON.stringify(meta.formatted), JSON.stringify(meta.argcanonicals), JSON.stringify(meta.questions)]); } } makeList('trigger', metas.triggers || {}); makeList('query', metas.queries || {}); makeList('action', metas.actions || {}); if (channels.length === 0) return Promise.resolve(); return db.insertOne(dbClient, 'insert into device_schema_channels(schema_id, version, name, ' + 'channel_type, doc, extends, types, argnames, required, is_input, string_values, is_list, is_monitorable, confirm) values ?', [channels]) .then(() => { return db.insertOne(dbClient, 'insert into device_schema_channel_canonicals(schema_id, version, language, name, ' + 'canonical, confirmation, confirmation_remote, formatted, argcanonicals, questions) values ?', [channelCanonicals]); }); } export async function create<T extends db.Optional<Row, OptionalFields>>(client : db.Client, schema : db.WithoutID<T>, meta : SchemaMetadata) : Promise<db.WithID<T>> { const KEYS = ['kind', 'kind_canonical', 'kind_type', 'owner', 'approved_version', 'developer_version'] as const; const vals = KEYS.map((key) => schema[key]); const marks = KEYS.map(() => '?'); return db.insertOne(client, 'insert into device_schema(' + KEYS.join(',') + ') ' + 'values (' + marks.join(',') + ')', vals).then((id) => { schema.id = id; return insertChannels(client, id, schema.kind, schema.kind_type, schema.developer_version, 'en', meta); }).then(() => schema as db.WithID<T>); } export async function update<T extends Partial<Row> & { developer_version : number }>(client : db.Client, id : number, kind : string, schema : T, meta : SchemaMetadata) : Promise<db.WithID<T>> { return db.query(client, "update device_schema set ? where id = ?", [schema, id]).then(() => { return insertChannels(client, id, kind, schema.kind_type, schema.developer_version, 'en', meta); }).then(() => { schema.id = id; return schema as db.WithID<T>; }); } function processMetaRows(rows : Array<Row & ChannelRow & ChannelCanonicalRow>) { const out : SchemaMetadata[] = []; let current : SchemaMetadata|null = null; rows.forEach((row) => { if (current === null || current.kind !== row.kind) { current = { kind: row.kind, kind_type: row.kind_type, kind_canonical: row.kind_canonical, triggers: {}, queries: {}, actions: {} }; out.push(current); } if (row.channel_type === null) return; const types = JSON.parse(row.types); const obj : SchemaChannelMetadata = { extends: JSON.parse(row.extends || 'null'), types: types, args: JSON.parse(row.argnames), required: JSON.parse(row.required) || [], is_input: JSON.parse(row.is_input) || [], is_list: !!row.is_list, is_monitorable: !!row.is_monitorable, confirm: !!row.confirm, confirmation: row.confirmation, confirmation_remote: row.confirmation_remote || row.confirmation, // for compatibility formatted: JSON.parse(row.formatted || '[]'), doc: row.doc, canonical: row.canonical, argcanonicals: JSON.parse(row.argcanonicals) || [], questions: JSON.parse(row.questions) || [], string_values: JSON.parse(row.string_values) || [], }; if (obj.args.length < types.length) { for (let i = obj.args.length; i < types.length; i++) obj.args[i] = 'arg' + (i+1); } switch (row.channel_type) { case 'action': current.actions[row.name] = obj; break; case 'trigger': current.triggers[row.name] = obj; break; case 'query': current.queries[row.name] = obj; break; default: throw new TypeError(); } }); return out; } function processTypeRows(rows : Array<Row & ChannelRow>) { const out : SchemaTypes[] = []; let current : SchemaTypes|null = null; rows.forEach((row) => { if (current === null || current.kind !== row.kind) { current = { kind: row.kind, kind_type: row.kind_type, triggers: {}, queries: {}, actions: {} }; out.push(current); } if (row.channel_type === null) return; const obj : SchemaChannelTypes = { extends: JSON.parse(row.extends || 'null'), types: JSON.parse(row.types), args: JSON.parse(row.argnames), required: JSON.parse(row.required), is_input: JSON.parse(row.is_input), is_list: !!row.is_list, is_monitorable: !!row.is_monitorable, }; switch (row.channel_type) { case 'action': current.actions[row.name] = obj; break; case 'trigger': current.triggers[row.name] = obj; break; case 'query': current.queries[row.name] = obj; break; default: throw new TypeError(); } }); return out; } export async function get(client : db.Client, id : number) : Promise<Row> { return db.selectOne(client, "select * from device_schema where id = ?", [id]); } export async function findNonExisting(client : db.Client, ids : string[], org : number) : Promise<string[]> { if (ids.length === 0) return Promise.resolve([]); const rows : Array<{ kind : string }> = await db.selectAll(client, `select kind from device_schema where kind in (?) and (owner = ? or approved_version is not null or exists (select 1 from organizations where organizations.id = ? and is_admin))`, [ids, org, org]); if (rows.length === ids.length) return []; const existing = new Set(rows.map((r) => r.kind)); const missing : string[] = []; for (const id of ids) { if (!existing.has(id)) missing.push(id); } return missing; } export async function getAllApproved(client : db.Client, org : number|null) : Promise<Array<{ kind : string, kind_canonical : string }>> { if (org === -1) { return db.selectAll(client, `select kind, kind_canonical from device_schema where kind_type in ('primary','other')`, []); } else if (org !== null) { return db.selectAll(client, `select kind, kind_canonical from device_schema where (approved_version is not null or owner = ?) and kind_type in ('primary','other')`, [org]); } else { return db.selectAll(client, `select kind, kind_canonical from device_schema where approved_version is not null and kind_type in ('primary','other')`, []); } } export async function getCurrentSnapshotTypes(client : db.Client, org : number|null) : Promise<SchemaTypes[]> { if (org === -1) { return db.selectAll(client, `select name, extends, types, argnames, required, is_input, is_list, is_monitorable, channel_type, kind, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and dsc.version = ds.developer_version`, []).then(processTypeRows); } else if (org !== null) { return db.selectAll(client, `select name, extends, types, argnames, required, is_input, is_list, is_monitorable, channel_type, kind, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and ((dsc.version = ds.developer_version and ds.owner = ?) or (dsc.version = ds.approved_version and ds.owner <> ?)) where (ds.approved_version is not null or ds.owner = ?)`, [org, org, org]).then(processTypeRows); } else { return db.selectAll(client, `select name, extends, types, argnames, required, is_input, is_list, is_monitorable, channel_type, kind, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and dsc.version = ds.approved_version where ds.approved_version is not null`, []).then(processTypeRows); } } export async function getCurrentSnapshotMeta(client : db.Client, language : string, org : number|null) : Promise<SchemaMetadata[]> { if (org === -1) { return db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, is_list, is_monitorable, string_values, questions, confirm, kind, kind_canonical, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and dsc.version = ds.developer_version left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ?`, [language]).then(processMetaRows); } else if (org !== null) { return db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, is_list, is_monitorable, string_values, questions, confirm, kind, kind_canonical, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and ((dsc.version = ds.developer_version and ds.owner = ?) or (dsc.version = ds.approved_version and ds.owner <> ?)) left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ? where (ds.approved_version is not null or ds.owner = ?)`, [org, org, language, org]).then(processMetaRows); } else { return db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, is_list, is_monitorable, string_values, questions, confirm, kind, kind_canonical, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and dsc.version = ds.approved_version left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ? where ds.approved_version is not null`, [language]).then(processMetaRows); } } export async function getSnapshotTypes(client : db.Client, snapshotId : number, org : number|null) : Promise<SchemaTypes[]> { if (org === -1) { return db.selectAll(client, `select name, extends, types, argnames, required, is_input, is_list, is_monitorable, channel_type, kind, kind_type from device_schema_snapshot ds left join device_schema_channels dsc on ds.schema_id = dsc.schema_id and dsc.version = ds.developer_version and ds.snapshot_id = ?`, [snapshotId]).then(processTypeRows); } else if (org !== null) { return db.selectAll(client, `select name, extends, types, argnames, required, is_input, is_list, is_monitorable, channel_type, kind, kind_type from device_schema_snapshot ds left join device_schema_channels dsc on ds.schema_id = dsc.schema_id and ((dsc.version = ds.developer_version and ds.owner = ?) or (dsc.version = ds.approved_version and ds.owner <> ?)) where (ds.approved_version is not null or ds.owner = ?) and ds.snapshot_id = ?`, [org, org, org, snapshotId]).then(processTypeRows); } else { return db.selectAll(client, `select name, extends, types, argnames, required, is_input, is_list, is_monitorable, channel_type, kind, kind_type from device_schema_snapshot ds left join device_schema_channels dsc on ds.schema_id = dsc.schema_id and dsc.version = ds.approved_version where ds.approved_version is not null and ds.snapshot_id = ?`, [snapshotId]).then(processTypeRows); } } export async function getSnapshotMeta(client : db.Client, snapshotId : number, language : string, org : number|null) : Promise<SchemaMetadata[]> { if (org === -1) { return db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, is_list, is_monitorable, string_values, questions, confirm, kind, kind_canonical, kind_type from device_schema_snapshot ds left join device_schema_channels dsc on ds.schema_id = dsc.schema_id and dsc.version = ds.developer_version left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ? and ds.snapshot_id = ?`, [language, snapshotId]).then(processMetaRows); } else if (org !== null) { return db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, is_list, is_monitorable, string_values, questions, confirm, kind, kind_canonical, kind_type from device_schema_snapshot ds left join device_schema_channels dsc on ds.schema_id = dsc.schema_id and ((dsc.version = ds.developer_version and ds.owner = ?) or (dsc.version = ds.approved_version and ds.owner <> ?)) left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ? where (ds.approved_version is not null or ds.owner = ?) and ds.snapshot_id = ?`, [org, org, language, org, snapshotId]).then(processMetaRows); } else { return db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, is_list, is_monitorable, string_values, questions, confirm, kind, kind_canonical, kind_type from device_schema_snapshot ds left join device_schema_channels dsc on ds.schema_id = dsc.schema_id and dsc.version = ds.approved_version left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ? where ds.approved_version is not null and ds.snapshot_id = ?`, [language, snapshotId]).then(processMetaRows); } } export async function getByKind(client : db.Client, kind : string) : Promise<Row> { return db.selectOne(client, "select * from device_schema where kind = ?", [kind]); } export async function getTypesAndNamesByKinds(client : db.Client, kinds : string[], org : number|null) : Promise<SchemaTypes[]> { let rows; if (org === -1) { rows = await db.selectAll(client, `select name, extends, types, argnames, required, is_input, is_list, is_monitorable, channel_type, kind, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and dsc.version = ds.developer_version where ds.kind in (?)`, [kinds]); } else if (org !== null) { rows = await db.selectAll(client, `select name, extends, types, argnames, required, is_input, is_list, is_monitorable, channel_type, kind, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and ((dsc.version = ds.developer_version and ds.owner = ?) or (dsc.version = ds.approved_version and ds.owner <> ?)) where ds.kind in (?) and (ds.approved_version is not null or ds.owner = ?)`, [org, org, kinds, org]); } else { rows = await db.selectAll(client, `select name, extends, types, argnames, required, is_input, is_list, is_monitorable, channel_type, kind, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and dsc.version = ds.approved_version where ds.kind in (?) and ds.approved_version is not null`, [kinds]); } return processTypeRows(rows); } export async function getMetasByKinds(client : db.Client, kinds : string[], org : number|null, language : string) : Promise<SchemaMetadata[]> { let rows; if (org === -1) { rows = await db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, string_values, is_list, is_monitorable, questions, confirm, kind, kind_canonical, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and dsc.version = ds.developer_version left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ? where ds.kind in (?)`, [language, kinds]); } else if (org !== null) { rows = await db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, string_values, is_list, is_monitorable, questions, confirm, kind, kind_canonical, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and ((dsc.version = ds.developer_version and ds.owner = ?) or (dsc.version = ds.approved_version and ds.owner <> ?)) left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ? where ds.kind in (?) and (ds.approved_version is not null or ds.owner = ?)`, [org, org, language, kinds, org]); } else { rows = await db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, string_values, is_list, is_monitorable, questions, confirm, kind, kind_canonical, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and dsc.version = ds.approved_version left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ? where ds.kind in (?) and ds.approved_version is not null`, [language, kinds]); } return processMetaRows(rows); } export async function getMetasByKindAtVersion(client : db.Client, kind : string, version : number, language : string) : Promise<SchemaMetadata[]> { const rows = await db.selectAll(client, `select dsc.name, channel_type, extends, canonical, confirmation, confirmation_remote, formatted, doc, types, argnames, argcanonicals, required, is_input, string_values, is_list, is_monitorable, questions, confirm, kind, kind_canonical, kind_type from device_schema ds left join device_schema_channels dsc on ds.id = dsc.schema_id and dsc.version = ? left join device_schema_channel_canonicals dscc on dscc.schema_id = dsc.schema_id and dscc.version = dsc.version and dscc.name = dsc.name and dscc.language = ? where ds.kind = ?`, [version, language, kind]); return processMetaRows(rows); } export async function isKindTranslated(client : db.Client, kind : string, language : string) : Promise<boolean> { return db.selectOne(client, " select" + " (select count(*) from device_schema_channel_canonicals, device_schema" + " where language = 'en' and id = schema_id and version = developer_version" + " and kind = ?) as english_count, (select count(*) from " + "device_schema_channel_canonicals, device_schema where language = ? and " + "version = developer_version and id = schema_id and kind = ?) as translated_count", [kind, language, kind]).then((row : { english_count : number, translated_count : number }) => { return row.english_count <= row.translated_count; }); } async function _delete(client : db.Client, id : number) : Promise<void> { await db.query(client, "delete from device_schema where id = ?", [id]); } export { _delete as delete }; export async function deleteByKind(client : db.Client, kind : string) : Promise<void> { await db.query(client, "delete from device_schema where kind = ?", [kind]); } export async function approve(client : db.Client, id : number) : Promise<void> { await db.query(client, "update device_schema set approved_version = developer_version where id = ?", [id]); } export async function approveByKind(dbClient : db.Client, kind : string) : Promise<void> { await db.query(dbClient, "update device_schema set approved_version = developer_version where kind = ?", [kind]); } export async function unapproveByKind(dbClient : db.Client, kind : string) : Promise<void> { await db.query(dbClient, "update device_schema set approved_version = null where kind = ?", [kind]); }
the_stack
import sinon from 'sinon'; import { expect } from 'chai'; import { factory, testInjector } from '@stryker-mutator/test-helpers'; import { CompleteDryRunResult } from '@stryker-mutator/api/test-runner'; import { Mutant, MutantStatus, MutantTestCoverage } from '@stryker-mutator/api/core'; import { Reporter } from '@stryker-mutator/api/report'; import { findMutantTestCoverage as sut } from '../../../src/mutants/find-mutant-test-coverage'; import { coreTokens } from '../../../src/di'; describe(sut.name, () => { let reporterMock: sinon.SinonStubbedInstance<Required<Reporter>>; beforeEach(() => { reporterMock = factory.reporter(); }); function act(dryRunResult: CompleteDryRunResult, mutants: Mutant[]) { return testInjector.injector .provideValue(coreTokens.reporter, reporterMock) .provideValue(coreTokens.dryRunResult, dryRunResult) .provideValue(coreTokens.mutants, mutants) .injectFunction(sut); } it('should not match ignored mutants to any tests', () => { const mutant = factory.mutant({ id: '2', status: MutantStatus.Ignored, statusReason: 'foo should ignore' }); const dryRunResult = factory.completeDryRunResult({ mutantCoverage: { static: {}, perTest: { '1': { 2: 2 } } } }); // Act const result = act(dryRunResult, [mutant]); // Assert const expected: MutantTestCoverage[] = [{ ...mutant, estimatedNetTime: 0, static: false, hitCount: 2 }]; expect(result).deep.eq(expected); }); it('should mark mutant as "NoCoverage" when there is coverage data, but none for the specific mutant', () => { const mutant = factory.mutant({ id: '3' }); const dryRunResult = factory.completeDryRunResult({ mutantCoverage: { static: {}, perTest: { '1': { 2: 2 } } } }); // Act const result = act(dryRunResult, [mutant]); // Assert const expected: MutantTestCoverage[] = [{ ...mutant, estimatedNetTime: 0, static: false, coveredBy: [], hitCount: undefined }]; expect(result).deep.eq(expected); }); describe('without mutant coverage data', () => { it('should mark mutants as "static"', () => { // Arrange const mutant1 = factory.mutant({ id: '1' }); const mutant2 = factory.mutant({ id: '2' }); const mutants = [mutant1, mutant2]; const dryRunResult = factory.completeDryRunResult({ mutantCoverage: undefined }); // Act const result = act(dryRunResult, mutants); // Assert const expected: MutantTestCoverage[] = [ { ...mutant1, estimatedNetTime: 0, coveredBy: undefined, static: true, hitCount: undefined }, { ...mutant2, estimatedNetTime: 0, coveredBy: undefined, static: true, hitCount: undefined }, ]; expect(result).deep.eq(expected); }); it('should calculate estimatedNetTime as the sum of all tests', () => { // Arrange const mutant1 = factory.mutant({ id: '1' }); const mutants = [mutant1]; const dryRunResult = factory.completeDryRunResult({ tests: [factory.successTestResult({ timeSpentMs: 20 }), factory.successTestResult({ timeSpentMs: 22 })], mutantCoverage: undefined, }); // Act const result = act(dryRunResult, mutants); // Assert expect(result[0].estimatedNetTime).eq(42); }); it('should report onAllMutantsMatchedWithTests', () => { // Arrange const mutants = [ factory.mutant({ id: '1', fileName: 'foo.js', mutatorName: 'fooMutator', replacement: '<=', location: { start: { line: 0, column: 0 }, end: { line: 0, column: 1 } }, }), factory.mutant({ id: '2', fileName: 'bar.js', mutatorName: 'barMutator', replacement: '{}', location: { start: { line: 0, column: 2 }, end: { line: 0, column: 3 } }, }), ]; const dryRunResult = factory.completeDryRunResult({ tests: [factory.successTestResult({ timeSpentMs: 20 }), factory.successTestResult({ timeSpentMs: 22 })], mutantCoverage: undefined, }); // Act act(dryRunResult, mutants); // Assert expect(reporterMock.onAllMutantsMatchedWithTests).calledWithExactly([ factory.mutantTestCoverage({ id: '1', fileName: 'foo.js', mutatorName: 'fooMutator', replacement: '<=', static: true, estimatedNetTime: 42, location: { start: { line: 0, column: 0 }, end: { line: 0, column: 1 } }, hitCount: undefined, }), factory.mutantTestCoverage({ id: '2', fileName: 'bar.js', mutatorName: 'barMutator', replacement: '{}', static: true, estimatedNetTime: 42, location: { start: { line: 0, column: 2 }, end: { line: 0, column: 3 } }, hitCount: undefined, }), ]); }); }); describe('with static coverage', () => { it('should disable test filtering', () => { // Arrange const mutant = factory.mutant({ id: '1' }); const mutants = [mutant]; const dryRunResult = factory.completeDryRunResult({ tests: [factory.successTestResult({ id: 'spec1', timeSpentMs: 0 })], mutantCoverage: { static: { 1: 1 }, perTest: {} }, }); // Act const result = act(dryRunResult, mutants); // Assert const expected: MutantTestCoverage[] = [{ ...mutant, estimatedNetTime: 0, static: true, coveredBy: undefined, hitCount: 1 }]; expect(result).deep.eq(expected); }); it('should calculate the hitCount based on total hits (perTest and static)', () => { // Arrange const mutant = factory.mutant({ id: '1' }); const mutants = [mutant]; const dryRunResult = factory.completeDryRunResult({ tests: [factory.successTestResult({ id: 'spec1', timeSpentMs: 0 })], mutantCoverage: { static: { 1: 1 }, perTest: { 1: { 1: 2, 2: 100 }, 2: { 2: 100 }, 3: { 1: 3 } } }, }); // Act const result = act(dryRunResult, mutants); // Assert expect(result[0].hitCount).deep.eq(6); }); it('should calculate estimatedNetTime as the sum of all tests', () => { // Arrange const mutant = factory.mutant({ id: '1' }); const mutants = [mutant]; const dryRunResult = factory.completeDryRunResult({ tests: [factory.successTestResult({ id: 'spec1', timeSpentMs: 20 }), factory.successTestResult({ id: 'spec1', timeSpentMs: 22 })], mutantCoverage: { static: { 1: 1 }, perTest: {} }, }); // Act const result = act(dryRunResult, mutants); // Assert expect(result[0].estimatedNetTime).eq(42); }); it('should report onAllMutantsMatchedWithTests with correct `static` value', () => { // Arrange const mutants = [factory.mutant({ id: '1' }), factory.mutant({ id: '2' })]; const dryRunResult = factory.completeDryRunResult({ tests: [factory.successTestResult()], mutantCoverage: { static: { 1: 1 }, perTest: {} }, // mutant 2 has no coverage }); // Act act(dryRunResult, mutants); // Assert const expectedFirstMatch: Partial<MutantTestCoverage> = { id: '1', static: true, coveredBy: undefined, }; const expectedSecondMatch: Partial<MutantTestCoverage> = { id: '2', static: false, coveredBy: [], }; expect(reporterMock.onAllMutantsMatchedWithTests).calledWithMatch([sinon.match(expectedFirstMatch), sinon.match(expectedSecondMatch)]); }); }); describe('with perTest coverage', () => { it('should enable test filtering for covered tests', () => { // Arrange const mutant1 = factory.mutant({ id: '1' }); const mutant2 = factory.mutant({ id: '2' }); const mutants = [mutant1, mutant2]; const dryRunResult = factory.completeDryRunResult({ tests: [factory.successTestResult({ id: 'spec1', timeSpentMs: 0 }), factory.successTestResult({ id: 'spec2', timeSpentMs: 0 })], mutantCoverage: { static: { 1: 0 }, perTest: { spec1: { 1: 1 }, spec2: { 1: 0, 2: 1 } } }, }); // Act const result = act(dryRunResult, mutants); // Assert const expected: MutantTestCoverage[] = [ { ...mutant1, estimatedNetTime: 0, coveredBy: ['spec1'], static: false, hitCount: 1 }, { ...mutant2, estimatedNetTime: 0, coveredBy: ['spec2'], static: false, hitCount: 1 }, ]; expect(result).deep.eq(expected); }); it('should calculate estimatedNetTime as the sum of covered tests', () => { // Arrange const mutant1 = factory.mutant({ id: '1' }); const mutant2 = factory.mutant({ id: '2' }); const mutants = [mutant1, mutant2]; const dryRunResult = factory.completeDryRunResult({ tests: [ factory.successTestResult({ id: 'spec1', timeSpentMs: 20 }), factory.successTestResult({ id: 'spec2', timeSpentMs: 10 }), factory.successTestResult({ id: 'spec3', timeSpentMs: 22 }), ], mutantCoverage: { static: { 1: 0 }, perTest: { spec1: { 1: 1 }, spec2: { 1: 0, 2: 1 }, spec3: { 1: 2 } } }, }); // Act const actualMatches = act(dryRunResult, mutants); // Assert expect(actualMatches.find((mutant) => mutant.id === '1')?.estimatedNetTime).eq(42); // spec1 + spec3 expect(actualMatches.find((mutant) => mutant.id === '2')?.estimatedNetTime).eq(10); // spec2 }); it('should report onAllMutantsMatchedWithTests with correct `testFilter` value', () => { // Arrange const mutants = [factory.mutant({ id: '1' }), factory.mutant({ id: '2' })]; const dryRunResult = factory.completeDryRunResult({ tests: [factory.successTestResult({ id: 'spec1', timeSpentMs: 0 }), factory.successTestResult({ id: 'spec2', timeSpentMs: 0 })], mutantCoverage: { static: { 1: 0 }, perTest: { spec1: { 1: 1 }, spec2: { 1: 0, 2: 1 } } }, }); // Act act(dryRunResult, mutants); // Assert const expectedFirstMatch: Partial<MutantTestCoverage> = { id: '1', static: false, coveredBy: ['spec1'], }; const expectedSecondMatch: Partial<MutantTestCoverage> = { id: '2', static: false, coveredBy: ['spec2'], }; expect(reporterMock.onAllMutantsMatchedWithTests).calledWithMatch([sinon.match(expectedFirstMatch), sinon.match(expectedSecondMatch)]); }); it('should allow for non-existing tests (#2485)', () => { // Arrange const mutant1 = factory.mutant({ id: '1' }); const mutant2 = factory.mutant({ id: '2' }); const mutants = [mutant1, mutant2]; const dryRunResult = factory.completeDryRunResult({ tests: [factory.successTestResult({ id: 'spec1', timeSpentMs: 20 })], // test result for spec2 is missing mutantCoverage: { static: {}, perTest: { spec1: { 1: 1 }, spec2: { 1: 0, 2: 1 } } }, }); // Act const actualMatches = act(dryRunResult, mutants); // Assert expect(actualMatches.find((mutant) => mutant.id === '1')?.coveredBy).deep.eq(['spec1']); expect(actualMatches.find((mutant) => mutant.id === '2')?.coveredBy).lengthOf(0); expect(testInjector.logger.debug).calledWith( 'Found test with id "spec2" in coverage data, but not in the test results of the dry run. Not taking coverage data for this test into account' ); }); }); });
the_stack
import { AdaptElement, AdaptMountedElement, AnyProps, Handle, isElement, isHandle, isMountedElement, useState } from "@adpt/core"; import * as yaml from "js-yaml"; import ld from "lodash"; import * as util from "util"; import { DockerSplitRegistryInfo } from "../docker"; import { EnvSimple, mergeEnvSimple } from "../env"; import { ClusterInfo, Kubeconfig, ResourcePod, ResourceProps } from "./common"; import { kubectl } from "./kubectl"; import { isResource, Resource } from "./Resource"; /** * Options for {@link k8s.makeClusterInfo} * * @public */ export interface MakeClusterInfoOptions { /** * A Javascript Object representing a valid kubeconfig, or a YAML string, or a path to a kubeconfig file. * * @remarks * If this is a Javascript object, it will be treated like a parsed kubeconfig. If this is a string, * {@link k8s.makeClusterInfo} will first attempt to parse it as JSON. If that fails, it will attempt * to parse it as YAML. If that fails it will treat the string as a path of configs (like with the `KUBECONFIG` * environment variable). * * If kubeconfig is missing {@link k8s.makeClusterInfo} will use the `KUBECONFIG` environment variable to build * a suitable config using `kubectl config view --flatten` and return that as the kubeconfig in the resulting * {@link k8s.ClusterInfo} */ kubeconfig?: Kubeconfig | string; /** * URL to the docker registry that this cluster uses to pull private images. * * @remarks * This is identical to the `registryPrefix` field in {@link k8s.ClusterInfo}. It will * be returned verbatim in the resulting {@link k8s.ClusterInfo} object. */ registryPrefix?: string | DockerSplitRegistryInfo; } async function getKubeconfigFromPath(path: string | undefined): Promise<Kubeconfig> { const kenv: EnvSimple = path ? { KUBECONFIG: path } : {}; const result = await kubectl(["config", "view", "-o", "json", "--flatten"], { env: mergeEnvSimple(process.env as EnvSimple, kenv) }); const json = result.stdout; const ret = JSON.parse(json); if (ret.clusters === null) ret.clusters = []; return ret; } async function getKubeconfig(configStr: string): Promise<Kubeconfig> { const errors: { attempt: string, message: string }[] = []; let kubeconfig: Kubeconfig | any[] | string | undefined; //JSON try { kubeconfig = JSON.parse(configStr); } catch (e) { errors.push({ attempt: "as JSON", message: e.message }); } //FIXME(manishv) better validation of returned data here if ((kubeconfig != null) && !ld.isObject(kubeconfig)) { throw new Error(`Invalid kubeconfig in JSON from ${configStr}`); } if (ld.isArray(kubeconfig)) throw new Error(`Invalid array kubeconfig in JSON from ${configStr}`); if (kubeconfig !== undefined) return kubeconfig; //YAML try { kubeconfig = yaml.safeLoad(configStr) as any; //FIXME(manishv) Put a Kubeconfig schema to validate YAML } catch (e) { errors.push({ attempt: "as YAML", message: e.message }); } if ((kubeconfig != null) && !ld.isObject(kubeconfig)) { if (ld.isString(kubeconfig)) { kubeconfig = undefined; //Try this as a path, since a path will look like a valid YAML } else { throw new Error(`Invalid kubeconfig in YAML from ${configStr}`); } } if (ld.isArray(kubeconfig)) throw new Error(`Invalid array kubeconfig in YAML from ${configStr}`); if (kubeconfig !== undefined) return kubeconfig; try { return getKubeconfigFromPath(configStr); } catch (e) { errors.push({ attempt: "from KUBECONFIG", message: e.message }); } throw new Error(errors.map((e) => `Could not get kubeconfig ${e.attempt}:\n${e.message}\n-------\n`).join("\n")); } /** * Make a {@link k8s.ClusterInfo} object suitable for use with k8s resources * * @remarks * * This function will take a set of options and generate a {@link k8s.ClusterInfo} * object that contains the kubeconfig, registryPrefix for private images, and any other * relevant information for the cluster * * See {@link k8s.MakeClusterInfoOptions} for information on how the information * is computed. * * @returns A {@link k8s.ClusterInfo} object. * * @public */ export async function makeClusterInfo(options: MakeClusterInfoOptions): Promise<ClusterInfo> { const registryPrefix = options.registryPrefix; if (options.kubeconfig === undefined) { return { kubeconfig: await getKubeconfigFromPath(process.env.KUBECONFIG), registryPrefix }; } if (ld.isString(options.kubeconfig)) { return { kubeconfig: await getKubeconfig(options.kubeconfig), registryPrefix }; } if (ld.isObject(options.kubeconfig)) { return { kubeconfig: options.kubeconfig, registryPrefix }; } throw new Error(`Illegal kubeconfig option in ${util.inspect(options)}`); } /** @internal */ export function isResourcePodTemplate(x: any): x is AdaptElement<ResourcePod> { if (!isElement(x)) return false; if (!isResource(x)) return false; if (x.props.apiVersion !== "v1" && x.props.kind === "Pod" && x.props.isTemplate === true) return true; return false; } function isNotReady<ValT, NotReadyT>(x: ValT | NotReadyT, nr: NotReadyT): x is NotReadyT { return ld.isEqual(x, nr); } /** * Hook that allows a prop to be either an array of handle to k8s resources and values * * @param initial - initial value of the prop, before the handles are be resolved * @param notReady - is a marker value to indicate that a handle's value isn't available yet * @param kinds - an array of legal k8s Kinds that a prop handle can point to * @param thisResourceName - the name of the resource using the hook, for error messages * @param propName - the name of the prop being resolved, again for error messages * * @returns A two element array, the first element is the current value, the second the update function * * This hook will start by returning the initial value and an update function that updates * the value the hook returns. The update function takes 2 arguments - the prop value which * is an array with a mix of values and handles to be resolved, and a function that receives * the elements that any handles point to along with that elements props. This function * can be passed by the caller of update to resolve handles as appropriate for the component. * * For example, {@link k8s.ClusterRoleBinding} uses this hook to resolve the subjects prop, * which is an array of other objects (typically {@link ServiceAccount}) that a particular * {@link k8s.ClusterRole} should point to. When ClusterRoleBinding calls the update method, * it passes a function that will convert a {@link k8s.Resource} element of Kind `ServiceAccount` * to the underlying `Subject` object that kubernetes expects, namely * `{ apiGroup: "", kind: "ServiceAccount", name: resourceIdToName(elem, deployID), namespace: <element namespace> }` * * @example * ``` * function MyResource({ serviceAccountNames }: { serviceAccountNames: (string | Handle)[]}) { * const { deployID } = useBuildHelpers(); * const [ resolvedServiceAccountNames, updateSANs] = useResources({ * initial: [], * notReady: null, * kinds: ["ServiceAccount"], * thisResourceName: "MyResources", * propName: "serviceAccountNames", * }); * * updateSANs(serviceAccountNames, (e, props) => { * return { * apiGroup: (e.metadata.apiVersion?.split("/")[0]) || "", * name: resourceElementToName(e, deployID), * namespace: props.metadata.namespace, * } * }); * * return null; * } * ``` * * @beta */ export function useResources<ValT, NotReadyT>({ initial, notReady, kinds, thisResourceName, propName, }: { initial: ValT[], notReady: NotReadyT, kinds: string[], thisResourceName: string, propName: string, }): [ (ValT | NotReadyT)[], (props: (ValT | Handle)[], f: (e: AdaptMountedElement, props: ResourceProps) => Promise<ValT> | ValT) => void ] { const [value, updateState] = useState<(ValT | NotReadyT)[]>(initial); return [ value, (props: (ValT | Handle)[], f: (e: AdaptMountedElement, props: ResourceProps) => Promise<ValT> | ValT) => { updateState(async () => { return Promise.all(props.map(async (prop) => { if (!isHandle(prop)) return prop; if (!prop.target) return notReady; if (!isMountedElement(prop.target)) return notReady; if (prop.target.componentType !== Resource) { throw new Error(`${thisResourceName} cannot handle ${propName} of type ${prop.target.componentType.name}`); } const targetProps: ResourceProps = prop.target.props as AnyProps as ResourceProps; if (!kinds.includes(targetProps.kind)) { throw new Error(`${thisResourceName} cannot handle ${propName} of kind ${targetProps.kind}`); } return f(prop.target, targetProps); })); }); } ]; } /** * Hook to allow conversion of a prop that could be a value or a handle * * This function behaves similarly to {@link k8s.useResources}, but works for * a prop that is either a Handle or a single value instead of an array of * Handles and values. * * See {@link k8s.useResources} for more detailed documentation. * * @beta */ export function useResource<ValT, NotReadyT>(opts: { initial: ValT | NotReadyT, notReady: NotReadyT, kinds: string[], thisResourceName: string, propName: string, }): [ ValT | NotReadyT, (prop: ValT | Handle, f: (e: AdaptMountedElement, props: ResourceProps) => Promise<ValT> | ValT) => void ] { const [vals, update] = useResources<ValT, NotReadyT>({ ...opts, initial: isNotReady(opts.initial, opts.notReady) ? [] : [opts.initial], }); return [ vals[0], (prop, f) => update([prop], f) ]; }
the_stack
import SObject from '../Core/SObject'; import {Vector3, Quaternion} from '../Core/Math'; import RigidBodyComponent, {IRigidBodyComponentState} from '../Physic/RigidBodyComponent'; import ColliderComponent from '../Physic/ColliderComponent'; import SceneActor from '../Renderer/ISceneActor'; import JointComponent from '../Physic/JointComponent'; /** * 支持的碰撞体类型枚举。 */ export enum EColliderType { /** * 没有碰撞体。 */ Null = 0, /** * 球碰撞体。 */ Sphere = 1, /** * 盒碰撞体。 */ Box = 2, /** * 平面碰撞体。 */ Plane = 3, /** * 柱状碰撞体。 */ Cylinder = 4 // todo: support terrain // Terrain = 5, // Particle = 6, // Mesh = 7 } /** * 支持的刚体类型枚举。 */ export enum ERigidBodyType { /** * 动态的,等同于`physicStatic = false`。 */ Dynamic = 1, /** * 静态的,等同于`physicStatic = true`。 */ Static = 2 } /** * 支持的关节类型枚举。 */ export enum EJointType { /** * 点对点约束。 */ PointToPoint = 0, /** * 铰链约束。 */ Hinge = 1, /** * 距离约束。 */ Distance = 2, /** * 弹簧约束。 */ Spring = 3, /** * 锁定约束。 */ Lock = 4 } /** * 支持的拾取模式枚举。 */ export enum EPickMode { /** * 只拾取距离摄像机最近的刚体,性能最佳。 * * @deprecated */ CLOSEST = 1, /** * 只拾取距离摄像机最近的刚体,性能最佳。 */ Closest = 1, /** * 拾取任意的刚体。 */ Any = 2, /** * 拾取所有的刚体。 */ All = 4 } /** * 碰撞体的通用参数。 */ export interface IColliderCommonOptions { /** * 是否是触发器,若是,则只会触发碰撞事件而不会产生物理效应。 */ isTrigger?: boolean; /** * 碰撞体的初始偏移。为 **[x, y, z]**。 */ offset?: number[]; /** * 碰撞体的初始四元数,用于设置旋转偏移。为 **[x, y, z, w]**。 */ quaternion?: number[]; // friction?: number; // restitution?: number; // 默认生成碰撞体的依据 // bindComponent?: SceneComponent; // todo: 绑定到特定Node并跟随变换 // enableBind?: boolean; // todo: 绑定到特定骨骼并跟随变换 // bindBone?: never; } /** * 盒碰撞体的参数。 */ export interface IBoxColliderOptions extends IColliderCommonOptions { /** * 尺寸。为 **[width, height, depth]**。 */ size: number[]; } /** * 球碰撞体的参数。 */ export interface ISphereColliderOptions extends IColliderCommonOptions { /** * 半径。 */ radius: number; } /** * 柱状碰撞体的参数。 */ export interface ICylinderColliderOptions extends IColliderCommonOptions { /** * 上圆面半径。 */ radiusTop: number; /** * 下圆面半径。 */ radiusBottom: number; /** * 高度。 */ height: number; /** * 片段数量。 */ numSegments: number; } /** * 平面碰撞体的参数。 */ export interface IPlaneColliderOptions extends IColliderCommonOptions {} /** * 碰撞体具体的参数。 */ export type TColliderParams = { type: EColliderType.Null, options: IColliderCommonOptions } |{ type: EColliderType.Box, options: IBoxColliderOptions } | { type: EColliderType.Sphere, options: ISphereColliderOptions } | { type: EColliderType.Cylinder, options: ICylinderColliderOptions } | { type: EColliderType.Plane, options: IPlaneColliderOptions }; /** * 关节的通用参数。 */ export interface IJointCommonOptions { /** * 需要约束的、拥有`RigidBody`的`SceneActor`。 */ actor: SceneActor; /** * 是否要合并碰撞体。 * * @default true */ collideConnected?: boolean; /** * 是否要唤醒刚体。 * * @default true */ wakeUpBodies?: boolean; } /** * 点对点约束关节的参数。 */ export interface IPointToPointJointOptions extends IJointCommonOptions { /** * 约束点距离自身Actor质心的偏移。 * * @default [0,0,0] */ pivotA?: Vector3; /** * 约束点距离另一个Actor质心的偏移。 * * @default [0,0,0] */ pivotB?: Vector3; /** * 最大力约束。 * * @default 1e6 */ maxForce?: number; } /** * 铰链约束关节的参数。 */ export interface IHingeJointOptions extends IJointCommonOptions { /** * 自身轴的中心距离质心的偏移。 * * @default [0,0,0] */ pivotA?: Vector3; /** * 自身可以绕着转动的轴。 * * @default [1,0,0] */ axisA?: Vector3; /** * 另一个Actor轴距离质心的偏移。 * * @default [0,0,0] */ pivotB?: Vector3; /** * 另一个Actor可以绕着转动的轴。 * * @default [1,0,0] */ axisB?: Vector3; /** * 最大力约束。 * * @default 1e6 */ maxForce?: number; } /** * 距离约束关节的参数。 */ export interface IDistanceJointOptions extends IJointCommonOptions { /** * 距离约束。 * * @default 初始距离 */ distance?: number; /** * 最大力约束。 * * @default 1e6 */ maxForce?: number; } /** * 弹簧约束关节的参数。 */ export interface ISpringJointOptions extends IJointCommonOptions { /** * 原始长度。 * * @default 1 */ restLength?: number; /** * 刚度。 * * @default 100 */ stiffness?: number; /** * 阻尼。 * * @default 1 */ damping?: number; /** * 自身在世界坐标下的,被弹簧勾住的基准点。 * * @default 初始位置。 */ worldAnchorA?: Vector3; /** * 另一个Actor在世界坐标下的,被弹簧勾住的基准点。 * * @default 初始位置。 */ worldAnchorB?: Vector3; /** * 自身在本地坐标下的,被弹簧勾住的基准点。 * * @default [0,0,0] */ localAnchorA?: Vector3; /** * 另一个Actor在本地坐标下的,被弹簧勾住的基准点。 * * @default [0,0,0] */ localAnchorB?: Vector3; } /** * 锁定约束关节的参数。 */ export interface ILockJointOptions extends IJointCommonOptions { /** * 最大力约束。 * * @default 1e6 */ maxForce?: number; } /** * 关节具体的参数。 */ export type TJointParams = { type: EJointType.PointToPoint, options: IPointToPointJointOptions } |{ type: EJointType.Distance, options: IDistanceJointOptions } | { type: EJointType.Hinge, options: IHingeJointOptions } | { type: EJointType.Spring, options: ISpringJointOptions } | { type: EJointType.Lock, options: ILockJointOptions }; /** * 拾取参数类型接口。 */ export interface IPickOptions { /** * 拾取触发类型,`up`为当鼠标或触摸结束时触发,`down`为开始时触发,`custom`则没有默认的触发器,需要自己通过调用`picker.pick`实现。 * 详见[../../guide/pick.md]。 */ type?: 'up' | 'down' | 'custom'; /** * 拾取模式,详见枚举值定义。 */ mode?: EPickMode; /** * 指定需要进行拾取检测的刚体组件,若不传则检测世界中的所有刚体。是一个性能优化或者限制玩家的方式。 */ bodies?: RigidBodyComponent[]; /** * 一个回调,若指定,则会在每次拾取完成后、触发拾取事件前调用,来筛选出真正预期拾取到的结果。 * 一般用于特殊状况,比如在多个检测对象中筛选出需要的对象。 */ filter?(results: IPickResult[]): IPickResult[]; /** * 当次拾取需要生成的射线长度。 */ rayLength?: number; /** * 是否需要检测碰撞效应。 * * @default false */ checkCollisionResponse?: boolean; /** * 是否需要跳过处于背面的刚体。 * * @default true */ skipBackfaces?: boolean; /** * 生成检测用射线的`filterMask`,也是一个限定玩家的手段。 */ collisionFilterMask?: number; /** * 生成检测用射线的`filterGroup`,也是一个限定玩家的手段。 */ collisionFilterGroup?: number; } /** * 拾取检测的结果。 */ export interface IPickResult { /** * 拾取到的刚体组件的父级Actor实例引用。 */ actor: SceneActor; /** * 拾取到的刚体组件的实例引用。 */ rigidBody: RigidBodyComponent; /** * 拾取到的碰撞体组件的实例引用。 */ collider: ColliderComponent; /** * 拾取到的对象上的点到相机的距离。 */ distance: number; /** * 拾取到的对象上的碰撞点的世界坐标。 */ point: Vector3; } /** * 碰撞事件的参数类型。 */ export interface ICollisionEvent { /** * 自身的刚体组件实例引用。 */ selfBody: RigidBodyComponent; /** * 被自身碰撞到的刚体组件实例引用。 */ otherBody: RigidBodyComponent; /** * 被自身碰撞到的刚体组件的父级Actor实例引用。 */ selfActor: SceneActor; /** * 自身的刚体组件的父级Actor实例引用。 */ otherActor: SceneActor; } /** * 带有碰撞体详情的碰撞事件的参数类型。 */ export interface IColliderCollisionEvent extends ICollisionEvent { /** * 自身的碰撞体组件实例引用。 */ selfCollider: ColliderComponent; /** * 被自身碰撞到的的碰撞体组件实例引用。 */ otherCollider: ColliderComponent; } /** * 物理世界接口,实现其可实现任意物理引擎到Sein.js的桥接。 * 引擎默认实现了一个桥接,若想扩展可以仿照,见[CannonPhysicWorld](../cannonphysicworld)。 */ export interface IPhysicWorld extends SObject { isPhysicWorld: boolean; timeStep: number; setGravity(gravity: Vector3): void; initContactEvents(): void; update(delta?: number, components?: RigidBodyComponent[]): void; applyImpulse(component: RigidBodyComponent, force: Vector3, contactPoint: Vector3): void; applyForce(component: RigidBodyComponent, force: Vector3, contactPoint: Vector3): void; pick( from: Vector3, to: Vector3, onPick: (result: IPickResult[]) => void, options?: IPickOptions ): boolean; clear(): void; createRigidBody(component: RigidBodyComponent, options: IRigidBodyComponentState): any; initEvents(component: RigidBodyComponent): void; removeRigidBody(component: RigidBodyComponent): void; disableRigidBody(component: RigidBodyComponent): void; enableRigidBody(component: RigidBodyComponent): void; createCollider(bodyComp: RigidBodyComponent, colliderComp: ColliderComponent, params: TColliderParams): any; removeCollider(rigidBody: RigidBodyComponent, collider: ColliderComponent): void; createJoint(component: RigidBodyComponent, jointComp: JointComponent, params: TJointParams): any; removeJoint(component: RigidBodyComponent, joint: JointComponent): void; disableJoint(joint: JointComponent): void; enableJoint(joint: JointComponent): void; setRootTransform(component: RigidBodyComponent): void; setRigidBodyTransform(component: RigidBodyComponent, newPosition: Vector3, newRotation: Quaternion, newScale?: Vector3): void; setColliderTransform(component: ColliderComponent, newPosition: Vector3, newRotation: Quaternion, newScale?: Vector3): void; updateBounding(component: RigidBodyComponent): void; setLinearVelocity(component: RigidBodyComponent, velocity: Vector3): void; setAngularVelocity(component: RigidBodyComponent, velocity: Vector3): void; getLinearVelocity(component: RigidBodyComponent): Vector3; getAngularVelocity(component: RigidBodyComponent): Vector3; setBodyMass(component: RigidBodyComponent, mass: number): void; getBodyMass(component: RigidBodyComponent): number; setFilterGroup(component: RigidBodyComponent, group: number): void; getFilterGroup(component: RigidBodyComponent): number; setFilterMask(component: RigidBodyComponent, mask: number): void; getFilterMask(component: RigidBodyComponent): number; setColliderIsTrigger(component: ColliderComponent, isTrigger: boolean): void; getColliderIsTrigger(component: ColliderComponent): boolean; getBodyFriction(component: RigidBodyComponent): number; setBodyFriction(component: RigidBodyComponent, friction: number): void; getBodyRestitution(component: RigidBodyComponent): number; setBodyRestitution(component: RigidBodyComponent, restitution: number): void; sleepBody(component: RigidBodyComponent): void; wakeUpBody(component: RigidBodyComponent): void; setBodyType(component: RigidBodyComponent, type: ERigidBodyType): void; }
the_stack
import { ref } from 'vue'; import { chunk, padEnd, has, keepDecimal } from './helpers'; import { ColorPickerColor, position, ColorInt, HSV, HSVA, RGB, RGBA, HSL, HSLA, Hex, Hexa, Color } from './color-utils-types'; export function isCssColor(color?: string | false): boolean { return !!color && !!color.match(/^(#|var\(--|(rgb|hsl)a?\()/); } export function colorToInt(color: Color): ColorInt { let rgb; if (typeof color === 'number') { rgb = color; } else if (typeof color === 'string') { let c = color[0] === '#' ? color.substring(1) : color; if (c.length === 3) { c = c .split('') .map((char) => char + char) .join(''); } if (c.length !== 6) { // consoleWarn(`'${color}' is not a valid rgb color`) } rgb = parseInt(c, 16); } else { throw new TypeError( `Colors can only be numbers or strings, recieved ${ color == null ? color : color.constructor.name } instead` ); } if (rgb < 0) { // consoleWarn(`Colors cannot be negative: '${color}'`) rgb = 0; } else if (rgb > 0xffffff || isNaN(rgb)) { // consoleWarn(`'${color}' is not a valid rgb color`) rgb = 0xffffff; } return rgb; } export function intToHex(color: ColorInt): string { let hexColor: string = color.toString(16); if (hexColor.length < 6) {hexColor = '0'.repeat(6 - hexColor.length) + hexColor;} return '#' + hexColor; } export function colorToHex(color: Color): string { return intToHex(colorToInt(color)); } /** * Converts HSVA to RGBA. Based on formula from https://en.wikipedia.org/wiki/HSL_and_HSV * * @param color HSVA color as an array [0-360, 0-1, 0-1, 0-1] */ export function HSVAtoRGBA(hsva: HSVA): RGBA { const { h, s, v, a } = hsva; const f = (n: number) => { const k = (n + h / 60) % 6; return v - v * s * Math.max(Math.min(k, 4 - k, 1), 0); }; const rgb = [f(5), f(3), f(1)].map((v) => Math.round(v * 255)); return { r: rgb[0], g: rgb[1], b: rgb[2], a }; } /** * Converts RGBA to HSVA. Based on formula from https://en.wikipedia.org/wiki/HSL_and_HSV * * @param color RGBA color as an array [0-255, 0-255, 0-255, 0-1] */ export function RGBAtoHSVA(rgba: RGBA): HSVA { if (!rgba) {return { h: 0, s: 1, v: 1, a: 1 };} const r = rgba.r / 255; const g = rgba.g / 255; const b = rgba.b / 255; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h = 0; if (max !== min) { if (max === r) { h = 60 * (0 + (g - b) / (max - min)); } else if (max === g) { h = 60 * (2 + (b - r) / (max - min)); } else if (max === b) { h = 60 * (4 + (r - g) / (max - min)); } } if (h < 0) {h = h + 360;} const s = max === 0 ? 0 : (max - min) / max; const hsv = [h, s, max]; return { h: Math.round(hsv[0]), s: hsv[1], v: hsv[2], a: rgba.a }; } export function HSVAtoHSLA(hsva: HSVA): HSLA { const { h, s, v, a } = hsva; const l = v - (v * s) / 2; const sprime = l === 1 || l === 0 ? 0 : (v - l) / Math.min(l, 1 - l); return { h: Math.round(h), s: sprime, l, a }; } export function HSLAtoHSVA(hsl: HSLA): HSVA { const { h, s, l, a } = hsl; const v = l + s * Math.min(l, 1 - l); const sprime = v === 0 ? 0 : 2 - (2 * l) / v; return { h: Math.round(h), s: sprime, v, a }; } export function RGBAtoCSS(rgba: RGBA): string { return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`; } export function RGBtoCSS(rgba: RGBA): string { return RGBAtoCSS({ ...rgba, a: 1 }); } export function RGBAtoHex(rgba: RGBA): Hex { const toHex = (v: number) => { const h = Math.round(v).toString(16); return ('00'.substring(0, 2 - h.length) + h).toUpperCase(); }; return `#${[toHex(rgba.r), toHex(rgba.g), toHex(rgba.b), toHex(Math.round(rgba.a * 255))].join( '' )}`; } export function HexToRGBA(hex: Hex): RGBA { const rgba = chunk(hex.slice(1), 2).map((c: string) => parseInt(c, 16)); return { r: rgba[0], g: rgba[1], b: rgba[2], a: Math.round((rgba[3] / 255) * 100) / 100 }; } export function HexToHSVA(hex: Hex): HSVA { const rgb = HexToRGBA(hex); return RGBAtoHSVA(rgb); } export function HSVAtoHex(hsva: HSVA): Hex { return RGBAtoHex(HSVAtoRGBA(hsva)); } export function parseHex(hex: string): Hex { if (hex.startsWith('#')) { hex = hex.slice(1); } hex = hex.replace(/([^0-9a-f])/gi, 'F'); if (hex.length === 3 || hex.length === 4) { hex = hex .split('') .map((x) => x + x) .join(''); } if (hex.length === 6) { hex = padEnd(hex, 8, 'F'); } else { hex = padEnd(padEnd(hex, 6), 8, 'F'); } return `#${hex}`.toUpperCase().substring(0, 9); } export function RGBtoInt(rgba: RGBA): ColorInt { return (rgba.r << 16) + (rgba.g << 8) + rgba.b; } export function fromHSVA(hsva: HSVA): ColorPickerColor { hsva = { ...hsva }; const hexa = HSVAtoHex(hsva); const hsla = HSVAtoHSLA(hsva); const rgba = HSVAtoRGBA(hsva); return { alpha: hsva.a, hex: hexa.substring(0, 7), hexa, hsla, hsva, hue: hsva.h, rgba }; } export function fromRGBA(rgba: RGBA): ColorPickerColor { const hsva = RGBAtoHSVA(rgba); const hexa = RGBAtoHex(rgba); const hsla = HSVAtoHSLA(hsva); const hsv = { h: hsva.h, s: hsva.s, v: hsva.v }; const hsl = { h: hsla.h, s: hsla.s, l: hsla.l }; return { alpha: hsva.a, hex: hexa.substring(0, 7), hexa, hsla, hsva, hsv, hsl, hue: hsva.h, rgba }; } export function fromHexa(hexa: Hexa): ColorPickerColor { const hsva = HexToHSVA(hexa); const hsla = HSVAtoHSLA(hsva); const rgba = HSVAtoRGBA(hsva); return { alpha: hsva.a, hex: hexa.substring(0, 7), hexa, hsla, hsva, hue: hsva.h, rgba }; } export function fromHSLA(hsla: HSLA): ColorPickerColor { const hsva = HSLAtoHSVA(hsla); const hexa = HSVAtoHex(hsva); const rgba = HSVAtoRGBA(hsva); return { alpha: hsva.a, hex: hexa.substring(0, 7), hexa, hsla, hsva, hue: hsva.h, rgba }; } export function fromHex(hex: Hex): ColorPickerColor { return fromHexa(parseHex(hex)); } export function parseColor(color: Color, oldColor?: ColorPickerColor | null): ColorPickerColor { if (!color) {return fromRGBA({ r: 0, g: 0, b: 0, a: 1 });} if (typeof color === 'string') { if (color.indexOf('#') !== -1) { // const hex = color.replace('#', '').trim() // return fromHexa(hex) } else if (color.indexOf('hsl') !== -1) { let alpha = null; const parts = color .replace(/hsla|hsl|\(|\)/gm, '') .split(/\s|,/g) .filter((val) => val !== '') .map((val) => parseFloat(val)); if (parts.length === 4) { alpha = parts[3]; } else if (parts.length === 3) { alpha = 1; } return fromHSLA({ h: parts[0], s: parts[1], l: parts[2], a: alpha }); } else if (color.indexOf('rgb') !== -1) { let alpha = null; const parts = color .replace(/rgba|rgb|\(|\)/gm, '') .split(/\s|,/g) .filter((val) => val !== '') .map((val) => parseFloat(val)); if (parts.length === 4) { alpha = parts[3]; } else if (parts.length === 3) { alpha = 1; } return fromRGBA({ r: parts[0], g: parts[1], b: parts[2], a: alpha }); } else if (color.indexOf('hsv') !== -1) { let alpha = null; const parts = color .replace(/hsva|hsv|\(|\)/gm, '') .split(/\s|,/g) .filter((val) => val !== '') .map((val) => parseFloat(val)); if (parts.length === 4) { alpha = parts[3]; } else if (parts.length === 3) { alpha = 1; } return fromHSVA({ h: parts[0], s: parts[1], v: parts[2], a: alpha }); } if (color === 'transparent') {return fromHexa('#00000000');} const hex = parseHex(color); if (oldColor && hex === oldColor.hexa) { return oldColor; } else { return fromHexa(hex); } } if (typeof color === 'object') { if (color.hasOwnProperty('alpha')) {return color;} const a = color.hasOwnProperty('a') ? parseFloat(color.a) : 1; if (has(color, ['r', 'g', 'b'])) { if (oldColor && color === oldColor.rgba) {return oldColor;} else {return fromRGBA({ ...color, a });} } else if (has(color, ['h', 's', 'l'])) { if (oldColor && color === oldColor.hsla) {return oldColor;} else {return fromHSLA({ ...color, a });} } else if (has(color, ['h', 's', 'v'])) { if (oldColor && color === oldColor.hsva) {return oldColor;} else {return fromHSVA({ ...color, a });} } } return fromRGBA({ r: 255, g: 0, b: 0, a: 1 }); } function stripAlpha(color: Color, stripAlpha: boolean) { if (stripAlpha) { const { a, ...rest } = color; return rest; } return color; } export function extractColor(color: ColorPickerColor, input: Color, mode, showAlpha: boolean): any { // 色相 const hue = keepDecimal(color.hsla.h, 2); // 饱和度 const hslSaturation = keepDecimal(color.hsla.s, 2); // 亮度 const lightness = keepDecimal(color.hsla.l, 2); // red const red = keepDecimal(color.rgba.r); // green const green = keepDecimal(color.rgba.g); // blue const blue = keepDecimal(color.rgba.b); // HSV饱和度 const hsvSaturation = keepDecimal(color.hsva.s, 2); // value const value = keepDecimal(color.hsva.v, 2); if (input == null) {return color;} function isShowAlpha(mode) { return showAlpha ? mode + 'a' : mode; } if (typeof input === 'string') { if (mode === 'hex') { return showAlpha ? color.hexa : color.hex; } else if (mode === 'hsl') { return `${isShowAlpha(mode)}(${hue}, ${hslSaturation}, ${lightness}${ showAlpha ? ', ' + color.alpha : '' })`; } else if (mode === 'rgb') { return `${isShowAlpha(mode)}(${red}, ${green}, ${blue}${showAlpha ? ', ' + color.alpha : ''})`; } else if (mode === 'hsv') { return `${isShowAlpha(mode)}(${hue}, ${hsvSaturation}, ${value}${ showAlpha ? ', ' + color.alpha : '' })`; } return input.length === 7 ? color.hex : color.hexa; } if (typeof input === 'object') { const shouldStrip = typeof input.a === 'number' && input.a === 0 ? !!input.a : !input.a; if (has(input, ['r', 'g', 'b'])) {return stripAlpha(color.rgba, shouldStrip);} else if (has(input, ['h', 's', 'l'])) {return stripAlpha(color.hsla, shouldStrip);} else if (has(input, ['h', 's', 'v'])) {return stripAlpha(color.hsva, shouldStrip);} } } export function hasAlpha(color: Color): boolean { if (!color) {return false;} if (typeof color === 'string') { return color.length > 7; } if (typeof color === 'object') { return has(color, ['a']) || has(color, ['alpha']); } return false; } export const elementResize = (parentElement: HTMLElement): position => { const left = ref(0); const top = ref(0); window.addEventListener('resize', () => { left.value = parentElement?.getBoundingClientRect().left; top.value = parentElement?.getBoundingClientRect().top + parentElement?.getBoundingClientRect().height; }); return { left, top }; }; export function RGBtoRGBA(rgba: RGBA): RGBA { if (typeof rgba === 'string') { rgba = (/rgba?\((.*?)\)/.exec(rgba) || ['', '0,0,0,1'])[1].split(','); return { r: Number(rgba[0]) || 0, g: Number(rgba[1]) || 0, b: Number(rgba[2]) || 0, a: Number(rgba[3] ? rgba[3] : 1) // Avoid the case of 0 }; } else { return rgba; } } export function RGBtoHSV(rgb: RGB): HSV { if (!rgb) {return { h: 0, s: 1, v: 1 };} const r = rgb.r / 255; const g = rgb.g / 255; const b = rgb.b / 255; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h = 0; if (max !== min) { if (max === r) { h = 60 * (0 + (g - b) / (max - min)); } else if (max === g) { h = 60 * (2 + (b - r) / (max - min)); } else if (max === b) { h = 60 * (4 + (r - g) / (max - min)); } } if (h < 0) {h = h + 360;} const s = max === 0 ? 0 : (max - min) / max; const hsv = [h, s, max]; return { h: hsv[0], s: hsv[1].toFixed(2), v: hsv[2].toFixed(2) }; } export function HSVtoHSL(hsv: HSV): HSL { const { h, s, v } = hsv; const l = Number((v - (v * s) / 2).toFixed(2)); const sprime = l === 1 || l === 0 ? 0 : (v - l) / Math.min(l, 1 - l); return { h, s: Number(sprime.toFixed(2)), l }; }
the_stack
import * as crypto from 'crypto'; import AnchoredDataSerializer from '../../lib/core/versions/latest/AnchoredDataSerializer'; import AnchoredOperationModel from '../../lib/core/models/AnchoredOperationModel'; import CoreIndexFile from '../../lib/core/versions/latest/CoreIndexFile'; import CreateOperation from '../../lib/core/versions/latest/CreateOperation'; import DataGenerator from './DataGenerator'; import DeactivateOperation from '../../lib/core/versions/latest/DeactivateOperation'; import Did from '../../lib/core/versions/latest/Did'; import DocumentModel from '../../lib/core/versions/latest/models/DocumentModel'; import Encoder from '../../lib/core/versions/latest/Encoder'; import JsonCanonicalizer from '../../lib/core/versions/latest/util/JsonCanonicalizer'; import Jwk from '../../lib/core/versions/latest/util/Jwk'; import JwkEs256k from '../../lib/core/models/JwkEs256k'; import Jws from '../../lib/core/versions/latest/util/Jws'; import Multihash from '../../lib/core/versions/latest/Multihash'; import OperationModel from '../../lib/core/versions/latest/models/OperationModel'; import OperationType from '../../lib/core/enums/OperationType'; import PatchAction from '../../lib/core/versions/latest/PatchAction'; import PublicKeyModel from '../../lib/core/versions/latest/models/PublicKeyModel'; import PublicKeyPurpose from '../../lib/core/versions/latest/PublicKeyPurpose'; import RecoverOperation from '../../lib/core/versions/latest/RecoverOperation'; import ServiceModel from '../../lib/core/versions/latest/models/ServiceModel'; import TransactionModel from '../../lib/common/models/TransactionModel'; import UpdateOperation from '../../lib/core/versions/latest/UpdateOperation'; interface AnchoredCreateOperationGenerationInput { transactionNumber: number; transactionTime: number; operationIndex: number; } interface RecoverOperationGenerationInput { didUniqueSuffix: string; recoveryPrivateKey: JwkEs256k; } interface GeneratedRecoverOperationData { operationBuffer: Buffer; recoverOperation: RecoverOperation; recoveryPublicKey: JwkEs256k; recoveryPrivateKey: JwkEs256k; signingPublicKey: PublicKeyModel; signingPrivateKey: JwkEs256k; updateKey: PublicKeyModel; updatePrivateKey: JwkEs256k; } /** * A class that can generate valid operations. * Mainly useful for testing purposes. */ export default class OperationGenerator { /** * Generates a random `TransactionModel`. */ public static generateTransactionModel (): TransactionModel { const anchorString = AnchoredDataSerializer.serialize({ coreIndexFileUri: OperationGenerator.generateRandomHash(), numberOfOperations: 1 }); return { anchorString, normalizedTransactionFee: DataGenerator.generateInteger(), transactionFeePaid: DataGenerator.generateInteger(), transactionNumber: DataGenerator.generateInteger(), transactionTime: DataGenerator.generateInteger(), transactionTimeHash: OperationGenerator.generateRandomHash(), writer: OperationGenerator.generateRandomHash() }; } /** * Generates a random multihash. */ public static generateRandomHash (): string { const randomBuffer = crypto.randomBytes(32); const hashAlgorithmInMultihashCode = 18; // SHA256 const randomHash = Encoder.encode(Multihash.hash(randomBuffer, hashAlgorithmInMultihashCode)); return randomHash; } /** * Generates SECP256K1 key pair to be used in an operation. If purposes not supplied, all purposes will be included * Mainly used for testing. * @returns [publicKey, privateKey] */ public static async generateKeyPair (id: string, purposes?: PublicKeyPurpose[]): Promise<[PublicKeyModel, JwkEs256k]> { const [publicKey, privateKey] = await Jwk.generateEs256kKeyPair(); const publicKeyModel = { id, type: 'EcdsaSecp256k1VerificationKey2019', publicKeyJwk: publicKey, purposes: purposes || Object.values(PublicKeyPurpose) }; return [publicKeyModel, privateKey]; } /** * Generates an anchored create operation. */ public static async generateAnchoredCreateOperation (input: AnchoredCreateOperationGenerationInput) { const createOperationData = await OperationGenerator.generateCreateOperation(); const anchoredOperationModel = { type: OperationType.Create, didUniqueSuffix: createOperationData.createOperation.didUniqueSuffix, operationBuffer: createOperationData.createOperation.operationBuffer, transactionNumber: input.transactionNumber, transactionTime: input.transactionTime, operationIndex: input.operationIndex }; return { createOperation: createOperationData.createOperation, operationRequest: createOperationData.operationRequest, anchoredOperationModel, recoveryPublicKey: createOperationData.recoveryPublicKey, recoveryPrivateKey: createOperationData.recoveryPrivateKey, updatePublicKey: createOperationData.updatePublicKey, updatePrivateKey: createOperationData.updatePrivateKey, signingPublicKey: createOperationData.signingPublicKey, signingPrivateKey: createOperationData.signingPrivateKey }; } /** * generate a long form did * @param recoveryPublicKey * @param updatePublicKey * @param otherPublicKeys * @param services */ public static async generateLongFormDid ( otherPublicKeys?: PublicKeyModel[], services?: ServiceModel[], network?: string) { const document = { publicKeys: otherPublicKeys || [], services: services || [] }; const patches = [{ action: PatchAction.Replace, document }]; const [recoveryPublicKey] = await Jwk.generateEs256kKeyPair(); const [updatePublicKey] = await Jwk.generateEs256kKeyPair(); const delta = { updateCommitment: Multihash.canonicalizeThenDoubleHashThenEncode(updatePublicKey), patches }; const deltaHash = Multihash.canonicalizeThenHashThenEncode(delta); const suffixData = { deltaHash: deltaHash, recoveryCommitment: Multihash.canonicalizeThenDoubleHashThenEncode(recoveryPublicKey) }; const didUniqueSuffix = Did['computeUniqueSuffix'](suffixData); const shortFormDid = network ? `did:sidetree:${network}:${didUniqueSuffix}` : `did:sidetree:${didUniqueSuffix}`; const initialState = { suffixData: suffixData, delta: delta }; const canonicalizedInitialStateBuffer = JsonCanonicalizer.canonicalizeAsBuffer(initialState); const encodedCanonicalizedInitialStateString = Encoder.encode(canonicalizedInitialStateBuffer); const longFormDid = `${shortFormDid}:${encodedCanonicalizedInitialStateString}`; return { longFormDid, shortFormDid, didUniqueSuffix }; } /** * Generates a long from from create operation data. */ public static async createDid ( recoveryKey: JwkEs256k, updateKey: JwkEs256k, patches: any, network?: string ) { const delta = { updateCommitment: Multihash.canonicalizeThenDoubleHashThenEncode(updateKey), patches }; const deltaHash = Multihash.canonicalizeThenHashThenEncode(delta); const suffixData = { deltaHash: deltaHash, recoveryCommitment: Multihash.canonicalizeThenDoubleHashThenEncode(recoveryKey) }; const didUniqueSuffix = Did['computeUniqueSuffix'](suffixData); const shortFormDid = network ? `did:sidetree:${network}:${didUniqueSuffix}` : `did:sidetree:${didUniqueSuffix}`; const initialState = { suffixData: suffixData, delta: delta }; const canonicalizedInitialStateBuffer = JsonCanonicalizer.canonicalizeAsBuffer(initialState); const encodedCanonicalizedInitialStateString = Encoder.encode(canonicalizedInitialStateBuffer); const longFormDid = `${shortFormDid}:${encodedCanonicalizedInitialStateString}`; return { longFormDid, shortFormDid, didUniqueSuffix }; } /** * Generates a create operation. */ public static async generateCreateOperation () { const signingKeyId = 'signingKey'; const [recoveryPublicKey, recoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); const [updatePublicKey, updatePrivateKey] = await Jwk.generateEs256kKeyPair(); const [signingPublicKey, signingPrivateKey] = await OperationGenerator.generateKeyPair(signingKeyId); const services = OperationGenerator.generateServices(['serviceId123']); const operationRequest = await OperationGenerator.createCreateOperationRequest( recoveryPublicKey, updatePublicKey, [signingPublicKey], services ); const operationBuffer = Buffer.from(JSON.stringify(operationRequest)); const createOperation = await CreateOperation.parse(operationBuffer); return { createOperation, operationRequest, recoveryPublicKey, recoveryPrivateKey, updatePublicKey, updatePrivateKey, signingPublicKey, signingPrivateKey }; } /** * Generates a recover operation. */ public static async generateRecoverOperation (input: RecoverOperationGenerationInput): Promise<GeneratedRecoverOperationData> { const newSigningKeyId = 'newSigningKey'; const [newRecoveryPublicKey, newRecoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); const [newSigningPublicKey, newSigningPrivateKey] = await OperationGenerator.generateKeyPair(newSigningKeyId); const [publicKeyToBeInDocument] = await OperationGenerator.generateKeyPair('newKey'); const services = OperationGenerator.generateServices(['serviceId123']); // Generate the next update and recover operation commitment hash reveal value pair. const [updateKey, updatePrivateKey] = await OperationGenerator.generateKeyPair('updateKey'); const operationJson = await OperationGenerator.generateRecoverOperationRequest( input.didUniqueSuffix, input.recoveryPrivateKey, newRecoveryPublicKey, newSigningPublicKey, services, [publicKeyToBeInDocument] ); const operationBuffer = Buffer.from(JSON.stringify(operationJson)); const recoverOperation = await RecoverOperation.parse(operationBuffer); return { recoverOperation, operationBuffer, recoveryPublicKey: newRecoveryPublicKey, recoveryPrivateKey: newRecoveryPrivateKey, signingPublicKey: newSigningPublicKey, signingPrivateKey: newSigningPrivateKey, updateKey, updatePrivateKey }; } /** * Generates an update operation that adds a new key. */ public static async generateUpdateOperation ( didUniqueSuffix: string, updatePublicKey: JwkEs256k, updatePrivateKey: JwkEs256k, multihashAlgorithmCodeToUse?: number, multihashAlgorithmForRevealValue?: number ) { const additionalKeyId = `additional-key`; const [additionalPublicKey, additionalPrivateKey] = await OperationGenerator.generateKeyPair(additionalKeyId); // Should really use an independent key, but reusing key for convenience in test. const nextUpdateCommitmentHash = Multihash.canonicalizeThenDoubleHashThenEncode(additionalPublicKey); const operationJson = await OperationGenerator.createUpdateOperationRequestForAddingAKey( didUniqueSuffix, updatePublicKey, updatePrivateKey, additionalPublicKey, nextUpdateCommitmentHash, multihashAlgorithmCodeToUse, multihashAlgorithmForRevealValue ); const operationBuffer = Buffer.from(JSON.stringify(operationJson)); const updateOperation = await UpdateOperation.parse(operationBuffer); return { updateOperation, operationBuffer, additionalKeyId, additionalPublicKey, additionalPrivateKey, nextUpdateKey: additionalPublicKey.publicKeyJwk }; } /** * Creates a named anchored operation model from `OperationModel`. */ public static createAnchoredOperationModelFromOperationModel ( operationModel: OperationModel, transactionTime: number, transactionNumber: number, operationIndex: number ): AnchoredOperationModel { const anchoredOperationModel: AnchoredOperationModel = { didUniqueSuffix: operationModel.didUniqueSuffix, type: operationModel.type, operationBuffer: operationModel.operationBuffer, operationIndex, transactionNumber, transactionTime }; return anchoredOperationModel; } /** * Creates a create operation request. */ public static async createCreateOperationRequest ( recoveryPublicKey: JwkEs256k, updatePublicKey: JwkEs256k, otherPublicKeys: PublicKeyModel[], services?: ServiceModel[]) { const document: DocumentModel = { publicKeys: otherPublicKeys, services }; const patches = [{ action: PatchAction.Replace, document }]; const delta = { updateCommitment: Multihash.canonicalizeThenDoubleHashThenEncode(updatePublicKey), patches }; const deltaHash = Multihash.canonicalizeThenHashThenEncode(delta); const suffixData = { deltaHash, recoveryCommitment: Multihash.canonicalizeThenDoubleHashThenEncode(recoveryPublicKey) }; const operation = { type: OperationType.Create, suffixData, delta }; return operation; } /** * Generates an update operation request. */ public static async generateUpdateOperationRequest (didUniqueSuffix?: string) { if (didUniqueSuffix === undefined) { didUniqueSuffix = OperationGenerator.generateRandomHash(); } const [nextUpdateKey] = await OperationGenerator.generateKeyPair('nextUpdateKey'); const nextUpdateCommitmentHash = Multihash.canonicalizeThenDoubleHashThenEncode(nextUpdateKey.publicKeyJwk); const anyNewSigningPublicKeyId = 'anyNewKey'; const [anyNewSigningKey] = await OperationGenerator.generateKeyPair(anyNewSigningPublicKeyId); const patches = [ { action: PatchAction.AddPublicKeys, publicKeys: [ anyNewSigningKey ] } ]; const signingKeyId = 'anySigningKeyId'; const [signingPublicKey, signingPrivateKey] = await OperationGenerator.generateKeyPair(signingKeyId); const request = await OperationGenerator.createUpdateOperationRequest( didUniqueSuffix, signingPublicKey.publicKeyJwk, signingPrivateKey, nextUpdateCommitmentHash, patches ); const buffer = Buffer.from(JSON.stringify(request)); const updateOperation = await UpdateOperation.parse(buffer); return { request, buffer, updateOperation }; } /** * Creates an update operation request. */ public static async createUpdateOperationRequest ( didSuffix: string, updatePublicKey: JwkEs256k, updatePrivateKey: JwkEs256k, nextUpdateCommitmentHash: string, patches: any, multihashAlgorithmCodeToUse?: number, multihashAlgorithmForRevealValue?: number ) { const revealValue = Multihash.canonicalizeThenHashThenEncode(updatePublicKey, multihashAlgorithmForRevealValue); const delta = { patches, updateCommitment: nextUpdateCommitmentHash }; const deltaHash = Multihash.canonicalizeThenHashThenEncode(delta, multihashAlgorithmCodeToUse); const signedDataPayloadObject = { updateKey: updatePublicKey, deltaHash: deltaHash }; const signedData = await OperationGenerator.signUsingEs256k(signedDataPayloadObject, updatePrivateKey); const updateOperationRequest = { type: OperationType.Update, didSuffix, revealValue, delta, signedData }; return updateOperationRequest; } /** * Generates a recover operation request. */ public static async generateRecoverOperationRequest ( didUniqueSuffix: string, recoveryPrivateKey: JwkEs256k, newRecoveryPublicKey: JwkEs256k, newSigningPublicKey: PublicKeyModel, services?: ServiceModel[], publicKeys?: PublicKeyModel[]) { const document = { publicKeys: publicKeys, services }; const recoverOperation = await OperationGenerator.createRecoverOperationRequest( didUniqueSuffix, recoveryPrivateKey, newRecoveryPublicKey, Multihash.canonicalizeThenDoubleHashThenEncode(newSigningPublicKey.publicKeyJwk), document ); return recoverOperation; } /** * Creates a recover operation request. */ public static async createRecoverOperationRequest ( didSuffix: string, recoveryPrivateKey: JwkEs256k, newRecoveryPublicKey: JwkEs256k, nextUpdateCommitmentHash: string, document: any ) { const recoveryPublicKey = Jwk.getEs256kPublicKey(recoveryPrivateKey); const revealValue = Multihash.canonicalizeThenHashThenEncode(recoveryPublicKey); const patches = [{ action: PatchAction.Replace, document }]; const delta = { patches, updateCommitment: nextUpdateCommitmentHash }; const deltaHash = Multihash.canonicalizeThenHashThenEncode(delta); const signedDataPayloadObject = { deltaHash, recoveryKey: recoveryPublicKey, recoveryCommitment: Multihash.canonicalizeThenDoubleHashThenEncode(newRecoveryPublicKey) }; const signedData = await OperationGenerator.signUsingEs256k(signedDataPayloadObject, recoveryPrivateKey); const operation = { type: OperationType.Recover, didSuffix, revealValue, signedData, delta }; return operation; } /** * Generates a deactivate operation request. */ public static async createDeactivateOperationRequest ( didSuffix: string, recoveryPrivateKey: JwkEs256k ) { const recoveryPublicKey = Jwk.getEs256kPublicKey(recoveryPrivateKey); const revealValue = Multihash.canonicalizeThenHashThenEncode(recoveryPublicKey); const signedDataPayloadObject = { didSuffix, recoveryKey: recoveryPublicKey }; const signedData = await OperationGenerator.signUsingEs256k(signedDataPayloadObject, recoveryPrivateKey); const operation = { type: OperationType.Deactivate, didSuffix, revealValue, signedData }; return operation; } /** * Generates a create operation request buffer. * @param nextRecoveryCommitmentHash The encoded commitment hash for the next recovery. * @param nextUpdateCommitmentHash The encoded commitment hash for the next update. */ public static async generateCreateOperationBuffer ( recoveryPublicKey: JwkEs256k, signingPublicKey: PublicKeyModel, services?: ServiceModel[] ): Promise<Buffer> { const operation = await OperationGenerator.createCreateOperationRequest( recoveryPublicKey, signingPublicKey.publicKeyJwk, [signingPublicKey], services ); return Buffer.from(JSON.stringify(operation)); } /** * Creates an update operation for adding a key. */ public static async createUpdateOperationRequestForAddingAKey ( didUniqueSuffix: string, updatePublicKey: JwkEs256k, updatePrivateKey: JwkEs256k, newPublicKey: PublicKeyModel, nextUpdateCommitmentHash: string, multihashAlgorithmCodeToUse?: number, multihashAlgorithmForRevealValue?: number) { const patches = [ { action: PatchAction.AddPublicKeys, publicKeys: [ newPublicKey ] } ]; const updateOperationRequest = await OperationGenerator.createUpdateOperationRequest( didUniqueSuffix, updatePublicKey, updatePrivateKey, nextUpdateCommitmentHash, patches, multihashAlgorithmCodeToUse, multihashAlgorithmForRevealValue ); return updateOperationRequest; } /** * Generate an update operation for adding and/or removing services. */ public static async generateUpdateOperationRequestForServices ( didUniqueSuffix: string, updatePublicKey: any, updatePrivateKey: JwkEs256k, nextUpdateCommitmentHash: string, idOfServiceEndpointToAdd: string | undefined, idsOfServiceEndpointToRemove: string[]) { const patches = []; if (idOfServiceEndpointToAdd !== undefined) { const patch = { action: PatchAction.AddServices, services: OperationGenerator.generateServices([idOfServiceEndpointToAdd]) }; patches.push(patch); } if (idsOfServiceEndpointToRemove.length > 0) { const patch = { action: PatchAction.RemoveServices, ids: idsOfServiceEndpointToRemove }; patches.push(patch); } const updateOperationRequest = await OperationGenerator.createUpdateOperationRequest( didUniqueSuffix, updatePublicKey, updatePrivateKey, nextUpdateCommitmentHash, patches ); return updateOperationRequest; } /** * Signs the given payload as a ES256K compact JWS. */ public static async signUsingEs256k (payload: any, privateKey: JwkEs256k): Promise<string> { const protectedHeader = { alg: 'ES256K' }; const compactJws = Jws.signAsCompactJws(payload, privateKey, protectedHeader); return compactJws; } /** * Generates a Deactivate Operation data. */ public static async createDeactivateOperation ( didUniqueSuffix: string, recoveryPrivateKey: JwkEs256k) { const operationRequest = await OperationGenerator.createDeactivateOperationRequest(didUniqueSuffix, recoveryPrivateKey); const operationBuffer = Buffer.from(JSON.stringify(operationRequest)); const deactivateOperation = await DeactivateOperation.parse(operationBuffer); return { operationRequest, operationBuffer, deactivateOperation }; } /** * Generates an array of services with specified ids * @param ids the id field in service. */ public static generateServices (ids: string[]): ServiceModel[] { const services = []; for (const id of ids) { services.push( { id: id, type: 'someType', serviceEndpoint: 'https://www.url.com' } ); } return services; } /** * Generates an core index file. */ public static async generateCoreIndexFile (recoveryOperationCount: number): Promise<Buffer> { const provisionalIndexFileUri = 'bafkreid5uh2g5gbbhvpza4mwfwbmigy43rar2xkalwtvc7v34b4557cr2i'; const coreProofFileUri = 'bafkreid5uh2g5gbbhvpza4mwfwbmigy43rar2xkalwtvc7v34b4557aaaa'; const recoverOperations = []; for (let i = 0; i < recoveryOperationCount; i++) { const [, anyRecoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); const anyDid = OperationGenerator.generateRandomHash(); const recoverOperationData = await OperationGenerator.generateRecoverOperation( { didUniqueSuffix: anyDid, recoveryPrivateKey: anyRecoveryPrivateKey }); const recoverOperation = recoverOperationData.recoverOperation; recoverOperations.push(recoverOperation); } const coreIndexFileBuffer = await CoreIndexFile.createBuffer(undefined, provisionalIndexFileUri, coreProofFileUri, [], recoverOperations, []); return coreIndexFileBuffer; } }
the_stack
import { equalArrays, fixCSS, IEventListener, suffix, joinIndexArrays, AEventDispatcher } from '../internal'; import { isSortingAscByDefault } from './annotations'; import Column, { dirty, dirtyCaches, dirtyHeader, dirtyValues, labelChanged, visibilityChanged, widthChanged, } from './Column'; import CompositeColumn from './CompositeColumn'; import { IRankingDump, defaultGroup, IndicesArray, IOrderedGroup, IDataRow, IColumnParent, IFlatColumn, ISortCriteria, UIntTypedArray, IGroupParent, ITypeFactory, IGroup, } from './interfaces'; import { groupRoots, traverseGroupsDFS } from './internal'; import AggregateGroupColumn from './AggregateGroupColumn'; import SetColumn from './SetColumn'; import { AGGREGATION_LEVEL_WIDTH } from '../styles'; export enum EDirtyReason { UNKNOWN = 'unknown', FILTER_CHANGED = 'filter', SORT_CRITERIA_CHANGED = 'sort_changed', SORT_CRITERIA_DIRTY = 'sort_dirty', GROUP_CRITERIA_CHANGED = 'group_changed', GROUP_CRITERIA_DIRTY = 'group_dirty', GROUP_SORT_CRITERIA_CHANGED = 'group_sort_changed', GROUP_SORT_CRITERIA_DIRTY = 'group_sort_dirty', } /** * emitted when a column has been added * @asMemberOf Ranking * @event */ export declare function addColumn(col: Column, index: number): void; /** * emitted when a column has been moved within this composite column * @asMemberOf Ranking * @event */ export declare function moveColumn(col: Column, index: number, oldIndex: number): void; /** * emitted when a column has been removed * @asMemberOf Ranking * @event */ export declare function removeColumn(col: Column, index: number): void; /** * emitted when the sort criteria property changes * @asMemberOf Ranking * @event */ export declare function sortCriteriaChanged(previous: ISortCriteria[], current: ISortCriteria[]): void; /** * emitted when the sort criteria property changes * @asMemberOf Ranking * @event */ export declare function groupCriteriaChanged(previous: Column[], current: Column[]): void; /** * emitted when the sort criteria property changes * @asMemberOf Ranking * @event */ export declare function groupSortCriteriaChanged(previous: ISortCriteria[], current: ISortCriteria[]): void; /** * emitted when the sort criteria property changes * @asMemberOf Ranking * @event */ export declare function dirtyOrder(reason?: EDirtyReason[]): void; /** * @asMemberOf Ranking * @event */ export declare function orderChanged( previous: number[], current: number[], previousGroups: IOrderedGroup[], currentGroups: IOrderedGroup[], dirtyReason: EDirtyReason[] ): void; /** * @asMemberOf Ranking * @event */ export declare function groupsChanged( previous: number[], current: number[], previousGroups: IOrderedGroup[], currentGroups: IOrderedGroup[] ): void; /** * emitted when the filter property changes * @asMemberOf NumberColumn * @event */ export declare function filterChanged(previous: any | null, current: any | null): void; /** * a ranking */ export default class Ranking extends AEventDispatcher implements IColumnParent { static readonly EVENT_WIDTH_CHANGED = Column.EVENT_WIDTH_CHANGED; static readonly EVENT_FILTER_CHANGED = 'filterChanged'; static readonly EVENT_LABEL_CHANGED = Column.EVENT_LABEL_CHANGED; static readonly EVENT_ADD_COLUMN = CompositeColumn.EVENT_ADD_COLUMN; static readonly EVENT_MOVE_COLUMN = CompositeColumn.EVENT_MOVE_COLUMN; static readonly EVENT_REMOVE_COLUMN = CompositeColumn.EVENT_REMOVE_COLUMN; static readonly EVENT_DIRTY = Column.EVENT_DIRTY; static readonly EVENT_DIRTY_HEADER = Column.EVENT_DIRTY_HEADER; static readonly EVENT_DIRTY_VALUES = Column.EVENT_DIRTY_VALUES; static readonly EVENT_DIRTY_CACHES = Column.EVENT_DIRTY_CACHES; static readonly EVENT_COLUMN_VISIBILITY_CHANGED = Column.EVENT_VISIBILITY_CHANGED; static readonly EVENT_SORT_CRITERIA_CHANGED = 'sortCriteriaChanged'; static readonly EVENT_GROUP_CRITERIA_CHANGED = 'groupCriteriaChanged'; static readonly EVENT_GROUP_SORT_CRITERIA_CHANGED = 'groupSortCriteriaChanged'; static readonly EVENT_DIRTY_ORDER = 'dirtyOrder'; static readonly EVENT_ORDER_CHANGED = 'orderChanged'; static readonly EVENT_GROUPS_CHANGED = 'groupsChanged'; private static readonly FORWARD_COLUMN_EVENTS = suffix( '.ranking', Column.EVENT_VISIBILITY_CHANGED, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY, Column.EVENT_VISIBILITY_CHANGED, Ranking.EVENT_FILTER_CHANGED ); private static readonly COLUMN_GROUP_SORT_DIRTY = suffix( '.groupOrder', Column.EVENT_DIRTY_CACHES, 'sortMethodChanged' ); private static readonly COLUMN_SORT_DIRTY = suffix('.order', Column.EVENT_DIRTY_CACHES); private static readonly COLUMN_GROUP_DIRTY = suffix('.group', Column.EVENT_DIRTY_CACHES, 'groupingChanged'); private label: string; private readonly sortCriteria: ISortCriteria[] = []; private readonly groupColumns: Column[] = []; private readonly groupSortCriteria: ISortCriteria[] = []; /** * columns of this ranking * @type {Array} * @private */ private readonly columns: Column[] = []; readonly dirtyOrder = (reason?: EDirtyReason[]) => { this.fire([Ranking.EVENT_DIRTY_ORDER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY], reason); }; private readonly dirtyOrderSortDirty = () => this.dirtyOrder([EDirtyReason.SORT_CRITERIA_DIRTY]); private readonly dirtyOrderGroupDirty = () => this.dirtyOrder([EDirtyReason.GROUP_CRITERIA_DIRTY]); private readonly dirtyOrderGroupSortDirty = () => this.dirtyOrder([EDirtyReason.GROUP_SORT_CRITERIA_DIRTY]); private readonly dirtyOrderFiltering = () => this.dirtyOrder([EDirtyReason.FILTER_CHANGED]); /** * the current ordering as an sorted array of indices * @type {Array} */ private groups: IOrderedGroup[] = [Object.assign({ order: [] as number[] }, defaultGroup)]; private order: IndicesArray = []; private index2pos: IndicesArray = []; constructor(public id: string) { super(); this.id = fixCSS(id); this.label = `Ranking ${id.startsWith('rank') ? id.slice(4) : id}`; } protected createEventList() { return super .createEventList() .concat([ Ranking.EVENT_WIDTH_CHANGED, Ranking.EVENT_FILTER_CHANGED, Ranking.EVENT_LABEL_CHANGED, Ranking.EVENT_GROUPS_CHANGED, Ranking.EVENT_ADD_COLUMN, Ranking.EVENT_REMOVE_COLUMN, Ranking.EVENT_GROUP_CRITERIA_CHANGED, Ranking.EVENT_MOVE_COLUMN, Ranking.EVENT_DIRTY, Ranking.EVENT_DIRTY_HEADER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY_CACHES, Ranking.EVENT_GROUP_SORT_CRITERIA_CHANGED, Ranking.EVENT_COLUMN_VISIBILITY_CHANGED, Ranking.EVENT_SORT_CRITERIA_CHANGED, Ranking.EVENT_DIRTY_ORDER, Ranking.EVENT_ORDER_CHANGED, ]); } on(type: typeof Ranking.EVENT_WIDTH_CHANGED, listener: typeof widthChanged | null): this; on(type: typeof Ranking.EVENT_FILTER_CHANGED, listener: typeof filterChanged | null): this; on(type: typeof Ranking.EVENT_LABEL_CHANGED, listener: typeof labelChanged | null): this; on(type: typeof Ranking.EVENT_ADD_COLUMN, listener: typeof addColumn | null): this; on(type: typeof Ranking.EVENT_MOVE_COLUMN, listener: typeof moveColumn | null): this; on(type: typeof Ranking.EVENT_REMOVE_COLUMN, listener: typeof removeColumn | null): this; on(type: typeof Ranking.EVENT_DIRTY, listener: typeof dirty | null): this; on(type: typeof Ranking.EVENT_DIRTY_HEADER, listener: typeof dirtyHeader | null): this; on(type: typeof Ranking.EVENT_DIRTY_VALUES, listener: typeof dirtyValues | null): this; on(type: typeof Ranking.EVENT_DIRTY_CACHES, listener: typeof dirtyCaches | null): this; on(type: typeof Ranking.EVENT_COLUMN_VISIBILITY_CHANGED, listener: typeof visibilityChanged | null): this; on(type: typeof Ranking.EVENT_SORT_CRITERIA_CHANGED, listener: typeof sortCriteriaChanged | null): this; on(type: typeof Ranking.EVENT_GROUP_CRITERIA_CHANGED, listener: typeof groupCriteriaChanged | null): this; on(type: typeof Ranking.EVENT_GROUP_SORT_CRITERIA_CHANGED, listener: typeof groupSortCriteriaChanged | null): this; on(type: typeof Ranking.EVENT_DIRTY_ORDER, listener: typeof dirtyOrder | null): this; on(type: typeof Ranking.EVENT_ORDER_CHANGED, listener: typeof orderChanged | null): this; on(type: typeof Ranking.EVENT_GROUPS_CHANGED, listener: typeof groupsChanged | 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); } assignNewId(idGenerator: () => string) { this.id = fixCSS(idGenerator()); this.columns.forEach((c) => c.assignNewId(idGenerator)); } getLabel() { return this.label; } setLabel(value: string) { if (value === this.label) { return; } this.fire(Ranking.EVENT_LABEL_CHANGED, this.label, (this.label = value)); } setGroups(groups: IOrderedGroup[], index2pos: IndicesArray, dirtyReason: EDirtyReason[]) { const old = this.order; const oldGroups = this.groups; this.groups = groups; this.index2pos = index2pos; this.order = joinIndexArrays(groups.map((d) => d.order)); // replace with subarrays to save memory if (groups.length > 1) { this.unifyGroups(groups); } else if (groups.length === 1) { // propagate to the top let p = groups[0].parent; while (p) { (p as any as IOrderedGroup).order = this.order; p = p.parent; } } this.fire( [Ranking.EVENT_ORDER_CHANGED, Ranking.EVENT_GROUPS_CHANGED, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY], old, this.order, oldGroups, groups, dirtyReason ); } private unifyGroups(groups: IOrderedGroup[]) { let offset = 0; const order = this.order as UIntTypedArray; const offsets = new Map< Readonly<IGroupParent> | IOrderedGroup, { offset: number; size: number; } >(); for (const group of groups) { const size = group.order.length; group.order = order.subarray(offset, offset + size); offsets.set(group, { offset, size }); offset += size; } // propagate also to the top with views const roots = groupRoots(groups); const resolve = ( g: Readonly<IGroupParent> | IOrderedGroup ): { offset: number; size: number; } => { if (offsets.has(g)) { // leaf return offsets.get(g)!; } const subs = (g as IGroupParent).subGroups.map((gi) => resolve(gi as Readonly<IGroupParent> | IOrderedGroup)); const offset = subs.length > 0 ? subs[0].offset : 0; const size = subs.reduce((a, b) => a + b.size, 0); const r = { offset, size }; offsets.set(g, r); (g as any as IOrderedGroup).order = order.subarray(offset, offset + size); return r; }; for (const root of roots) { resolve(root); } } getRank(dataIndex: number) { if (dataIndex < 0 || dataIndex > this.index2pos.length) { return -1; } const v = this.index2pos[dataIndex]; return v != null && !Number.isNaN(v) && v > 0 ? v : -1; } getOrder() { return this.order; } getOrderLength() { return this.order.length; } getGroups() { return this.groups.slice(); } /** * Returns the flat group tree in depth first search (DFS). */ getFlatGroups() { const r: Readonly<IGroup | IGroupParent>[] = []; traverseGroupsDFS(this.groups, (v) => { r.push(v); }); return r; } dump(toDescRef: (desc: any) => any): IRankingDump { const r: IRankingDump = {}; r.columns = this.columns.map((d) => d.dump(toDescRef)); r.sortCriteria = this.sortCriteria.map((s) => ({ asc: s.asc, sortBy: s.col!.id })); r.groupSortCriteria = this.groupSortCriteria.map((s) => ({ asc: s.asc, sortBy: s.col!.id })); r.groupColumns = this.groupColumns.map((d) => d.id); return r; } restore(dump: IRankingDump, factory: ITypeFactory) { this.clear(); (dump.columns || []).forEach((child: any) => { const c = factory(child); if (c) { this.push(c); } }); // compatibility case if (dump.sortColumn && dump.sortColumn.sortBy) { const help = this.columns.find((d) => d.id === dump.sortColumn!.sortBy); if (help) { this.sortBy(help, dump.sortColumn.asc); } } if (dump.groupColumns) { const groupColumns = dump.groupColumns .map((id: string) => this.columns.find((d) => d.id === id)) .filter((d) => d != null) as Column[]; this.setGroupCriteria(groupColumns); } const restoreSortCriteria = (dumped: any) => { return dumped .map((s: { asc: boolean; sortBy: string }) => { return { asc: s.asc, col: this.columns.find((d) => d.id === s.sortBy) || null, }; }) .filter((s: any) => s.col); }; if (dump.sortCriteria) { this.setSortCriteria(restoreSortCriteria(dump.sortCriteria)); } if (dump.groupSortCriteria) { this.setGroupSortCriteria(restoreSortCriteria(dump.groupSortCriteria)); } } flatten(r: IFlatColumn[], offset: number, levelsToGo = 0, padding = 0) { let acc = offset; // + this.getWidth() + padding; if (levelsToGo > 0 || levelsToGo <= Column.FLAT_ALL_COLUMNS) { this.columns.forEach((c) => { if (c.getVisible() && levelsToGo <= Column.FLAT_ALL_COLUMNS) { acc += c.flatten(r, acc, levelsToGo - 1, padding) + padding; } }); } return acc - offset; } getPrimarySortCriteria(): ISortCriteria | null { if (this.sortCriteria.length === 0) { return null; } return this.sortCriteria[0]; } getSortCriteria(): ISortCriteria[] { return this.sortCriteria.map((d) => Object.assign({}, d)); } getGroupSortCriteria(): ISortCriteria[] { return this.groupSortCriteria.map((d) => Object.assign({}, d)); } toggleSorting(col: Column) { return this.setSortCriteria(this.toggleSortingLogic(col, this.sortCriteria)); } private toggleSortingLogic(col: Column, sortCriteria: ISortCriteria[]) { const newSort = sortCriteria.slice(); const current = newSort.findIndex((d) => d.col === col); const defaultAsc = isSortingAscByDefault(col); if (current < 0) { newSort.splice(0, newSort.length, { col, asc: defaultAsc }); } else if (newSort[current].asc === defaultAsc) { // asc -> desc, or desc -> asc newSort.splice(current, 1, { col, asc: !defaultAsc }); } else { // remove newSort.splice(current, 1); } return newSort; } toggleGrouping(col: Column) { const old = this.groupColumns.indexOf(col); if (old >= 0) { const newGroupings = this.groupColumns.slice(); newGroupings.splice(old, 1); return this.setGroupCriteria(newGroupings); } return this.setGroupCriteria([col]); } getGroupCriteria() { return this.groupColumns.slice(); } /** * replaces, moves, or remove the given column in the sorting hierarchy * @param col {Column} * @param priority {number} when priority < 0 remove the column only else replace at the given priority */ sortBy(col: Column, ascending = false, priority = 0) { if (col.findMyRanker() !== this) { return false; //not one of mine } return this.setSortCriteria( this.hierarchyLogic( this.sortCriteria, this.sortCriteria.findIndex((d) => d.col === col), { col, asc: ascending }, priority ) ); } /** * replaces, moves, or remove the given column in the group sorting hierarchy * @param col {Column} * @param priority {number} when priority < 0 remove the column only else replace at the given priority */ groupSortBy(col: Column, ascending = false, priority = 0) { if (col.findMyRanker() !== this) { return false; //not one of mine } return this.setGroupSortCriteria( this.hierarchyLogic( this.groupSortCriteria, this.groupSortCriteria.findIndex((d) => d.col === col), { col, asc: ascending }, priority ) ); } private hierarchyLogic<T>(entries: T[], index: number, entry: T, priority: number) { entries = entries.slice(); if (index >= 0) { // move at the other position entries.splice(index, 1); if (priority >= 0) { entries.splice(Math.min(priority, entries.length), 0, entry); } } else if (priority >= 0) { entries[Math.min(priority, entries.length)] = entry; } return entries; } /** * replaces, moves, or remove the given column in the grouping hierarchy * @param col {Column} * @param priority {number} when priority < 0 remove the column only else replace at the given priority */ groupBy(col: Column, priority = 0): boolean { if (col.findMyRanker() !== this) { return false; //not one of mine } return this.setGroupCriteria(this.hierarchyLogic(this.groupColumns, this.groupColumns.indexOf(col), col, priority)); } setSortCriteria(value: ISortCriteria | ISortCriteria[]) { const values = Array.isArray(value) ? value.slice() : [value]; const bak = this.sortCriteria.slice(); if (equalCriteria(values, bak)) { return false; } // update listener bak.forEach((d) => { d.col.on(Ranking.COLUMN_SORT_DIRTY, null!); }); values.forEach((d) => { d.col.on(Ranking.COLUMN_SORT_DIRTY, this.dirtyOrderSortDirty); }); this.sortCriteria.splice(0, this.sortCriteria.length, ...values.slice()); this.triggerResort(bak); return true; } setGroupCriteria(column: Column[] | Column) { const cols = Array.isArray(column) ? column : [column]; if (equalArrays(this.groupColumns, cols)) { return true; //same } this.groupColumns.forEach((groupColumn) => { groupColumn.on(Ranking.COLUMN_GROUP_DIRTY, null); }); const bak = this.groupColumns.slice(); this.groupColumns.splice(0, this.groupColumns.length, ...cols); this.groupColumns.forEach((groupColumn) => { groupColumn.on(Ranking.COLUMN_GROUP_DIRTY, this.dirtyOrderGroupDirty); }); this.fire( [ Ranking.EVENT_GROUP_CRITERIA_CHANGED, Ranking.EVENT_DIRTY_ORDER, Ranking.EVENT_DIRTY_HEADER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY_CACHES, Ranking.EVENT_DIRTY, ], bak, this.getGroupCriteria() ); this.autoAdaptAggregationColumn(); return true; } private autoAdaptAggregationColumn() { // set column auto adds two levels const length = this.groupColumns.reduce((acc, c) => acc + (c instanceof SetColumn ? 2 : 1), 0); const col = this.children.find((d) => d instanceof AggregateGroupColumn); if (!col) { return; } const targetWidth = length * AGGREGATION_LEVEL_WIDTH; if (targetWidth > col.getWidth()) { col.setWidth(targetWidth); } } toggleGroupSorting(col: Column) { return this.setGroupSortCriteria(this.toggleSortingLogic(col, this.groupSortCriteria)); } setGroupSortCriteria(value: ISortCriteria | ISortCriteria[]) { const values = Array.isArray(value) ? value.slice() : [value]; const bak = this.groupSortCriteria.slice(); if (equalCriteria(values, bak)) { return false; } bak.forEach((d) => { d.col.on(Ranking.COLUMN_GROUP_SORT_DIRTY, null!); }); values.forEach((d) => { d.col.on(Ranking.COLUMN_GROUP_SORT_DIRTY, this.dirtyOrderGroupSortDirty); }); this.groupSortCriteria.splice(0, this.groupSortCriteria.length, ...values.slice()); this.triggerGroupResort(bak); return true; } private triggerGroupResort(bak: ISortCriteria | ISortCriteria[] | null) { const sortCriterias = this.getGroupSortCriteria(); const bakMulti = Array.isArray(bak) ? bak : sortCriterias; this.fire( [ Ranking.EVENT_GROUP_SORT_CRITERIA_CHANGED, Ranking.EVENT_DIRTY_ORDER, Ranking.EVENT_DIRTY_HEADER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY, ], bakMulti, sortCriterias ); } private triggerResort(bak: ISortCriteria | ISortCriteria[] | null) { const sortCriterias = this.getSortCriteria(); const bakMulti = Array.isArray(bak) ? bak : sortCriterias; this.fire( [ Ranking.EVENT_SORT_CRITERIA_CHANGED, Ranking.EVENT_DIRTY_ORDER, Ranking.EVENT_DIRTY_HEADER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY, ], bakMulti, sortCriterias ); } get children() { return this.columns.slice(); } get length() { return this.columns.length; } insert(col: Column, index: number = this.columns.length) { this.columns.splice(index, 0, col); col.attach(this); this.forward(col, ...Ranking.FORWARD_COLUMN_EVENTS); col.on(`${Ranking.EVENT_FILTER_CHANGED}.order`, this.dirtyOrderFiltering); col.on(`${Column.EVENT_VISIBILITY_CHANGED}.ranking`, (oldValue, newValue) => this.fire( [ Ranking.EVENT_COLUMN_VISIBILITY_CHANGED, Ranking.EVENT_DIRTY_HEADER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY, ], col, oldValue, newValue ) ); this.fire( [Ranking.EVENT_ADD_COLUMN, Ranking.EVENT_DIRTY_HEADER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY], col, index ); if (col.isFiltered()) { this.dirtyOrderFiltering(); } return col; } move(col: Column, index: number = this.columns.length) { if (col.parent !== this) { // not a move operation! console.error('invalid move operation: ', col); return null; } const old = this.columns.indexOf(col); if (index === old) { // no move needed return col; } //delete first this.columns.splice(old, 1); // adapt target index based on previous index, i.e shift by one this.columns.splice(old < index ? index - 1 : index, 0, col); this.fire( [Ranking.EVENT_MOVE_COLUMN, Ranking.EVENT_DIRTY_HEADER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY], col, index, old ); return col; } moveAfter(col: Column, reference: Column) { const i = this.columns.indexOf(reference); if (i < 0) { return null; } return this.move(col, i + 1); } get fqpath() { return ''; } findByPath(fqpath: string): Column { let p: IColumnParent | Column = this as any; const indices = fqpath.split('@').map(Number).slice(1); //ignore the first entry = ranking while (indices.length > 0) { const i = indices.shift()!; p = (p as IColumnParent).at(i); } return p as Column; } indexOf(col: Column) { return this.columns.indexOf(col); } at(index: number) { return this.columns[index]; } insertAfter(col: Column, ref: Column) { const i = this.columns.indexOf(ref); if (i < 0) { return null; } return this.insert(col, i + 1); } push(col: Column) { return this.insert(col); } remove(col: Column) { const i = this.columns.indexOf(col); if (i < 0) { return false; } this.unforward(col, ...Ranking.FORWARD_COLUMN_EVENTS); const isSortCriteria = this.sortCriteria.findIndex((d) => d.col === col); const sortCriteriaChanged = isSortCriteria >= 0; if (sortCriteriaChanged) { this.sortCriteria.splice(isSortCriteria, 1); } const isGroupSortCriteria = this.groupSortCriteria.findIndex((d) => d.col === col); const groupSortCriteriaChanged = isGroupSortCriteria >= 0; if (groupSortCriteriaChanged) { this.groupSortCriteria.splice(isGroupSortCriteria, 1); } let newGrouping: Column[] | null = null; const isGroupColumn = this.groupColumns.indexOf(col); if (isGroupColumn >= 0) { // was my grouping criteria newGrouping = this.groupColumns.slice(); newGrouping.splice(isGroupColumn, 1); } col.detach(); this.columns.splice(i, 1); this.fire( [Ranking.EVENT_REMOVE_COLUMN, Ranking.EVENT_DIRTY_HEADER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY], col, i ); if (newGrouping) { this.setGroupCriteria(newGrouping); } else if (sortCriteriaChanged) { this.triggerResort(null); } else if (groupSortCriteriaChanged) { this.triggerGroupResort(null); } else if (col.isFiltered()) { this.dirtyOrderFiltering(); } return true; } clear() { if (this.columns.length === 0) { return; } this.sortCriteria.forEach((d) => { d.col.on(`${Column.EVENT_DIRTY_CACHES}.order`, null!); }); this.sortCriteria.splice(0, this.sortCriteria.length); this.groupSortCriteria.forEach((d) => { d.col.on(Ranking.COLUMN_GROUP_SORT_DIRTY, null!); }); this.groupSortCriteria.splice(0, this.groupSortCriteria.length); this.groupColumns.forEach((d) => { d.on(Ranking.COLUMN_GROUP_DIRTY, null!); }); this.groupColumns.splice(0, this.groupColumns.length); this.columns.forEach((col) => { this.unforward(col, ...Ranking.FORWARD_COLUMN_EVENTS); col.detach(); }); const removed = this.columns.splice(0, this.columns.length); this.fire( [ Ranking.EVENT_REMOVE_COLUMN, Ranking.EVENT_DIRTY_ORDER, Ranking.EVENT_DIRTY_HEADER, Ranking.EVENT_DIRTY_VALUES, Ranking.EVENT_DIRTY, ], removed ); } get flatColumns(): Column[] { const r: IFlatColumn[] = []; this.flatten(r, 0, Column.FLAT_ALL_COLUMNS); return r.map((d) => d.col); } find(idOrFilter: string | ((col: Column) => boolean)) { const filter = typeof idOrFilter === 'string' ? (col: Column) => col.id === idOrFilter : idOrFilter; const r = this.flatColumns; for (const v of r) { if (filter(v)) { return v; } } return null; } isFiltered() { return this.columns.some((d) => d.isFiltered()); } filter(row: IDataRow) { return this.columns.every((d) => d.filter(row)); } clearFilters() { return this.columns.map((d) => d.clearFilter()).some((d) => d); } findMyRanker() { return this; } get fqid() { return this.id; } /** * marks the header, values, or both as dirty such that the values are reevaluated * @param type specify in more detail what is dirty, by default whole column */ markDirty(type: 'header' | 'values' | 'all' = 'all') { switch (type) { case 'header': return this.fire([Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY]); case 'values': return this.fire([Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY]); default: return this.fire([ Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, Column.EVENT_DIRTY, ]); } } } function equalCriteria(a: ISortCriteria[], b: ISortCriteria[]) { if (a.length !== b.length) { return false; } return a.every((ai, i) => { const bi = b[i]; return ai.col === bi.col && ai.asc === bi.asc; }); }
the_stack
import { Injectable } from '@angular/core'; import * as Ro from '@nakedobjects/restful-objects'; import { Dictionary } from 'lodash'; import each from 'lodash-es/each'; import filter from 'lodash-es/filter'; import find from 'lodash-es/find'; import findKey from 'lodash-es/findKey'; import first from 'lodash-es/first'; import forEach from 'lodash-es/forEach'; import keys from 'lodash-es/keys'; import map from 'lodash-es/map'; import omit from 'lodash-es/omit'; import remove from 'lodash-es/remove'; import sortBy from 'lodash-es/sortBy'; import { Subject } from 'rxjs'; import { ConfigService } from './config.service'; import { LoggerService } from './logger.service'; import { RepLoaderService } from './rep-loader.service'; import { CollectionViewState, InteractionMode, Pane, PaneRouteData } from './route-data'; import { UrlManagerService } from './url-manager.service'; import { ErrorWrapper, ClientErrorCode, ErrorCategory } from './error.wrapper'; enum DirtyState { DirtyMustReload = 1, DirtyMayReload = 2, Clean = 3 } class DirtyList { private dirtyObjects: Dictionary<DirtyState> = {}; setDirty(oid: Ro.ObjectIdWrapper, alwaysReload: boolean = false) { this.setDirtyInternal(oid, alwaysReload ? DirtyState.DirtyMustReload : DirtyState.DirtyMayReload); } setDirtyInternal(oid: Ro.ObjectIdWrapper, dirtyState: DirtyState) { const key = oid.getKey(); this.dirtyObjects[key] = dirtyState; } getDirty(oid: Ro.ObjectIdWrapper) { const key = oid.getKey(); return this.dirtyObjects[key] || DirtyState.Clean; } clearDirty(oid: Ro.ObjectIdWrapper) { const key = oid.getKey(); this.dirtyObjects = omit(this.dirtyObjects, key) as Dictionary<DirtyState>; } clear() { this.dirtyObjects = {}; } } function isSameObject(object: Ro.DomainObjectRepresentation | null | undefined, type: string, id?: string) { if (object) { const sid = object.serviceId(); return sid ? sid === type : (object.domainType() === type && object.instanceId() === Ro.withNull(id)); } return false; } class TransientCache { private transientCache: [undefined, Ro.DomainObjectRepresentation[], Ro.DomainObjectRepresentation[]] = [undefined, [], []]; // per pane constructor(private readonly depth: number) { } add(paneId: Pane, obj: Ro.DomainObjectRepresentation) { let paneObjects = this.transientCache[paneId]!; if (paneObjects.length >= this.depth) { paneObjects = paneObjects.slice(-(this.depth - 1)); } paneObjects.push(obj); this.transientCache[paneId] = paneObjects; } get(paneId: Pane, type: string, id: string): Ro.DomainObjectRepresentation | null { const paneObjects = this.transientCache[paneId]!; return find(paneObjects, o => isSameObject(o, type, id)) || null; } remove(paneId: Pane, type: string, id: string) { let paneObjects = this.transientCache[paneId]!; paneObjects = remove(paneObjects, o => isSameObject(o, type, id)); this.transientCache[paneId] = paneObjects; } clear() { this.transientCache = [undefined, [], []]; } swap() { const [, t1, t2] = this.transientCache; this.transientCache[1] = t2; this.transientCache[2] = t1; } } class RecentCache { constructor(private readonly keySeparator: string, private readonly depth: number) { } private recentCache: Ro.DomainObjectRepresentation[] = []; add(obj: Ro.DomainObjectRepresentation) { // find any matching entries and remove them - should only be one remove(this.recentCache, i => i.id() === obj.id()); // push obj on top of array this.recentCache = [obj].concat(this.recentCache); // drop oldest if we're full if (this.recentCache.length > this.depth) { this.recentCache = this.recentCache.slice(0, this.depth); } } items(): Ro.DomainObjectRepresentation[] { return this.recentCache; } clear() { this.recentCache = []; } } class ValueCache { private currentValues: [undefined, Dictionary<Ro.Value>, Dictionary<Ro.Value>] = [undefined, {}, {}]; private currentId: [undefined, string, string] = [undefined, '', '']; addValue(id: string, valueId: string, value: Ro.Value, paneId: Pane) { if (this.currentId[paneId] !== id) { this.currentId[paneId] = id; this.currentValues[paneId] = {}; } this.currentValues[paneId]![valueId] = new Ro.Value(value); } getValue(id: string, valueId: string, paneId: Pane) { if (this.currentId[paneId] !== id) { this.currentId[paneId] = id; this.currentValues[paneId] = {}; } return this.currentValues[paneId]![valueId]; } getValues(id: string | null, paneId: Pane) { if (id && this.currentId[paneId] !== id) { this.currentId[paneId] = id; this.currentValues[paneId] = {}; } return this.currentValues[paneId] as Dictionary<Ro.Value>; } clear(paneId: Pane) { this.currentId[paneId] = ''; this.currentValues[paneId] = {}; } swap() { const [, i1, i2] = this.currentId; this.currentId[Pane.Pane1] = i2; this.currentId[Pane.Pane2] = i1; const [, v1, v2] = this.currentValues; this.currentValues[Pane.Pane1] = v2; this.currentValues[Pane.Pane2] = v1; } } @Injectable() export class ContextService { clearingDataFlag = false; constructor( private readonly urlManager: UrlManagerService, private readonly repLoader: RepLoaderService, private readonly configService: ConfigService, private readonly loggerService: LoggerService ) { } private pendingClearMessages = false; private pendingClearWarnings = false; private nextTransientId = 0; private currentError: ErrorWrapper | null = null; private previousUrl: string | null = null; private warningsSource = new Subject<string[]>(); private messagesSource = new Subject<string[]>(); warning$ = this.warningsSource.asObservable(); messages$ = this.messagesSource.asObservable(); private pendingPotentActionCount: [undefined, number, number] = [undefined, 0, 0]; private concurrencyErrorSource = new Subject<Ro.ObjectIdWrapper>(); concurrencyError$ = this.concurrencyErrorSource.asObservable(); private subTypeCache: Dictionary<Dictionary<Promise<boolean>>> = {}; private get keySeparator() { return this.configService.config.keySeparator; } // cached values private currentObjects: [undefined, Ro.DomainObjectRepresentation | null, Ro.DomainObjectRepresentation | null] = [undefined, null, null]; // per pane private transientCache = new TransientCache(this.configService.config.transientCacheDepth); private currentMenuList: Dictionary<Ro.MenuRepresentation> = {}; private currentServices: Ro.DomainServicesRepresentation | null = null; private currentMenus: Ro.MenusRepresentation | null = null; private currentVersion: Ro.VersionRepresentation | null = null; private currentUser: Ro.UserRepresentation | null = null; private readonly recentcache = new RecentCache(this.keySeparator, this.configService.config.recentCacheDepth); private readonly dirtyList = new DirtyList(); private currentLists: Dictionary<{ list: Ro.ListRepresentation; added: number }> = {}; private readonly parameterCache = new ValueCache(); private readonly objectEditCache = new ValueCache(); getFile = (object: Ro.DomainObjectRepresentation, url: string, mt: string) => { const isDirty = this.getIsDirty(object.getOid()); return this.repLoader.getFile(url, mt, isDirty); } setFile = (object: Ro.DomainObjectRepresentation, url: string, mt: string, file: Blob) => this.repLoader.uploadFile(url, mt, file); clearCachedFile = (url: string) => this.repLoader.clearCache(url); clearCachedCollections(obj: Ro.DomainObjectRepresentation) { each(obj.collectionMembers(), cm => { const details = cm.getDetails(); if (details) { const baseUrl = details.getUrl(); details.inlineItems(true); const inlineUrl = details.getUrl(); this.repLoader.clearCache(baseUrl); this.repLoader.clearCache(inlineUrl); } }); } // exposed for test mocking getDomainObject = (paneId: Pane, oid: Ro.ObjectIdWrapper, interactionMode: InteractionMode): Promise<Ro.DomainObjectRepresentation> => { const type = oid.domainType; const id = oid.instanceId; const dirtyState = this.dirtyList.getDirty(oid); // no need to reload forms const forceReload = interactionMode !== InteractionMode.Form && ((dirtyState === DirtyState.DirtyMustReload) || ((dirtyState === DirtyState.DirtyMayReload) && this.configService.config.autoLoadDirty)); if (!forceReload && isSameObject(this.currentObjects[paneId], type, id)) { return Promise.resolve(this.currentObjects[paneId]!); } // deeper cache for transients if (interactionMode === InteractionMode.Transient) { const transientObj = this.transientCache.get(paneId, type, id); const p: Promise<Ro.DomainObjectRepresentation> = transientObj ? Promise.resolve(transientObj) : Promise.reject(new ErrorWrapper(ErrorCategory.ClientError, ClientErrorCode.ExpiredTransient, '')); return p; } const object = new Ro.DomainObjectRepresentation(); object.hateoasUrl = `${this.configService.config.appPath}/objects/${type}/${id}`; object.setInlinePropertyDetails(interactionMode === InteractionMode.Edit); this.incPendingPotentActionOrReload(paneId); return this.repLoader.populate<Ro.DomainObjectRepresentation>(object, forceReload) .then((obj: Ro.DomainObjectRepresentation) => { this.currentObjects[paneId] = obj; if (forceReload) { this.dirtyList.clearDirty(oid); this.clearCachedCollections(obj); } this.cacheRecentlyViewed(obj); this.decPendingPotentActionOrReload(paneId); return Promise.resolve(obj); }) .catch((e) => { this.decPendingPotentActionOrReload(paneId); throw e; }); } private editOrReloadObject(paneId: Pane, object: Ro.DomainObjectRepresentation, inlineDetails: boolean) { const parms = Ro.inlinePropertyDetails(inlineDetails); return this.repLoader.retrieveFromLink<Ro.DomainObjectRepresentation>(object.selfLink(), parms) .then(obj => { this.currentObjects[paneId] = obj; const oid = obj.getOid(); this.dirtyList.clearDirty(oid); this.cacheRecentlyViewed(obj); return Promise.resolve(obj); }); } getIsDirty = (oid: Ro.ObjectIdWrapper) => !oid.isService && this.dirtyList.getDirty(oid) !== DirtyState.Clean; mustReload = (oid: Ro.ObjectIdWrapper) => { const dirtyState = this.dirtyList.getDirty(oid); return (dirtyState === DirtyState.DirtyMustReload) || ((dirtyState === DirtyState.DirtyMayReload) && this.configService.config.autoLoadDirty); } getObjectForEdit = (paneId: Pane, object: Ro.DomainObjectRepresentation) => this.editOrReloadObject(paneId, object, true); reloadObject = (paneId: Pane, object: Ro.DomainObjectRepresentation) => this.editOrReloadObject(paneId, object, false); getService = (paneId: Pane, serviceType: string): Promise<Ro.DomainObjectRepresentation> => { if (isSameObject(this.currentObjects[paneId], serviceType)) { return Promise.resolve(this.currentObjects[paneId]!); } return this.getServices() .then((services: Ro.DomainServicesRepresentation) => { const service = services.getService(serviceType); if (service) { return this.repLoader.populate(service); } return Promise.reject(`unknown service ${serviceType}`); }) .then((service: Ro.DomainObjectRepresentation) => { this.currentObjects[paneId] = service; return Promise.resolve(service); }); } getActionDetails = (actionMember: Ro.ActionMember): Promise<Ro.ActionRepresentation> => { const details = actionMember.getDetails(); if (details) { return this.repLoader.populate(details, true); } return Promise.reject(`Couldn't find details on ${actionMember.actionId()}`); } getCollectionDetails = (collectionMember: Ro.CollectionMember, state: CollectionViewState, ignoreCache: boolean): Promise<Ro.CollectionRepresentation> => { const details = collectionMember.getDetails(); if (details) { if (state === CollectionViewState.Table) { details.inlineItems(true); } const parent = collectionMember.parent; let isDirty = false; if (parent instanceof Ro.DomainObjectRepresentation) { const oid = parent.getOid(); isDirty = this.dirtyList.getDirty(oid) !== DirtyState.Clean; } return this.repLoader.populate(details, isDirty || ignoreCache); } return Promise.reject(`Couldn't find details on ${collectionMember.collectionId()}`); } getInvokableAction = (action: Ro.ActionMember | Ro.ActionRepresentation): Promise<Ro.InvokableActionMember | Ro.ActionRepresentation> => { if (action instanceof Ro.InvokableActionMember || action instanceof Ro.ActionRepresentation) { return Promise.resolve(action); } return this.getActionDetails(action); } getMenu = (menuId: string): Promise<Ro.MenuRepresentation> => { if (this.currentMenuList[menuId]) { return Promise.resolve(this.currentMenuList[menuId]); } return this.getMenus() .then((menus: Ro.MenusRepresentation) => { const menu = menus.getMenu(menuId); if (menu) { return this.repLoader.populate(menu); } return Promise.reject(`couldn't find menu ${menuId}`); }) .then((menu: Ro.MenuRepresentation) => { this.currentMenuList[menuId] = menu; return Promise.resolve(menu); }); } clearMessages = () => { if (this.pendingClearMessages) { this.messagesSource.next([]); } this.pendingClearMessages = !this.pendingClearMessages; } clearWarnings = () => { if (this.pendingClearWarnings) { this.warningsSource.next([]); } this.pendingClearWarnings = !this.pendingClearWarnings; } broadcastMessage = (m: string) => { this.pendingClearMessages = false; this.messagesSource.next([m]); } broadcastWarning = (w: string) => { this.pendingClearWarnings = false; this.warningsSource.next([w]); } getHome = () => { // for moment don't bother caching only called on startup and for whatever resaon cache doesn't work. // once version cached no longer called. return this.repLoader.populate<Ro.HomePageRepresentation>(new Ro.HomePageRepresentation({}, this.configService.config.appPath)); } getServices = () => { if (this.currentServices) { return Promise.resolve(this.currentServices); } return this.getHome() .then((home: Ro.HomePageRepresentation) => { const ds = home.getDomainServices(); return this.repLoader.populate<Ro.DomainServicesRepresentation>(ds); }) .then((services: Ro.DomainServicesRepresentation) => { this.currentServices = services; return Promise.resolve(services); }); } getMenus = () => { if (this.currentMenus) { return Promise.resolve(this.currentMenus); } return this.getHome() .then((home: Ro.HomePageRepresentation) => { const ds = home.getMenus(); return this.repLoader.populate<Ro.MenusRepresentation>(ds); }) .then((menus: Ro.MenusRepresentation) => { this.currentMenus = menus; return Promise.resolve(this.currentMenus); }); } getVersion = () => { if (this.currentVersion) { return Promise.resolve(this.currentVersion); } return this.getHome() .then((home: Ro.HomePageRepresentation) => { const v = home.getVersion(); return this.repLoader.populate<Ro.VersionRepresentation>(v); }) .then((version: Ro.VersionRepresentation) => { this.currentVersion = version; return Promise.resolve(version); }); } getUser = () => { if (this.currentUser) { return Promise.resolve(this.currentUser); } return this.getHome() .then((home: Ro.HomePageRepresentation) => { const u = home.getUser(); return this.repLoader.populate<Ro.UserRepresentation>(u); }) .then((user: Ro.UserRepresentation) => { this.currentUser = user; return Promise.resolve(user); }); } getObject = (paneId: Pane, oid: Ro.ObjectIdWrapper, interactionMode: InteractionMode) => { return oid.isService ? this.getService(paneId, oid.domainType) : this.getDomainObject(paneId, oid, interactionMode); } getCachedList = (paneId: Pane, page: number, pageSize: number) => { const index = this.urlManager.getListCacheIndex(paneId, page, pageSize); const entry = this.currentLists[index]; return entry ? entry.list : null; } clearCachedList = (paneId: Pane, page: number, pageSize: number) => { const index = this.urlManager.getListCacheIndex(paneId, page, pageSize); delete this.currentLists[index]; } private cacheList(list: Ro.ListRepresentation, index: string) { const entry = this.currentLists[index]; if (entry) { entry.list = list; entry.added = Date.now(); } else { if (keys(this.currentLists).length >= this.configService.config.listCacheSize) { // delete oldest; // TODO this looks wrong surely just "added" test ! // Fix "!" const oldest = first(sortBy(this.currentLists, 'e.added'))!.added; const oldestIndex = findKey(this.currentLists, (e: { added: number }) => e.added === oldest); if (oldestIndex) { delete this.currentLists[oldestIndex]; } } this.currentLists[index] = { list: list, added: Date.now() }; } } private handleResult = (paneId: Pane, result: Ro.ActionResultRepresentation, page: number, pageSize: number): Promise<Ro.ListRepresentation> => { if (result.resultType() === 'list') { const resultList = result.result().list() as Ro.ListRepresentation; // not null const index = this.urlManager.getListCacheIndex(paneId, page, pageSize); this.cacheList(resultList, index); return Promise.resolve(resultList); } else { return Promise.reject(new ErrorWrapper(ErrorCategory.ClientError, ClientErrorCode.WrongType, 'expect list')); } } private getList = (paneId: Pane, resultPromise: () => Promise<Ro.ActionResultRepresentation>, page: number, pageSize: number) => { return resultPromise().then(result => this.handleResult(paneId, result, page, pageSize)); } getActionExtensionsFromMenu = (menuId: string, actionId: string) => this.getMenu(menuId) .then(menu => Promise.resolve(menu.actionMember(actionId).extensions())) getActionExtensionsFromObject = (paneId: Pane, oid: Ro.ObjectIdWrapper, actionId: string) => this.getObject(paneId, oid, InteractionMode.View).then(object => Promise.resolve(object.actionMember(actionId).extensions())) getListFromMenu = (routeData: PaneRouteData, page?: number, pageSize?: number) => { const menuId = routeData.menuId; const actionId = routeData.actionId; const parms = routeData.actionParams; const state = routeData.state; const paneId = routeData.paneId; const newPage = page || routeData.page; const newPageSize = pageSize || routeData.pageSize; const urlParms = Ro.getPagingParms(newPage, newPageSize); if (state === CollectionViewState.Table) { Ro.inlineCollectionItems(true, urlParms); } const promise = () => this.getMenu(menuId).then(menu => this.getInvokableAction(menu.actionMember(actionId))).then(details => this.repLoader.invoke(details, parms, urlParms)); return this.getList(paneId, promise, newPage, newPageSize); } getListFromObject = (routeData: PaneRouteData, page?: number, pageSize?: number) => { const objectId = routeData.objectId; const actionId = routeData.actionId; const parms = routeData.actionParams; const state = routeData.state; const oid = Ro.ObjectIdWrapper.fromObjectId(objectId, this.keySeparator); const paneId = routeData.paneId; const newPage = page || routeData.page; const newPageSize = pageSize || routeData.pageSize; const urlParms = Ro.getPagingParms(newPage, newPageSize); if (state === CollectionViewState.Table) { Ro.inlineCollectionItems(true, urlParms); } const promise = () => this.getObject(paneId, oid, InteractionMode.View) .then(object => this.getInvokableAction(object.actionMember(actionId))) .then(details => this.repLoader.invoke(details, parms, urlParms)); return this.getList(paneId, promise, newPage, newPageSize); } setObject = (paneId: Pane, co: Ro.DomainObjectRepresentation) => this.currentObjects[paneId] = co; swapCurrentObjects = () => { this.parameterCache.swap(); this.objectEditCache.swap(); this.transientCache.swap(); const [, p1, p2] = this.currentObjects; this.currentObjects[1] = p2; this.currentObjects[2] = p1; } getError = () => this.currentError; setError = (e: ErrorWrapper) => this.currentError = e; getPreviousUrl = () => this.previousUrl; setPreviousUrl = (url: string) => this.previousUrl = url; private doPrompt = (field: Ro.IField, id: string, searchTerm: string | null, setupPrompt: (map: Ro.PromptMap) => void, objectValues: () => Dictionary<Ro.Value>, digest?: string | null) => { const promptMap = field.getPromptMap() as Ro.PromptMap; // not null promptMap.setMembers(objectValues); setupPrompt(promptMap); const addEmptyOption = field.entryType() !== Ro.EntryType.AutoComplete && field.extensions().optional(); return this.repLoader.retrieve(promptMap, Ro.PromptRepresentation, digest).then((p: Ro.PromptRepresentation) => p.choices(addEmptyOption)); } autoComplete = (field: Ro.IField, id: string, objectValues: () => Dictionary<Ro.Value>, searchTerm: string, digest?: string | null) => this.doPrompt(field, id, searchTerm, (promptMap: Ro.PromptMap) => promptMap.setSearchTerm(searchTerm), objectValues, digest) conditionalChoices = (field: Ro.IField, id: string, objectValues: () => Dictionary<Ro.Value>, args: Dictionary<Ro.Value>, digest?: string | null) => this.doPrompt(field, id, null, (promptMap: Ro.PromptMap) => promptMap.setArguments(args), objectValues, digest) setResult = (action: Ro.ActionRepresentation | Ro.InvokableActionMember, result: Ro.ActionResultRepresentation, fromPaneId: number, toPaneId: number, page: number, pageSize: number) => { if (!result.result().isNull()) { if (result.resultType() === 'object') { const resultObject = result.result().object()! as Ro.DomainObjectRepresentation; resultObject.keySeparator = this.keySeparator; if (resultObject.persistLink()) { // transient object const domainType = resultObject.extensions().domainType()!; resultObject.wrapped().domainType = domainType; resultObject.wrapped().instanceId = (this.nextTransientId++).toString(); resultObject.hateoasUrl = `/${domainType}/${this.nextTransientId}`; // copy the etag down into the object resultObject.etagDigest = result.etagDigest; this.setObject(toPaneId, resultObject); this.transientCache.add(toPaneId, resultObject); this.urlManager.pushUrlState(toPaneId); const interactionMode = resultObject.extensions().interactionMode() === 'transient' ? InteractionMode.Transient : InteractionMode.NotPersistent; this.urlManager.setObjectWithMode(resultObject, interactionMode, toPaneId); } else if (resultObject.selfLink()) { // persistent object // set the object here and then update the url. That should reload the page but pick up this object // so we don't hit the server again. // copy the etag down into the object resultObject.etagDigest = result.etagDigest; this.setObject(toPaneId, resultObject); // update angular cache const url = Ro.urlWithInlinePropertyDetailsFalse(resultObject); this.repLoader.addToCache(url, resultObject.wrapped()); // if render in edit must be a form if (resultObject.extensions().interactionMode() === 'form') { this.urlManager.pushUrlState(toPaneId); this.urlManager.setObjectWithMode(resultObject, InteractionMode.Form, toPaneId); } else { this.cacheRecentlyViewed(resultObject); this.urlManager.setObject(resultObject, toPaneId); } } else { this.loggerService.throw('ContextService:setResult result object without self or persist link'); } } else if (result.resultType() === 'list') { const resultList = result.result().list()!; const parms = this.parameterCache.getValues(action.actionId(), fromPaneId); const search = this.urlManager.setList(action, parms, fromPaneId, toPaneId); const index = this.urlManager.getListCacheIndexFromSearch(search, toPaneId, page, pageSize); this.cacheList(resultList, index); } } else if (result.resultType() === 'void') { this.urlManager.triggerPageReloadByFlippingReloadFlagInUrl(fromPaneId); } } incPendingPotentActionOrReload(paneId: Pane) { const count = this.pendingPotentActionCount[paneId]! + 1; this.pendingPotentActionCount[paneId] = count; } decPendingPotentActionOrReload(paneId: Pane) { let count = this.pendingPotentActionCount[paneId]! - 1; if (count < 0) { // should never happen count = 0; this.loggerService.warn('ContextService:decPendingPotentActionOrReload count less than 0'); } this.pendingPotentActionCount[paneId] = count; } isPendingPotentActionOrReload(paneId: Pane) { return this.pendingPotentActionCount[paneId]! > 0; } private setMessages(result: Ro.ActionResultRepresentation) { this.pendingClearMessages = this.pendingClearWarnings = false; const warnings = result.extensions().warnings() || []; const messages = result.extensions().messages() || []; this.warningsSource.next(warnings); this.messagesSource.next(messages); } setConcurrencyError(oid: Ro.ObjectIdWrapper) { this.concurrencyErrorSource.next(oid); } private invokeActionInternal( invokeMap: Ro.InvokeMap, action: Ro.ActionRepresentation | Ro.InvokableActionMember, fromPaneId: number, toPaneId: number, setDirty: () => void, gotoResult: boolean = false) { invokeMap.inlinePropertyDetails(false); if (action.extensions().returnType() === 'list' && action.extensions().renderEagerly()) { invokeMap.inlineCollectionItems(true); } return this.repLoader.retrieve(invokeMap, Ro.ActionResultRepresentation, action.parent.etagDigest) .then((result: Ro.ActionResultRepresentation) => { setDirty(); this.setMessages(result); if (gotoResult) { this.setResult(action, result, fromPaneId, toPaneId, 1, this.configService.config.defaultPageSize); } return result; }); } private getSetDirtyFunction(action: Ro.ActionRepresentation | Ro.InvokableActionMember, parms: Dictionary<Ro.Value>) { const parent = action.parent; if (action.isNotQueryOnly()) { const clearCacheIfNecessary = this.configService.config.clearCacheOnChange ? () => this.markDirtyAfterChange() : () => { }; if (parent instanceof Ro.DomainObjectRepresentation) { return () => { this.dirtyList.setDirty(parent.getOid()); this.setCurrentObjectsDirty(); clearCacheIfNecessary(); }; } if (parent instanceof Ro.CollectionRepresentation) { return () => { const selfLink = parent.selfLink(); const oid = Ro.ObjectIdWrapper.fromLink(selfLink, this.keySeparator); this.dirtyList.setDirty(oid); this.setCurrentObjectsDirty(); clearCacheIfNecessary(); }; } if (parent instanceof Ro.CollectionMember) { return () => { const memberParent = parent.parent; if (memberParent instanceof Ro.DomainObjectRepresentation) { this.dirtyList.setDirty(memberParent.getOid()); } this.setCurrentObjectsDirty(); clearCacheIfNecessary(); }; } if (parent instanceof Ro.ListRepresentation && parms) { const ccaParm = find(action.parameters(), p => p.isCollectionContributed()); const ccaId = ccaParm ? ccaParm.id() : null; const ccaValue = ccaId ? parms[ccaId] : null; // this should always be true if (ccaValue && ccaValue.isList()) { const refValues = filter(ccaValue.list()!, v => v.isReference()); const links = map(refValues, v => v.link()!); return () => { forEach(links, (l: Ro.Link) => this.dirtyList.setDirty(l.getOid(this.keySeparator))); this.setCurrentObjectsDirty(); clearCacheIfNecessary(); }; } } return () => { this.setCurrentObjectsDirty(); clearCacheIfNecessary(); }; } return () => { }; } invokeAction = (action: Ro.ActionRepresentation | Ro.InvokableActionMember, parms: Dictionary<Ro.Value>, fromPaneId = 1, toPaneId = 1, gotoResult: boolean = true) => { const invokeOnMap = (iAction: Ro.ActionRepresentation | Ro.InvokableActionMember) => { const im = iAction.getInvokeMap() as Ro.InvokeMap; each(parms, (parm, k) => im.setParameter(k!, parm)); const setDirty = this.getSetDirtyFunction(iAction, parms); return this.invokeActionInternal(im, iAction, fromPaneId, toPaneId, setDirty, gotoResult); }; return invokeOnMap(action); } private setNewObject(updatedObject: Ro.DomainObjectRepresentation, paneId: Pane, viewSavedObject: Boolean) { this.setObject(paneId, updatedObject); this.dirtyList.clearDirty(updatedObject.getOid()); if (viewSavedObject) { this.urlManager.setObject(updatedObject, paneId); } else { this.urlManager.popUrlState(paneId); } } private setDirtyIfNecessary() { if (this.configService.config.clearCacheOnChange) { this.markDirtyAfterChange(); this.setCurrentObjectsDirty(); } } updateObject = (object: Ro.DomainObjectRepresentation, props: Dictionary<Ro.Value>, paneId: Pane, viewSavedObject: boolean) => { const update = object.getUpdateMap(); each(props, (v, k) => update.setProperty(k!, v)); return this.repLoader.retrieve(update, Ro.DomainObjectRepresentation, object.etagDigest) .then((updatedObject: Ro.DomainObjectRepresentation) => { this.setDirtyIfNecessary(); // This is a kludge because updated object has no self link. const rawLinks = object.wrapped().links; updatedObject.wrapped().links = rawLinks; this.setNewObject(updatedObject, paneId, viewSavedObject); return Promise.resolve(updatedObject); }); } saveObject = (object: Ro.DomainObjectRepresentation, props: Dictionary<Ro.Value>, paneId: Pane, viewSavedObject: boolean) => { const persist = object.getPersistMap(); each(props, (v, k) => persist.setMember(k!, v)); return this.repLoader.retrieve(persist, Ro.DomainObjectRepresentation, object.etagDigest) .then((updatedObject: Ro.DomainObjectRepresentation) => { this.setDirtyIfNecessary(); this.transientCache.remove(paneId, object.domainType()!, object.id()); this.setNewObject(updatedObject, paneId, viewSavedObject); return Promise.resolve(updatedObject); }); } validateUpdateObject = (object: Ro.DomainObjectRepresentation, props: Dictionary<Ro.Value>) => { const update = object.getUpdateMap(); update.setValidateOnly(); each(props, (v, k) => update.setProperty(k!, v)); return this.repLoader.validate(update, object.etagDigest); } validateSaveObject = (object: Ro.DomainObjectRepresentation, props: Dictionary<Ro.Value>) => { const persist = object.getPersistMap(); persist.setValidateOnly(); each(props, (v, k) => persist.setMember(k!, v)); return this.repLoader.validate(persist, object.etagDigest); } isSubTypeOf = (toCheckType: string, againstType: string): Promise<boolean> => { if (this.subTypeCache[toCheckType] && typeof this.subTypeCache[toCheckType][againstType] !== 'undefined') { return this.subTypeCache[toCheckType][againstType]; } const isSubTypeOf = new Ro.DomainTypeActionInvokeRepresentation(againstType, toCheckType, this.configService.config.appPath); const promise = this.repLoader.populate(isSubTypeOf, true) .then((updatedObject: Ro.DomainTypeActionInvokeRepresentation) => { return updatedObject.value(); }) .catch((reject: ErrorWrapper) => { return false; }); const entry: Dictionary<Promise<boolean>> = {}; entry[againstType] = promise; this.subTypeCache[toCheckType] = entry; return promise; } private cacheRecentlyViewed(obj: Ro.DomainObjectRepresentation) { // never cache forms if (obj.extensions().interactionMode() !== 'form') { this.recentcache.add(obj); } } getRecentlyViewed = () => this.recentcache.items(); clearRecentlyViewed = () => { // clear both recent view and cached objects each(this.recentcache.items(), i => this.dirtyList.setDirty(i.getOid())); this.recentcache.clear(); } private markDirtyAfterChange = () => { each(this.recentcache.items(), i => this.dirtyList.setDirty(i.getOid())); this.currentLists = {}; } private setCurrentObjectsDirty = () => { const pane1Obj = this.currentObjects[Pane.Pane1]; const pane2Obj = this.currentObjects[Pane.Pane2]; const setDirty = (m: Ro.DomainObjectRepresentation | null | undefined) => { if (m) { this.dirtyList.setDirty(m.getOid()); } }; setDirty(pane1Obj); setDirty(pane2Obj); } private logoff() { for (let pane = 1; pane <= 2; pane++) { delete this.currentObjects[pane]; } this.currentServices = null; this.currentMenus = null; this.currentVersion = null; this.currentUser = null; this.transientCache.clear(); this.recentcache.clear(); this.dirtyList.clear(); // k will always be defined forEach(this.currentMenuList, (v, k) => delete this.currentMenuList[k!]); forEach(this.currentLists, (v, k) => delete this.currentLists[k!]); } cacheFieldValue = (dialogId: string, pid: string, pv: Ro.Value, paneId: Pane = Pane.Pane1) => { this.parameterCache.addValue(dialogId, pid, pv, paneId); } getDialogCachedValues = (dialogId: string | null = null, paneId: Pane = Pane.Pane1) => { return this.parameterCache.getValues(dialogId, paneId); } getObjectCachedValues = (objectId: string | null = null, paneId: Pane = Pane.Pane1) => { return this.objectEditCache.getValues(objectId, paneId); } clearDialogCachedValues = (paneId: Pane = Pane.Pane1) => { this.parameterCache.clear(paneId); } clearObjectCachedValues = (paneId: Pane = Pane.Pane1) => { this.objectEditCache.clear(paneId); } cachePropertyValue = (obj: Ro.DomainObjectRepresentation, p: Ro.PropertyMember, pv: Ro.Value, paneId: Pane = Pane.Pane1) => { this.dirtyList.setDirty(obj.getOid()); this.objectEditCache.addValue(obj.id(), p.id(), pv, paneId); } }
the_stack
* @module iModels */ import { Base64EncodedString } from "./Base64EncodedString"; import { DbQueryError, DbQueryRequest, DbQueryResponse, DbRequestExecutor, DbRequestKind, DbResponseStatus, DbValueFormat, QueryBinder, QueryOptions, QueryOptionsBuilder, QueryPropertyMetaData, QueryRowFormat, } from "./ConcurrentQuery"; /** @beta */ export class PropertyMetaDataMap implements Iterable<QueryPropertyMetaData> { private _byPropName = new Map<string, number>(); private _byJsonName = new Map<string, number>(); private _byNoCase = new Map<string, number>(); public constructor(public readonly properties: QueryPropertyMetaData[]) { for (const property of this.properties) { this._byPropName.set(property.name, property.index); this._byJsonName.set(property.jsonName, property.index); this._byNoCase.set(property.name.toLowerCase(), property.index); this._byNoCase.set(property.jsonName.toLowerCase(), property.index); } } public get length(): number { return this.properties.length; } public [Symbol.iterator](): Iterator<QueryPropertyMetaData, any, undefined> { return this.properties[Symbol.iterator](); } public findByName(name: string): QueryPropertyMetaData | undefined { const index = this._byPropName.get(name); if (typeof index === "number") { return this.properties[index]; } return undefined; } public findByJsonName(name: string): QueryPropertyMetaData | undefined { const index = this._byJsonName.get(name); if (typeof index === "number") { return this.properties[index]; } return undefined; } public findByNoCase(name: string): QueryPropertyMetaData | undefined { const index = this._byNoCase.get(name.toLowerCase()); if (typeof index === "number") { return this.properties[index]; } return undefined; } } /** * @beta */ export type QueryValueType = any; /** @beta */ export interface QueryRowProxy { toRow(): any; toArray(): QueryValueType[]; getMetaData(): QueryPropertyMetaData[]; [propertyName: string]: QueryValueType; [propertyIndex: number]: QueryValueType; } /** @beta */ export interface QueryStats { backendCpuTime: number; // Time spent running the query. It exclude query time in queue. Time is in microseconds. backendTotalTime: number; // backend total time spent running the query. Time is in milliseconds. backendMemUsed: number; // Estimated m emory used for query. Time is in milliseconds. backendRowsReturned: number; // Total rows returned by backend. totalTime: number; // Round trip time from client perspective.Time is in milliseconds. retryCount: number; } /** @beta */ export class ECSqlReader { private static readonly _maxRetryCount = 10; private _localRows: any[] = []; private _localOffset: number = 0; private _globalOffset: number = -1; private _globalCount: number = -1; private _done: boolean = false; private _globalDone: boolean = false; private _props = new PropertyMetaDataMap([]); private _param = new QueryBinder().serialize(); private _lockArgs: boolean = false; private _stats = { backendCpuTime: 0, backendTotalTime: 0, backendMemUsed: 0, backendRowsReturned: 0, totalTime: 0, retryCount: 0 }; private _rowProxy = new Proxy<ECSqlReader>(this, { get: (target: ECSqlReader, key: string | Symbol) => { if (typeof key === "string") { const idx = Number.parseInt(key, 10); if (!Number.isNaN(idx)) { return target.getRowInternal()[idx]; } const prop = target._props.findByNoCase(key); if (prop) { return target.getRowInternal()[prop.index]; } if (key === "getMetaData") { return () => target._props.properties; } if (key === "toRow") { return () => target.formatCurrentRow(true); } if (key === "getArray" || key === "toJSON") { return () => this.getRowInternal(); } } return undefined; }, has: (target: ECSqlReader, p: string | symbol) => { return !target._props.findByNoCase(p as string); }, ownKeys: (target: ECSqlReader) => { const keys = []; for (const prop of target._props) { keys.push(prop.name); } return keys; }, }); private _options: QueryOptions = new QueryOptionsBuilder().getOptions(); /** @internal */ public constructor(private _executor: DbRequestExecutor<DbQueryRequest, DbQueryResponse>, public readonly query: string, param?: QueryBinder, options?: QueryOptions) { if (query.trim().length === 0) { throw new Error("expecting non-empty ecsql statement"); } if (param) { this._param = param.serialize(); } this.reset(options); } private static replaceBase64WithUint8Array(row: any) { for (const key of Object.keys(row)) { const val = row[key]; if (typeof val === "string") { if (Base64EncodedString.hasPrefix(val)) { row[key] = Base64EncodedString.toUint8Array(val); } } else if (typeof val === "object" && val !== null) { this.replaceBase64WithUint8Array(val); } } } public setParams(param: QueryBinder) { if (this._lockArgs) { throw new Error("call resetBindings() before setting or changing parameters"); } this._param = param.serialize(); } public reset(options?: QueryOptions) { if (options) { this._options = options; } this._props = new PropertyMetaDataMap([]); this._localRows = []; this._globalDone = false; this._globalOffset = 0; this._globalCount = -1; if (typeof this._options.rowFormat === "undefined") this._options.rowFormat = QueryRowFormat.UseECSqlPropertyIndexes; if (this._options.limit) { if (typeof this._options.limit.offset === "number" && this._options.limit.offset > 0) this._globalOffset = this._options.limit.offset; if (typeof this._options.limit.count === "number" && this._options.limit.count > 0) this._globalCount = this._options.limit.count; } this._done = false; } public get current(): QueryRowProxy { return (this._rowProxy as any); } // clear all bindings public resetBindings() { this._param = new QueryBinder().serialize(); this._lockArgs = false; } // return if there is any more rows available public get done(): boolean { return this._done; } public getRowInternal(): any[] { if (this._localRows.length <= this._localOffset) throw new Error("no current row"); return this._localRows[this._localOffset] as any[]; } // return performance related statistics for current query. public get stats(): QueryStats { return this._stats; } private async readRows(): Promise<any[]> { if (this._globalDone) { return []; } this._lockArgs = true; this._globalOffset += this._localRows.length; this._globalCount -= this._localRows.length; if (this._globalCount === 0) { return []; } const valueFormat = this._options.rowFormat === QueryRowFormat.UseJsPropertyNames? DbValueFormat.JsNames :DbValueFormat.ECSqlNames; const request: DbQueryRequest = { ... this._options, kind: DbRequestKind.ECSql, valueFormat, query: this.query, args: this._param, }; request.includeMetaData = this._props.length > 0 ? false : true; request.limit = { offset: this._globalOffset, count: this._globalCount < 1 ? -1 : this._globalCount }; const resp = await this.runWithRetry(request); this._globalDone = resp.status === DbResponseStatus.Done; if (this._props.length === 0 && resp.meta.length > 0) { this._props = new PropertyMetaDataMap(resp.meta); } for (const row of resp.data) { ECSqlReader.replaceBase64WithUint8Array(row); } return resp.data; } private async runWithRetry(request: DbQueryRequest) { const needRetry = (rs: DbQueryResponse) => (rs.status === DbResponseStatus.Partial || rs.status === DbResponseStatus.QueueFull || rs.status === DbResponseStatus.Timeout) && (rs.data.length === 0); const updateStats = (rs: DbQueryResponse) => { this._stats.backendCpuTime += rs.stats.cpuTime; this._stats.backendTotalTime += rs.stats.totalTime; this._stats.backendMemUsed += rs.stats.memUsed; this._stats.backendRowsReturned += rs.data.length; }; const execQuery = async (req: DbQueryRequest) => { const startTime = Date.now(); const rs = await this._executor.execute(req); this.stats.totalTime += (Date.now() - startTime); return rs; }; let retry = ECSqlReader._maxRetryCount; let resp = await execQuery(request); DbQueryError.throwIfError(resp, request); while (--retry > 0 && needRetry(resp)) { resp = await execQuery(request); this._stats.retryCount += 1; if (needRetry(resp)) { updateStats(resp); } } if (retry === 0 && needRetry(resp)) { throw new Error("query too long to execute or server is too busy"); } updateStats(resp); return resp; } public formatCurrentRow(onlyReturnObject: boolean = false): any[] | object { if (!onlyReturnObject && this._options.rowFormat === QueryRowFormat.UseECSqlPropertyIndexes) { return this.getRowInternal(); } const formattedRow = {}; for (const prop of this._props) { const propName = this._options.rowFormat === QueryRowFormat.UseJsPropertyNames ? prop.jsonName : prop.name; const val = this.getRowInternal()[prop.index]; if (typeof val !== "undefined" && val !== null) { Object.defineProperty(formattedRow, propName, { value: val, enumerable: true, }); } } return formattedRow; } public async getMetaData(): Promise<QueryPropertyMetaData[]> { if (this._props.length === 0) { await this.fetchRows(); } return this._props.properties; } private async fetchRows() { this._localOffset = -1; this._localRows = await this.readRows(); if (this._localRows.length === 0) { this._done = true; } } public async step(): Promise<boolean> { if (this._done) { return false; } const cachedRows = this._localRows.length; if (this._localOffset < cachedRows - 1) { ++this._localOffset; } else { await this.fetchRows(); this._localOffset = 0; return !this._done; } return true; } public async toArray(): Promise<any[]> { const rows = []; while (await this.step()) { rows.push(this.formatCurrentRow()); } return rows; } }
the_stack
import Adapt, { AdaptElement, BuildData, BuildHelpers, BuildNotImplemented, BuiltinProps, childrenToArray, DeferredComponent, gql, Handle, isElement, isHandle, isMountedElement, ObserveForStatus, waiting, WithChildren } from "@adpt/core"; import { InternalError, Omit, removeUndef } from "@adpt/utils"; import ld from "lodash"; import { ClusterInfo, computeNamespaceFromMetadata, LabelSelector, LocalObjectReference, Metadata, ResourceProps, ResourcePropsWithConfig } from "./common"; import { ContainerSpec, isK8sContainerElement, K8sContainer, K8sContainerProps } from "./Container"; import { K8sObserver } from "./k8s_observer"; import { registerResourceKind, resourceElementToName, resourceIdToName } from "./manifest_support"; import { isResource, Resource } from "./Resource"; import { isServiceAccountProps } from "./ServiceAccount"; /** @public */ export interface NodeSelectorRequirement { /** The label key that the selector applies to. */ key: string; /** * Represents a key's relationship to a set of values. * * Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. */ operator: "In" | "NotIn" | "Exists" | "DoesNotExist" | "Gt" | "Lt"; /** * Values for operator * * If the operator is In or NotIn, the values array must be non-empty. * If the operator is Exists or DoesNotExist, the values array must be empty. * If the operator is Gt or Lt, the values array must have a single element, * which will be interpreted as an integer. * This array is replaced during a strategic merge patch. */ values: string[]; } /** @public */ export interface NodeSelectorTerm { /** A list of node selector requirements by node's labels. */ matchExpressions?: NodeSelectorRequirement[]; /** A list of node selector requirements by node's fields. */ matchFields?: NodeSelectorRequirement []; } /** @public */ export interface PreferredSchedulingTerm { /** * A node selector term, associated with the corresponding weight. */ preference: NodeSelectorTerm; /** Weight associated with matching the corresponding nodeSelectorTerm, in the range 1-100. */ weight: number; } /** @public */ export interface NodeSelector { /** A list of node selector terms. The terms are ORed */ nodeSelectorTerms: NodeSelectorTerm[]; } /** @public */ export interface NodeAffinity { // tslint:disable-next-line: max-line-length /** The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding "weight" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred. */ preferredDuringSchedulingIgnoredDuringExecution?: PreferredSchedulingTerm[]; // tslint:disable-next-line: max-line-length /** If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node. */ requiredDuringSchedulingIgnoredDuringExecution?: NodeSelector; } /** @public */ export interface PodAffinityTerm { /** * Label query over a set of resources, in this case pods. */ labelSelector: LabelSelector; // tslint:disable-next-line: max-line-length /** Specifies which namespaces the labelSelector applies to (matches against); null or empty list means "this pod's namespace" */ namespaces?: string[]; // tslint:disable-next-line: max-line-length /** This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching the labelSelector in the specified namespaces, where co-located is defined as running on a node whose value of the label with key topologyKey matches that of any node on which any of the selected pods is running. Empty topologyKey is not allowed. */ topologyKey: string; } /** @public */ export interface WeightedPodAffinityTerm { /** A pod affinity term, associated with the corresponding weight. */ podAffinityTerm: PodAffinityTerm; /** * weight associated with matching the corresponding podAffinityTerm, in the range 1-100. */ weight: number; } /** @public */ export interface PodAffinity { // tslint:disable max-line-length /** * The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. * * The node that is most preferred is the one with the greatest sum of weights, * i.e. for each node that meets all of the scheduling requirements (resource request, * requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating * through the elements of this field and adding "weight" to the sum if the node has pods * which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred. */ // tslint:enable max-line-length preferredDuringSchedulingIgnoredDuringExecution: WeightedPodAffinityTerm[]; // tslint:disable max-line-length /** * If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. * * If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied. */ // tslint:enable max-line-length requiredDuringSchedulingIgnoredDuringExecution: PodAffinityTerm[]; } /** @public */ export interface PodAntiAffinity { // tslint:disable-next-line: max-line-length /** The scheduler will prefer to schedule pods to nodes that satisfy the anti-affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling anti-affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding "weight" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred. */ preferredDuringSchedulingIgnoredDuringExecution: WeightedPodAffinityTerm[]; // tslint:disable-next-line: max-line-length /** If the anti-affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the anti-affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied. */ requiredDuringSchedulingIgnoredDuringExecution: PodAffinity; } /** @public */ export interface Affinity { /** Describes node affinity scheduling rules for the pod. */ nodeAffinity: NodeAffinity; // tslint:disable-next-line: max-line-length /** Describes pod affinity scheduling rules (e.g. co-locate this pod in the same node, zone, etc. as some other pod(s)). */ podAffinity: PodAffinity; // tslint:disable-next-line: max-line-length /** PodAntiAffinity Describes pod anti-affinity scheduling rules (e.g. avoid putting this pod in the same node, zone, etc. as some other pod(s)). */ podAntiAffinity: PodAntiAffinity; } /** @public */ export interface PodDNSConfigOption { name: string; value?: string; } /** @public */ export interface PodDNSConfig { /** * A list of DNS name server IP addresses. * * This will be appended to the base nameservers generated from DNSPolicy. Duplicated nameservers will be removed. */ nameservers: string[]; /** * A list of DNS resolver options. * * This will be merged with the base options generated from DNSPolicy. * Duplicated entries will be removed. * Resolution options given in Options will override those that appear in the base DNSPolicy. */ options: PodDNSConfigOption[]; /** * A list of DNS search domains for host-name lookup. * * This will be appended to the base search paths generated from DNSPolicy. Duplicated search paths will be removed. */ searches: string[]; } /** @public */ interface HostAlias { /** * Hostnames for the above IP address. */ hostnames: string[]; /** * IP address of the host file entry. */ ip: string; } /** @public */ export interface PodReadinessGate { /** Refers to a condition in the pod's condition list with matching type. */ conditionType: string; } /** @public */ export interface SELinuxOptions { /** SELinux level label that applies to the container. */ level: string; /** SELinux role label that applies to the container. */ role: string; /** SELinux type label that applies to the container. */ type: string; /** SELinux user label that applies to the container */ user: string; } /** @public */ export interface SeccompProfile { /** * Indicates a profile defined in a file on the node should be used. * * The profile must be preconfigured on the node to work. * Must be a descending path, relative to the kubelet's configured seccomp profile location. * Must only be set if type is "Localhost". */ localhostProfile?: string; /** * Indicates which kind of seccomp profile will be applied. * * Valid options are: * * Localhost - a profile defined in a file on the node should be used. * * RuntimeDefault - the container runtime default profile should be used. * * Unconfined - no profile should be applied. */ type: "Localhost" | "RuntimeDefault" | "Unconfined"; } /** @public */ export interface Sysctl { name: string; value: string; } /** @public */ export interface WindowsSecurityContextOptions { // tslint:disable max-line-length /** * The GMSA admission webhook ({@link https://github.com/kubernetes-sigs/windows-gmsa}) inlines the contents of the GMSA credential spec named by the GMSACredentialSpecName field. */ // tslint:enable max-line-length gmsaCredentialSpec?: string; /** * GMSACredentialSpecName is the name of the GMSA credential spec to use. */ gmsaCredentialSpecName?: string; /** * The UserName in Windows to run the entrypoint of the container process. * * Defaults to the user specified in image metadata if unspecified. May also be set in PodSecurityContext. * If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. */ runAsUserName?: string; } /** @public */ export interface PodSecurityContext { /** * A special supplemental group that applies to all containers in a pod. * * Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod: * * 1. The owning GID will be the FSGroup * 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) * 3. The permission bits are OR'd with rw-rw---- * * If unset, the Kubelet will not modify the ownership and permissions of any volume. */ fsGroup?: number; /** * Defines behavior of changing ownership and permission of the volume before being exposed inside Pod. * * This field will only apply to volume types which support fsGroup based ownership(and permissions). * It will have no effect on ephemeral volume types such as: secret, configmaps and emptydir. * Valid values are "OnRootMismatch" and "Always". If not specified defaults to "Always". * * @defaultValue Always */ fsGroupChangePolicy?: "OnRootMismatch" | "Always"; /** * The GID to run the entrypoint of the container process. * * Uses runtime default if unset. May also be set in SecurityContext. * If set in both SecurityContext and PodSecurityContext, the value specified in * SecurityContext takes precedence for that container. */ runAsGroup?: number; /** * Indicates that the container must run as a non-root user. * * If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and * fail to start the container if it does. If unset or false, no such validation will be performed. * May also be set in SecurityContext. * If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. */ runAsNonRoot?: boolean; /** * The UID to run the entrypoint of the container process. * * Defaults to user specified in image metadata if unspecified. * May also be set in SecurityContext. * If set in both SecurityContext and PodSecurityContext, the value specified in * SecurityContext takes precedence for that container. */ runAsUser?: number; /** * The SELinux context to be applied to all containers. * * If unspecified, the container runtime will allocate a random SELinux context for each container. * May also be set in SecurityContext. * If set in both SecurityContext and PodSecurityContext, the value specified in * SecurityContext takes precedence for that container. */ seLinuxOptions?: SELinuxOptions; /** * The seccomp options to use by the containers in this pod. */ seccompProfile?: SeccompProfile; /** * A list of groups applied to the first process run in each container, in addition to the container's primary GID. * * If unspecified, no groups will be added to any container. */ supplementalGroups?: number[]; /** * Sysctls hold a list of namespaced sysctls used for the pod. * * Pods with unsupported sysctls (by the container runtime) might fail to launch. */ sysctls?: Sysctl[]; /** * The Windows specific settings applied to all containers. * * If unspecified, the options within a container's SecurityContext will be used. * If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. */ windowsOptions: WindowsSecurityContextOptions; } /** @public */ export interface Toleration { /** * Indicates the taint effect to match. * * Empty means match all taint effects. * When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. */ effect?: "NoSchedule" | "PreferNoSchedule" | "NoExecute"; /** * The taint key that the toleration applies to. * * Empty means match all taint keys. * If the key is empty, operator must be Exists; * this combination means to match all values and all keys. */ key?: string; /** * Represents a key's relationship to the value. * * Valid operators are Exists and Equal. * Defaults to Equal. * Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category. * * @defaultValue Equal */ operator?: "Exists" | "Equal"; // tslint:disable max-line-length /** * Represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. * * By default, it is not set, which means tolerate the taint forever (do not evict). * Zero and negative values will be treated as 0 (evict immediately) by the system. */ // tslint:enable max-line-length tolerationSeconds?: number; /** * Value is the taint value the toleration matches to. * * If the operator is Exists, the value should be empty, otherwise just a regular string. */ value?: string; } /** @public */ export interface TopologySpreadConstraint { /** * Used to find matching pods. * * Pods that match this label selector are counted to determine the * number of pods in their corresponding topology domain. */ labelSelector: LabelSelector; /** * Describes the degree to which pods may be unevenly distributed. * * When `whenUnsatisfiable=DoNotSchedule`, it is the maximum permitted * difference between the number of matching pods in the target topology * and the global minimum. * For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with * the same labelSelector spread as 1/1/0: | zone1 | zone2 | zone3 | | P | P | | * - if MaxSkew is 1, incoming pod can only be scheduled to zone3 to become 1/1/1; * scheduling it onto zone1(zone2) would make the ActualSkew(2-0) on zone1(zone2) violate MaxSkew(1). * - if MaxSkew is 2, incoming pod can be scheduled onto any zone. * When `whenUnsatisfiable=ScheduleAnyway`, it is used to give higher precedence to topologies that satisfy it. * It's a required field. Default value is 1 and 0 is not allowed. * * @example * * @defaultValue 1 */ maxSkew: number; /** * The key of node labels. * * Nodes that have a label with this key and identical values are considered to be in the same topology. * We consider each \<key, value\> as a "bucket", and try to put balanced number of pods into each bucket. * It's a required field. */ topologyKey: string; /** * Indicates how to deal with a pod if it doesn't satisfy the spread constraint. * * - DoNotSchedule (default) tells the scheduler not to schedule it. * - ScheduleAnyway tells the scheduler to schedule the pod in any location, * but giving higher precedence to topologies that would help reduce the skew. * * A constraint is considered "Unsatisfiable" for an incoming pod if and only if every possible * node assigment for that pod would violate "MaxSkew" on some topology. * For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector * spread as 3/1/1: | zone1 | zone2 | zone3 | | P P P | P | P | If WhenUnsatisfiable is set to DoNotSchedule, * incoming pod can only be scheduled to zone2(zone3) to become 3/2/1(3/1/2) * as ActualSkew(2-1) on zone2(zone3) satisfies MaxSkew(1). * In other words, the cluster can still be imbalanced, but scheduler won't make it * *more* imbalanced. * * It's a required field. */ whenUnsatisfiable: string; } /** @public */ export interface KeyToPath { /** The key to project. */ key: string; /** * mode bits to use on this file, * Must be a value between 0 and 0777. * If not specified, the volume defaultMode will be used. * This might be in conflict with other options that affect the file mode, like fsGroup, * and the result can be other mode bits set. */ mode?: number; /** * The relative path of the file to map the key to. * * May not be an absolute path. May not contain the path element '..'. May not start with the string '..'. */ path: string; } /** @public */ export interface ConfigMapVolumeSource { /** * mode bits to use on created files by default. * * Must be a value between 0 and 0777. Defaults to 0644. * Directories within the path are not affected by this setting. * This might be in conflict with other options that affect the file mode, * like fsGroup, and the result can be other mode bits set. */ defaultMode?: number; //tslint:disable max-line-length /** * If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. * * If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. * If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. * Paths must be relative and may not contain the '..' path or start with '..'. */ //tslint:enable max-line-length items?: KeyToPath[]; /** * Name of the referent. * * More info: {@link https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names} */ name: string | Handle; /** Specify whether the ConfigMap or its keys must be defined */ optional?: boolean; } /** @public */ export interface SecretVolumeSource { /** * mode bits to use on created files by default. * * Must be a value between 0 and 0777. Defaults to 0644. * Directories within the path are not affected by this setting. * This might be in conflict with other options that affect the file mode, * like fsGroup, and the result can be other mode bits set. */ defaultMode?: number; //tslint:disable max-line-length /** * If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. * * If specified, the listed keys will be projected into the specified paths, * and unlisted keys will not be present. If a key is specified which is not * present in the Secret, the volume setup will error unless it is marked optional. * * Paths must be relative and may not contain the '..' path or start with '..'. */ //tslint:enable max-line-length items?: KeyToPath[]; /** Specify whether the Secret or its keys must be defined */ optional?: boolean; /** * Name of the secret in the pod's namespace to use. * * More info: {@link https://kubernetes.io/docs/concepts/storage/volumes#secret} */ secretName: string | Handle; } /** @public */ export interface EmptyDirVolumeSource { /** * What type of storage medium should back this directory. * * The default is "" which means to use the node's default medium. * Must be an empty string (default) or Memory. * More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir */ medium: string; /** * Total amount of local storage required for this EmptyDir volume. * * The size limit is also applicable for memory medium. * The maximum usage on memory medium EmptyDir would be the minimum * value between the SizeLimit specified here and the sum of memory limits of all containers in a pod. * The default is nil which means that the limit is undefined. * More info: {@link http://kubernetes.io/docs/user-guide/volumes#emptydir} */ sizeLimit: string; } /** * Volumes for {@link k8s.PodProps} * * @public */ export interface Volume { /** * Volume's name. * * Must be a DNS_LABEL and unique within the pod. * * More info: {@link https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names} */ name: string; /** * Represents a configMap that should populate this volume */ configMap?: ConfigMapVolumeSource; /** * EmptyDir represents a temporary directory that shares a pod's lifetime. * * More info: {@link https://kubernetes.io/docs/concepts/storage/volumes#emptydir} * */ emptyDir?: EmptyDirVolumeSource; /** * Represents a secret that should populate this volume. * * More info: {@link https://kubernetes.io/docs/concepts/storage/volumes#secret} */ secret?: SecretVolumeSource; /** Other k8s volume kinds not typed yet for \@adpt/cloud */ [key: string]: any; } /** * Props for the {@link k8s.Pod} component * * @public */ export interface PodProps extends WithChildren { /** * True is this is a template for use in a controller, false otherwise * @defaultValue false */ isTemplate: boolean; /** Information about the k8s cluster (ip address, auth info, etc.) */ config?: ClusterInfo; /** k8s metadata */ metadata: Metadata; // tslint:disable max-line-length /** * Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. * * Value must be a positive integer. */ // tslint:enable max-line-length activeDeadlineSeconds?: number; /** If specified, the pod's scheduling constraints */ affinity?: Affinity; /** AutomountServiceAccountToken indicates whether a service account token should be automatically mounted. */ automountServiceAccountToken?: boolean; /** * Specifies the DNS parameters of a pod. * * Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy. */ dnsConfig?: PodDNSConfig; /** * Set DNS policy for the pod. * * Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. * DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. * To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly * to 'ClusterFirstWithHostNet'. * * @defaultValue ClusterFirst */ dnsPolicy: "ClusterFirstWithHostNet" | "ClusterFirst" | "Default" | "None"; //tslint:disable max-line-length /** * Indicates whether information about services should be injected into pod's environment variables matching the syntax of Docker links. * * @defaultValue true */ //tslint:enable max-line-length enableServiceLinks: boolean; /** * An optional list of hosts and IPs that will be injected into the pod's hosts file if specified. * * This is only valid for non-hostNetwork pods. */ hostAliases?: HostAlias[]; /** * Use the host's ipc namespace. * @defaultValue false */ hostIPC: boolean; /** * Host networking requested for this pod. * * Use the host's network namespace. * If this option is set, the ports that will be used must be specified. Default to false. */ hostNetwork?: boolean; /** * Use the host's pid namespace. * @defaultValue false */ hostPID: boolean; /** * Specifies the hostname of the Pod. * * If not specified, the pod's hostname will be set to a system-defined value. */ hostname?: string; /** * List of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. * * If specified, these secrets will be passed to individual puller implementations for them to use. * For example, in the case of docker, only DockerConfig type secrets are honored. * More info: {@link https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod} */ imagePullSecrets?: LocalObjectReference[]; /** * A request to schedule this pod onto a specific node. * * If it is non-empty, the scheduler simply schedules this pod onto that node, * assuming that it fits resource requirements. */ nodeName?: string; /** * A selector which must be true for the pod to fit on a node. * * Selector which must match a node's labels for the pod to be scheduled on that node. * More info: {@link https://kubernetes.io/docs/concepts/configuration/assign-pod-node/} */ nodeSelector?: { [label: string]: boolean | string }; /** * Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. * * This field will be autopopulated at admission time by the RuntimeClass admission controller. * If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. * The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. * If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in * the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. * * More info: {@link https://git.k8s.io/enhancements/keps/sig-node/20190226-pod-overhead.md} * * This field is alpha-level as of Kubernetes v1.16, and is only honored by servers that enable * the PodOverhead feature. * @alpha */ overhead?: unknown; /** * PreemptionPolicy is the Policy for preempting pods with lower priority. * * This field is beta-level, gated by the NonPreemptingPriority feature-gate. * * @defaultValue PreemptLowerPriority * @beta */ preemptionPolicy?: "Never" | "PreemptLowerPriority"; /** * The priority various system components use this field to find the priority of the pod. * * When Priority Admission Controller is enabled, it prevents users from setting this field. * The admission controller populates this field from PriorityClassName. * The higher the value, the higher the priority. */ priority?: number; /** * If specified, indicates the pod's priority. * * "system-node-critical" and "system-cluster-critical" are two special keywords which indicate the highest * priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass * object with that name. If not specified, the pod priority will be default or zero if there is no default. */ priorityClassName?: string; /** * If specified, all readiness gates will be evaluated for pod readiness. * * A pod is ready when all its containers are ready AND all conditions specified * in the readiness gates have status equal to "True" * * More info: {@link https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-readiness-gate} */ readinessGates?: PodReadinessGate[]; /** * Restart policy for all containers within the pod. * * One of Always, OnFailure, Never. Default to Always. * More info: {@link https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy} * * @defaultValue Always */ restartPolicy: "Always" | "OnFailure" | "Never"; // tslint:disable max-line-length /** * Refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. * * If no RuntimeClass resource matches the named class, the pod will not be run. * If unset or empty, the "legacy" RuntimeClass will be used, which is an implicit * class with an empty definition that uses the default runtime handler. * * More info: {@link https://kubernetes.io/docs/concepts/containers/runtime-class/} * * This is a beta feature as of Kubernetes v1.14. */ runtimeClassName?: string; // tslint:enable max-line-length /** * If specified, the pod will be dispatched by specified scheduler. * If not specified, the pod will be dispatched by default scheduler. */ schedulerName?: string; /** * SecurityContext holds pod-level security attributes and common container settings. * See type description for default values of each field. * * @defaultValue \{\} */ securityContext: PodSecurityContext; /** * ServiceAccountName is the name of the ServiceAccount to use to run this pod. * More info: {@link https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/} */ serviceAccountName?: string | Handle; /** * If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). * In Linux containers, this means setting the FQDN in the hostname field of the kernel * (the nodename field of struct utsname). * In Windows containers, this means setting the registry value of hostname for the registry key * HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters to FQDN. * If a pod does not have FQDN, this has no effect. * * @defaultValue false */ setHostnameAsFQDN?: boolean; /** * Share a single process namespace between all of the containers in a pod. * When this is set containers will be able to view and signal processes from other containers in the same pod, * and the first process in each container will not be assigned PID 1. * HostPID and ShareProcessNamespace cannot both be set. * * @defaultValue false */ shareProcessNamespace: boolean; // tslint:disable max-line-length /** * If specified, the fully qualified Pod hostname will be "\<hostname\>.\<subdomain\>.\<pod namespace\>.svc.\<cluster domain\>". * If not specified, the pod will not have a domainname at all. */ subdomain?: string; // tslint:enable max-line-length /** * Optional duration in seconds the pod needs to terminate gracefully. * * May be decreased in delete request. Value must be non-negative integer. * The value zero indicates delete immediately. If this value is nil, the default * grace period will be used instead. The grace period is the duration in seconds * after the processes running in the pod are sent a termination signal and the time * when the processes are forcibly halted with a kill signal. Set this value longer * than the expected cleanup time for your process. Defaults to 30 seconds. */ terminationGracePeriodSeconds?: number; /** If specified, the pod's tolerations. */ tolerations?: Toleration[]; /** * TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. * * Scheduler will schedule pods in a way which abides by the constraints. All topologySpreadConstraints are ANDed. */ topologySpreadConstraints?: TopologySpreadConstraint[]; /** * List of volumes that can be mounted by containers belonging to the pod. * * More info: {@link https://kubernetes.io/docs/concepts/storage/volumes} */ volumes?: Volume[]; } function isContainerArray(children: any[]): children is AdaptElement<K8sContainerProps>[] { const badKids = children.filter((c) => !isElement(c) || !isK8sContainerElement(c)); if (badKids.length === 0) return true; const names = badKids.map((c) => isElement(c) ? c.componentName : String(c)); throw new BuildNotImplemented(`Pod children must be of type ` + `${K8sContainer.name}. Invalid children are: ${names.join(", ")}`); } function dups<T>(data: T[]): T[] { const grouped = ld.groupBy(data, ld.identity); const filtered = ld.filter(grouped, (val) => val.length > 1); return ld.uniq(ld.flatten(filtered)); } function defaultize(spec: ContainerSpec): ContainerSpec { spec = { ...spec }; if (spec.env && spec.env.length === 0) delete spec.env; if (spec.tty !== true) delete spec.tty; if (spec.ports && spec.ports.length === 0) delete spec.ports; if (spec.ports) { spec.ports = spec.ports.map( (p) => p.protocol ? p : { ...p, protocol: "TCP" }); } return spec; } function containerSpecProps(props: K8sContainerProps & BuiltinProps) { const { key, handle, ...rest } = props; return rest; } /** @internal */ export function makePodManifest(props: PodProps & BuiltinProps, data: { volumes?: Volume[]; serviceAccountName?: string; }) { const { key, handle, isTemplate, metadata, config, children, volumes: origVolumes, ...propsLL } = props; const containers = ld.compact( childrenToArray(props.children) .map((c) => isK8sContainerElement(c) ? c : null)); const spec: PodSpec = { ...propsLL, containers: containers.map((c) => ({ ...containerSpecProps(c.props) })) .map(defaultize) .map(removeUndef), ...removeUndef({ serviceAccountName: data.serviceAccountName, }), volumes: data.volumes, }; return { kind: "Pod", metadata: props.metadata, spec, }; } interface ResolvedVolumes { volumes?: Volume[]; } interface ResolvedServiceAccountName { serviceAccountName?: string; } function resolveMappedVolumeHandle(vol: Volume, deployID: string, toResolve: { [key: string]: { field: string } }) { for (const key in toResolve) { if (!Object.hasOwnProperty.call(toResolve, key)) continue; if (vol[key] === undefined) continue; const field = toResolve[key].field; const h = vol[key][field]; if (!isHandle(h)) return vol; const target = h.target; if (!isMountedElement(target) && target !== null) { return { ...vol, [key]: { ...vol[key], [field]: `adapt-unresolved-${key}`, // Make sure we force k8s to wait for the handle to resolve optional: false, } }; } if (target === null) { return { ...vol, [key]: { [field]: `adapt-null-${key}`, // Make the volume optional so k8s skips it optional: true, } }; } if (!isResource(target)) { throw new Error(`Cannot have a non-resource handle target for a ${key} volume ${field}`); } const props = (target as AdaptElement<ResourceProps>).props; if (key.toLowerCase() !== props.kind.toLowerCase()) { throw new Error(`Cannot use handle to ${props.kind} as reference in ${key}`); } return { ...vol, [key]: { ...vol[key], [field]: resourceElementToName(target, deployID), } }; } return vol; } function resolveVolumeHandles(volumes: Volume[] | undefined, deployID: string) { if (volumes === undefined) return {}; return { volumes: volumes.map((vol) => resolveMappedVolumeHandle( vol, deployID, { configMap: { field: "name" }, secret: { field: "secretName" } })) }; } function resolveServiceAccountName(serviceAccountName: string | Handle | undefined, deployID: string) { if (serviceAccountName === undefined) return undefined; if (!isHandle(serviceAccountName)) return { serviceAccountName }; const target = serviceAccountName.target; //A bogus name makes the pod undeployable so it watis for the service account to be ready if (!isMountedElement(target)) { return { serviceAccountName: `bogusServiceAccountName` }; } if (!isResource(target)) { throw new Error("Cannot have non-resource element as Pod serviceAccountName"); } if (!isServiceAccountProps(target.props)) { throw new Error(`Cannot have resource of type ${target.props.kind} as Pod serviceAccountName`); } return { serviceAccountName: resourceElementToName(target, deployID) }; } /** * Component for Kubernetes Pods * * @public */ export class Pod extends DeferredComponent<PodProps, ResolvedVolumes & ResolvedServiceAccountName> { static defaultProps = { isTemplate: false, metadata: {}, dnsPolicy: "ClusterFirst", enableServiceLinks: true, hostIPC: false, hostPID: false, restartPolicy: "Always", securityContext: {}, shareProcessNamespace: false, terminationGracePeriodSeconds: 30, }; initialState() { return {}; } build(helpers: BuildHelpers) { this.setState(() => ({ ...resolveVolumeHandles(this.props.volumes, helpers.deployID), ...resolveServiceAccountName(this.props.serviceAccountName, helpers.deployID) })); const { key } = this.props; if (!key) throw new InternalError("key is null"); const children = childrenToArray(this.props.children); if (ld.isEmpty(children)) return null; if (!isContainerArray(children)) return null; const containerNames = children.map((child) => child.props.name); const dupNames = dups(containerNames); if (!ld.isEmpty(dupNames)) { throw new BuildNotImplemented(`Duplicate names within a pod: ${dupNames.join(", ")}`); } const manifest = makePodManifest(this.props as PodProps & BuiltinProps, this.state); return (<Resource key={key} // tslint:disable-next-line: no-object-literal-type-assertion config={this.props.config} kind="Pod" isTemplate = {this.props.isTemplate} metadata={manifest.metadata} spec={manifest.spec} />); } async status(_observe: ObserveForStatus, buildData: BuildData) { const succ = buildData.successor; if (!succ) return undefined; return succ.status(); } } /** * Tests whether x is a Pod element * * @param x - value to test * @returns `true` if x is a Pod element, false otherwise * * @public */ export function isPod(x: any): x is AdaptElement<PodProps> { if (!isElement(x)) return false; if (x.componentType === Pod) return true; return false; } /* * Plugin info */ /** * Spec for for Kubernetes Pods * * @public */ export interface PodSpec extends Omit<PodProps, "config" | "metadata" | "isTemplate"> { containers: ContainerSpec[]; terminationGracePeriodSeconds?: number; } function isReady(status: any) { if (status.phase !== "Running") return false; const conditions = status.conditions; if (!conditions) return false; if (!Array.isArray(conditions)) return false; if (conditions.filter((c: any) => (c.type === "Ready") && (c.status === "True")).length !== 0) return true; return false; } function deployedWhen(statusObj: unknown) { const status: any = statusObj; if (!status || !status.status) return waiting(`Kubernetes cluster returned invalid status for Pod`); if (isReady(status.status)) return true; let msg = `Pod state ${status.status.phase}`; if (Array.isArray(status.status.conditions)) { const failing = status.status.conditions .filter((cond: any) => cond.status !== "True") .map((cond: any) => cond.message) .join("; "); if (failing) msg += `: ${failing}`; } return waiting(msg); } /** @internal */ export const podResourceInfo = { kind: "Pod", deployedWhen, statusQuery: async (props: ResourcePropsWithConfig, observe: ObserveForStatus, buildData: BuildData) => { const obs: any = await observe(K8sObserver, gql` query ($name: String!, $kubeconfig: JSON!, $namespace: String!) { withKubeconfig(kubeconfig: $kubeconfig) { readCoreV1NamespacedPod(name: $name, namespace: $namespace) @all(depth: 100) } }`, { name: resourceIdToName(props.key, buildData.id, buildData.deployID), kubeconfig: props.config.kubeconfig, namespace: computeNamespaceFromMetadata(props.metadata) } ); return obs.withKubeconfig.readCoreV1NamespacedPod; }, }; registerResourceKind(podResourceInfo);
the_stack
export namespace DVDPlayer { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * DVD Player */ export interface Application { /** * The version of the DVD Player */ version(): string; /** * Is the app starting up? */ appInitializing(): boolean; /** * Does user have multiple choices to start playback from? */ hasMultiplePlaybackChoice(): boolean; /** * Turn off interaction with user for last play sheet, etc */ interactionOverride(): boolean; /** * Turn off display of menu bar when mouse moves to menu bar area in full screen mode */ viewerFullScreenMenuOverride(): boolean; /** * Is there media in the drive? */ hasMedia(): boolean; /** * Is playback currently on a dvd menu? */ dvdMenuActive(): boolean; /** * The current dvd menu */ activeDvdMenu(): any; /** * The state of playback */ dvdState(): any; /** * The scan rate for fast forwarding and rewinding */ dvdScanRate(): any; /** * To hide or show the controller window */ controllerVisibility(): boolean; /** * The position of the controller window in screen coordinates */ controllerPosition(): any; /** * The window bounds in screen coordinates */ controllerBounds(): any; /** * The screen bounds the window is on */ controllerScreenBounds(): any; /** * The controller orientation - (Not supported in 5.0 and greater) */ controllerOrientation(): any; /** * The state of the controller drawer */ controllerDrawer(): any; /** * To hide or show the info window - (Not supported in 5.0 and greater) */ infoVisibility(): boolean; /** * The position of the info window in screen coordinates - (Not supported in 5.0 and greater) */ infoPosition(): any; /** * The window bounds in screen coordinates - (Not supported in 5.0 and greater) */ infoBounds(): any; /** * The screen bounds the window is on - (Not supported in 5.0 and greater) */ infoScreenBounds(): any; /** * Sets the type of info window being displayed - (Not supported in 5.0 and greater) */ infoType(): any; /** * The info text color - (Not supported in 5.0 and greater) */ infoTextColor(): any; /** * To hide or show the viewer window */ viewerVisibility(): boolean; /** * To set the position of the viewer window in screen coordinates */ viewerPosition(): any; /** * The window bounds in screen coordinates */ viewerBounds(): any; /** * The screen bounds the window is on */ viewerScreenBounds(): any; /** * To set the the viewer size */ viewerSize(): any; /** * Set to true to enter presentation mode */ viewerFullScreen(): boolean; /** * To turn the audio on or off */ audioMuted(): boolean; /** * The DVD audio volume, 0 is silent, 255 is full on */ audioVolume(): number; /** * The elapsed time, in seconds, of the current title */ elapsedTime(): number; /** * The elapsed time, in seconds and frames, of the current title */ elapsedExtendedTime(): any; /** * The remaining time, in seconds, of the current title */ remainingTime(): number; /** * The remaining time, in seconds and frames, of the current title */ remainingExtendedTime(): any; /** * The length of the title in seconds */ titleLength(): number; /** * The length of the title in seconds and frames */ titleExtendedLength(): any; /** * The number of angles available at the current time position */ availableAngles(): number; /** * The number of audio tracks available at the current time position */ availableAudioTracks(): number; /** * The number of chapters available at the current time position */ availableChapters(): number; /** * The number of subtitles available at the current time position */ availableSubtitles(): number; /** * The number of titles available at the current time position */ availableTitles(): number; /** * The current camera angle at the current time position */ angle(): number; /** * The current audio track at the current time position */ audioTrack(): number; /** * The current chapter at the current time position */ chapter(): number; /** * Are we currently displaying subtitles? */ displayingSubtitle(): boolean; /** * The current subtitle (caption) at the current time position */ subtitle(): number; /** * The current title at the current time position */ title(): number; /** * Turn closed captioning on or off */ closedCaptioning(): boolean; /** * The display type for closed captioning */ closedCaptioningDisplay(): any; /** * Supports extended bookmark functionality */ extendedBookmarks(): boolean; /** * The number of bookmarks available for the current media */ availableBookmarks(): number; /** * The names of the bookmarks for the current media */ bookmarkList(): any; /** * Has a default bookmark been set? */ hasDefaultBookmark(): boolean; /** * Does the media have a last play bookmark from being previously viewed? */ hasLastPlayBookmark(): any; /** * Supports extended video clip functionality */ extendedVideoClips(): boolean; /** * The number of video clips available for the current media */ availableVideoClips(): number; /** * The names of the video clips for the current media */ videoClipList(): any; /** * To turn the loop state for video clips on or off */ loopVideoClip(): boolean; /** * Is video clip being played? */ clipMode(): boolean; /** * Disable displaying the status message? */ disableStatusWindow(): boolean; } // CLass Extension /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * DVD Player */ export interface Application { privateMenuPaused(): boolean; privateMenuActionTicks(): number; } // Records // Function options } export interface DVDPlayer extends DVDPlayer.Application { // Functions /** * Start fast forwarding a DVD disc * @return returns DVD Player error code */ fastForwardDvd(): number; /** * Start playback of a DVD disc * @return returns DVD Player error code */ playDvd(): number; /** * Pause the playback of a DVD disc * @return returns DVD Player error code */ pauseDvd(): number; /** * Start rewinding a DVD disc * @return returns DVD Player error code */ rewindDvd(): number; /** * Stop the playback of a DVD disc * @return returns DVD Player error code */ stopDvd(): number; /** * Step the dvd movie to the next frame * @return returns DVD Player error code */ stepDvd(): number; /** * Go to the specified place * @param directParameter undefined * @return returns DVD Player error code */ go(directParameter: any, ): number; /** * Press a key in a menu * @param directParameter undefined * @return returns DVD Player error code */ press(directParameter: any, ): number; /** * open a VIDEO_TS folder for playing dvd from file * @param directParameter file reference to VIDEO_TS folder * @return returns DVD Player error code */ openVIDEOTs(directParameter: any, ): number; /** * open a dvd video folder (VIDEO_TS or HVDVD_TS) folder for playing dvd from file * @param directParameter file reference to VIDEO_TS or HVDVD_TS folder * @return returns DVD Player error code */ openDvdVideoFolder(directParameter: any, ): number; /** * Play the previous chapter of the current title * @return returns DVD Player error code */ playPreviousChapter(): number; /** * Play the next chapter of the current title * @return returns DVD Player error code */ playNextChapter(): number; /** * Specify the bookmark to play by index * @param directParameter The index of the bookmark * @return returns DVD Player error code */ playBookmark(directParameter: number, ): number; /** * Specify the bookmark to play by name * @param directParameter The name of the bookmark * @return returns DVD Player error code */ playNamedBookmark(directParameter: string, ): number; /** * Specify the video clip to play by index * @param directParameter The index of the video clip * @return returns DVD Player error code */ playVideoClip(directParameter: number, ): number; /** * Specify the video clip to play by name * @param directParameter The name of the video clip * @return returns DVD Player error code */ playNamedVideoClip(directParameter: string, ): number; /** * Exit video clip mode if currently playing a video clip * @return returns DVD Player error code */ exitClipMode(): number; /** * obscure the mouse cursor * @return returns DVD Player error code */ obscureCursor(): number; /** * eject the dvd we are using * @return returns DVD Player error code */ ejectDvd(): number; }
the_stack
import { CellModel, ColumnModel, getCell, SheetModel, setCell, Workbook, getSheetIndex, CellStyleModel } from './../index'; import { getCellAddress, getRangeIndexes, BeforeCellUpdateArgs, beforeCellUpdate, workbookEditOperation, CellUpdateArgs, InsertDeleteModelArgs, getColumnHeaderText } from './index'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; /** * Check whether the text is formula or not. * * @param {string} text - Specify the text. * @param {boolean} isEditing - Specify the isEditing. * @returns {boolean} - Check whether the text is formula or not. */ export function checkIsFormula(text: string, isEditing?: boolean): boolean { return text && text[0] === '=' && (text.length > 1 || isEditing); } /** * Check whether the value is cell reference or not. * * @param {string} value - Specify the value to check. * @returns {boolean} - Returns boolean value */ export function isCellReference(value: string): boolean { let range: string = value; range = range.split('$').join(''); if (range.indexOf(':') > -1) { const rangeSplit: string[] = range.split(':'); if (isValidCellReference(rangeSplit[0]) && isValidCellReference(rangeSplit[1])) { return true; } } else if (range.indexOf(':') < 0) { if (isValidCellReference(range)) { return true; } } return false; } /** * Check whether the value is character or not. * * @param {string} value - Specify the value to check. * @returns {boolean} - Returns boolean value */ export function isChar(value: string): boolean { if ((value.charCodeAt(0) >= 65 && value.charCodeAt(0) <= 90) || (value.charCodeAt(0) >= 97 && value.charCodeAt(0) <= 122)) { return true; } return false; } /** * Check whether the range selection is on complete row. * * @param {SheetModel} sheet - Specify the sheet. * @param {number[]} range - Specify the range index. * @returns {boolean} - Returns boolean value * @hidden */ export function isRowSelected(sheet: SheetModel, range: number[]): boolean { return range[1] === 0 && range[3] === sheet.colCount - 1; } /** * Check whether the range selection is on complete column. * * @param {SheetModel} sheet - Specify the sheet. * @param {number[]} range - Specify the range index. * @returns {boolean} - Returns boolean value * @hidden */ export function isColumnSelected(sheet: SheetModel, range: number[]): boolean { return range[0] === 0 && range[2] === sheet.rowCount - 1; } /** * @param {number[]} range - Specify the range * @param {number} rowIdx - Specify the row index * @param {number} colIdx - Specify the col index * @returns {boolean} - Returns boolean value */ export function inRange(range: number[], rowIdx: number, colIdx: number) : boolean { return range && (rowIdx >= range[0] && rowIdx <= range[2] && colIdx >= range[1] && colIdx <= range[3]); } /** * @param {number[]} address - Specify the address * @param {number} rowIdx - Specify the row index * @param {number} colIdx - Specify the col index * @returns {boolean} - Returns boolean value */ export function isInMultipleRange(address: string, rowIdx: number, colIdx: number): boolean { let range: number[]; let isInRange: boolean; const splitedAddress: string[] = address.split(' '); for (let i: number = 0, len: number = splitedAddress.length; i < len; i++) { range = getRangeIndexes(splitedAddress[i]); isInRange = inRange(range, rowIdx, colIdx); if (isInRange) { break; } } return isInRange; } /** @hidden * @param {number[]} range - Specify the range * @param {number[]} testRange - Specify the test range * @param {boolean} isModify - Specify the boolean value * @returns {boolean} - Returns boolean value */ export function isInRange(range: number[], testRange: number[], isModify?: boolean) : boolean { let inRange: boolean = range[0] <= testRange[0] && range[2] >= testRange[2] && range[1] <= testRange[1] && range[3] >= testRange[3]; if (inRange) { return true; } if (isModify) { if (testRange[0] < range[0] && testRange[2] < range[0] || testRange[0] > range[2] && testRange[2] > range[2]) { return false; } else { if (testRange[0] < range[0] && testRange[2] > range[0]) { testRange[0] = range[0]; inRange = true; } if (testRange[2] > range[2]) { testRange[2] = range[2]; inRange = true; } } if (testRange[1] < range[1] && testRange[3] < range[1] || testRange[1] > range[3] && testRange[3] > range[3]) { return false; } else { if (testRange[1] < range[1] && testRange[3] > range[1]) { testRange[1] = range[1]; inRange = true; } if (testRange[3] > range[3]) { testRange[3] = range[3]; inRange = true; } } } return inRange; } /** * @hidden * @param {string} address - Specifies the address for whole column. * @param {number[]} testRange - Specifies range used to split the address. * @param {number} colIdx - Specifies the column index. * @returns {string} - returns the modified address. */ export function getSplittedAddressForColumn(address: string, testRange: number[], colIdx: number): string { const colName: string = getColumnHeaderText(colIdx + 1); if (address) { address.split(' ').forEach((addrs: string) => { const range: number[] = getRangeIndexes(addrs); if (isInRange(range, testRange)) { address = address.split(addrs).join(colName + (range[0] + 1) + ':' + colName + testRange[0] + ' ' + colName + (testRange[2] + 2) + ':' + colName + (range[2] + 1)); } else if (isInRange(range, testRange, true)) { let modifiedAddress: string; if (testRange[0] > range[0]) { modifiedAddress = colName + (range[0] + 1) + ':' + colName + testRange[0]; } else { modifiedAddress = colName + (testRange[2] + 2) + ':' + colName + (range[2] + 1); } address = address.split(addrs).join(modifiedAddress); } }); } else { address = colName + '1:' + colName + testRange[0] + ' ' + colName + (testRange[2] + 2) + ':' + colName + '1048576'; } return address; } /** * Check whether the cell is locked or not * * @param {CellModel} cell - Specify the cell. * @param {ColumnModel} column - Specify the column. * @returns {boolean} - Returns boolean value * @hidden */ export function isLocked(cell: CellModel, column: ColumnModel): boolean { if (!cell) { cell = {}; } if (cell.isLocked) { return true; } else if (cell.isLocked === false) { return false; } else if (column && column.isLocked) { return true; } else if (!cell.isLocked && (column && column.isLocked !== false)) { return true; } return false; } /** * Check whether the value is cell reference or not. * * @param {string} value - Specify the value to check. * @returns {boolean} - Returns boolean value * @hidden */ export function isValidCellReference(value: string): boolean { const text: string = value; const startNum: number = 0; let endNum: number = 0; let j: number = 0; const numArr: number[] = [89, 71, 69]; // XFD is the last column, for that we are using ascii values of Z, G, E (89, 71, 69) to restrict the flow. let cellText: string = ''; const textLength: number = text.length; for (let i: number = 0; i < textLength; i++) { if (isChar(text[i])) { endNum++; } } cellText = text.substring(startNum, endNum); const cellTextLength: number = cellText.length; if (cellTextLength !== textLength) { if (cellTextLength < 4) { if (textLength !== 1 && (isNaN(parseInt(text, 10)))) { while (j < cellTextLength) { if ((cellText[j]) && cellText[j].charCodeAt(0) < numArr[j]) { j++; continue; } else if (!(cellText[j]) && j > 0) { break; } else { return false; } } const cellNumber: number = parseFloat(text.substring(endNum, textLength)); if (cellNumber > 0 && cellNumber < 1048577) { // 1048576 - Maximum number of rows in excel. return true; } } } } return false; } /** * @hidden * @param {SheetModel} sheet - Specify the sheet * @param {number} index - specify the index * @param {boolean} increase - specify the boolean value. * @param {string} layout - specify the string * @returns {number} - To skip the hidden index * */ export function skipHiddenIdx(sheet: SheetModel, index: number, increase: boolean, layout: string = 'rows'): number { if (increase) { for (let i: number = index; i < Infinity; i++) { if ((sheet[layout])[index] && (sheet[layout])[index].hidden) { index++; } else { break; } } } else { for (let i: number = index; i > -1; i--) { if ((sheet[layout])[index] && (sheet[layout])[index].hidden) { index--; } else { break; } } } return index; } /** * @param {CellStyleModel} style - Cell style. * @param {boolean} onActionUpdate - Specifies the action. * @returns {boolean} - retruns `true` is height needs to be checked. * @hidden */ export function isHeightCheckNeeded(style: CellStyleModel, onActionUpdate?: boolean): boolean { const keys: string[] = Object.keys(style); return (onActionUpdate ? keys.indexOf('fontSize') > -1 : keys.indexOf('fontSize') > -1 && Number(style.fontSize.split('pt')[0]) > 12) || keys.indexOf('fontFamily') > -1 || keys.indexOf('borderTop') > -1 || keys.indexOf('borderBottom') > -1; } /** * @param {number[]} currIndexes - current indexes in which formula get updated * @param {number[]} prevIndexes - copied indexes * @param {SheetModel} sheet - sheet model * @param {CellModel} prevCell - copied or prev cell * @returns {string} - retruns updated formula * @hidden */ export function getUpdatedFormula(currIndexes: number[], prevIndexes: number[], sheet: SheetModel, prevCell?: CellModel): string { let cIdxValue: string; let cell: CellModel; if (prevIndexes) { cell = prevCell || getCell(prevIndexes[0], prevIndexes[1], sheet, false, true); cIdxValue = cell.formula ? cell.formula.toUpperCase() : ''; } if (cIdxValue) { if (cIdxValue.indexOf('=') === 0) { cIdxValue = cIdxValue.slice(1); } cIdxValue = cIdxValue.split('(').join(',').split(')').join(','); const formulaOperators: string[] = ['+', '-', '*', '/', '>=', '<=', '<>', '>', '<', '=', '%']; let splitArray: string[]; let value: string = cIdxValue; for (let i: number = 0; i < formulaOperators.length; i++) { splitArray = value.split(formulaOperators[i]); value = splitArray.join(','); } splitArray = value.split(','); const newAddress: { [key: string]: string }[] = []; let newRef: string; let refObj: { [key: string]: string }; for (let j: number = 0; j < splitArray.length; j++) { if (isCellReference(splitArray[j])) { const range: number[] = getRangeIndexes(splitArray[j]); const newRange: number[] = [currIndexes[0] - (prevIndexes[0] - range[0]), currIndexes[1] - (prevIndexes[1] - range[1]), currIndexes[0] - (prevIndexes[0] - range[2]), currIndexes[1] - (prevIndexes[1] - range[3])]; if (newRange[0] < 0 || newRange[1] < 0 || newRange[2] < 0 || newRange[3] < 0) { newRef = '#REF!'; } else { newRef = getCellAddress(newRange[0], newRange[1]); if (splitArray[j].includes(':')) { newRef += (':' + getCellAddress(newRange[2], newRange[3])); } newRef = isCellReference(newRef) ? newRef : '#REF!'; } refObj = {}; refObj[splitArray[j]] = newRef; if (splitArray[j].includes(':')) { newAddress.splice(0, 0, refObj); } else { newAddress.push(refObj); } } } let objKey: string; cIdxValue = cell.formula; for (let j: number = 0; j < newAddress.length; j++) { objKey = Object.keys(newAddress[j])[0]; cIdxValue = cIdxValue.replace(new RegExp(objKey, 'gi'), newAddress[j][objKey].toUpperCase()); } return cIdxValue; } else { return null; } } /**@hidden */ export function updateCell(context: Workbook, sheet: SheetModel, prop: CellUpdateArgs): boolean { const args: BeforeCellUpdateArgs = { cell: prop.cell, rowIndex: prop.rowIdx, colIndex: prop.colIdx, cancel: false, sheet: sheet.name }; if (!prop.preventEvt) { // Prevent event triggering for public method cell update. context.trigger(beforeCellUpdate, args); } if (!prop.eventOnly && !args.cancel) { // `eventOnly` - To trigger event event and return without cell model update. if (prop.valChange) { const prevCell: CellModel = getCell(args.rowIndex, args.colIndex, sheet); const prevCellVal: string = !prop.preventEvt && context.getDisplayText(prevCell); const isFormulaCell: boolean = !!(prevCell && prevCell.formula); setCell(args.rowIndex, args.colIndex, sheet, args.cell, !prop.pvtExtend); const cell: CellModel = getCell(args.rowIndex, args.colIndex, sheet, false, true); context.notify( workbookEditOperation, { action: 'updateCellValue', address: [args.rowIndex, args.colIndex], sheetIndex: getSheetIndex(context, sheet.name), value: isFormulaCell && !cell.formula ? (cell.value || (<unknown>cell.value === 0 ? '0' : '')) : (cell.formula || cell.value || (<unknown>cell.value === 0 ? '0' : '')) }); if (prop.requestType && args.cell === null) { setCell(args.rowIndex, args.colIndex, sheet, args.cell, !prop.pvtExtend); } if (prop.cellDelete) { delete cell.value; delete cell.formula; delete cell.hyperlink; } if (prop.uiRefresh) { context.serviceLocator.getService<{ refresh: Function }>('cell').refresh( args.rowIndex, args.colIndex, prop.lastCell, prop.td, prop.checkCf, prop.checkWrap); } if (!prop.preventEvt) { const cellDisplayText: string = context.getDisplayText(cell); if (cellDisplayText !== prevCellVal) { let cellValue: string = getCell(args.rowIndex, args.colIndex, sheet, false, true).value; cellValue = cellValue || (<unknown>cellValue === 0 ? '0' : ''); const evtArgs: { [key: string]: Object } = { value: cellValue, oldValue: prevCellVal, formula: cell.formula || '', address: `${sheet.name}!${getCellAddress(args.rowIndex, args.colIndex)}`, displayText: cellDisplayText }; if (prop.requestType) { evtArgs.requestType = prop.requestType; } context.trigger('cellSave', evtArgs); } } } else { setCell(args.rowIndex, args.colIndex, sheet, args.cell, !prop.pvtExtend); } } return args.cancel; } /** * @param {number} rowIdx - row index * @param {number} colIdx - column index * @param {SheetModel} sheet - sheet model * @returns {number[]} - retruns data range * @hidden */ export function getDataRange(rowIdx: number, colIdx: number, sheet: SheetModel): number[] { let i: number = 0; let j: number = 0; let loopLength: number = 0; const length: number = sheet.usedRange.rowIndex + sheet.usedRange.colIndex; const startCell: { rowIndex: number, colIndex: number } = { rowIndex: rowIdx, colIndex: colIdx }; const endCell: { rowIndex: number, colIndex: number } = { rowIndex: rowIdx, colIndex: colIdx }; for (i = 1; i < length + 1; i++) { for (j = -loopLength; j < loopLength + 1; j++) { // start from right if (getCell(rowIdx + j, colIdx + i, sheet, null, true).value) { endCell.rowIndex = endCell.rowIndex > rowIdx + j ? endCell.rowIndex : rowIdx + j; endCell.colIndex = endCell.colIndex > colIdx + i ? endCell.colIndex : colIdx + i; } } if (getCell(rowIdx + i, colIdx + i, sheet, null, true).value) { endCell.rowIndex = endCell.rowIndex > rowIdx + i ? endCell.rowIndex : rowIdx + i; endCell.colIndex = endCell.colIndex > colIdx + i ? endCell.colIndex : colIdx + i; } for (j = -loopLength; j < loopLength + 1; j++) { if (getCell(rowIdx + i, colIdx + j, sheet, null, true).value) { endCell.rowIndex = endCell.rowIndex > rowIdx + i ? endCell.rowIndex : rowIdx + i; endCell.colIndex = endCell.colIndex > colIdx + j ? endCell.colIndex : colIdx + j; } } if (getCell(rowIdx + i, colIdx - i, sheet, null, true).value) { endCell.rowIndex = endCell.rowIndex > rowIdx + i ? endCell.rowIndex : rowIdx + i; startCell.colIndex = startCell.colIndex < colIdx - i ? startCell.colIndex : colIdx - i; } for (j = -loopLength; j < loopLength + 1; j++) { if (getCell(rowIdx + j, colIdx - i, sheet, null, true).value) { startCell.rowIndex = startCell.rowIndex < rowIdx + j ? startCell.rowIndex : rowIdx + j; startCell.colIndex = startCell.colIndex < colIdx - i ? startCell.colIndex : colIdx - i; endCell.rowIndex = endCell.rowIndex > rowIdx + j ? endCell.rowIndex : rowIdx + j; } } if (getCell(rowIdx - i, colIdx - i, sheet, null, true).value) { startCell.rowIndex = startCell.rowIndex < rowIdx - i ? startCell.rowIndex : rowIdx - i; startCell.colIndex = startCell.colIndex < colIdx - i ? startCell.colIndex : colIdx - i; } for (j = -loopLength; j < loopLength + 1; j++) { if (getCell(rowIdx - i, colIdx + j, sheet, null, true).value) { startCell.rowIndex = startCell.rowIndex < rowIdx - i ? startCell.rowIndex : rowIdx - i; startCell.colIndex = startCell.colIndex < colIdx + j ? startCell.colIndex : colIdx + j; endCell.colIndex = endCell.colIndex > colIdx + j ? endCell.colIndex : colIdx + j; } } if (getCell(rowIdx - i, colIdx + i, sheet, null, true).value) { startCell.rowIndex = startCell.rowIndex < rowIdx - i ? startCell.rowIndex : rowIdx - i; endCell.colIndex = endCell.colIndex > colIdx + i ? endCell.colIndex : colIdx + i; } loopLength++; } return [startCell.rowIndex, startCell.colIndex, endCell.rowIndex, endCell.colIndex]; } /** * @param {InsertDeleteModelArgs} args - row index * @param {number[]} formatRange - format range index * @returns {number[]} - retruns updated range * @hidden */ export function insertFormatRange(args: InsertDeleteModelArgs, formatRange: number[], isAction: boolean): number[] { let sltRangeIndex: number[] = getRangeIndexes(args.model.selectedRange); let insertStartIndex: number = 0; let insertEndIndex: number = 0; if (args.modelType === 'Column') { if (isAction) { sltRangeIndex = [0,args.start as number,0,args.end]; } if (args.insertType === "before") { if ((formatRange[1] <= sltRangeIndex[1] && formatRange[3] >= sltRangeIndex[1])) { insertStartIndex = 0; insertEndIndex = (sltRangeIndex[3] - sltRangeIndex[1]) + 1; } else if (sltRangeIndex[1] < formatRange[1]) { insertStartIndex = insertEndIndex = (sltRangeIndex[3] - sltRangeIndex[1]) + 1; } } else { if ((formatRange[1] <= sltRangeIndex[3] && formatRange[3] >= sltRangeIndex[3])) { insertStartIndex = 0; insertEndIndex = (sltRangeIndex[3] - sltRangeIndex[1]) + 1; } else if (sltRangeIndex[3] < formatRange[3]) { insertStartIndex = insertEndIndex = (sltRangeIndex[3] - sltRangeIndex[1]) + 1; } } return [formatRange[0], formatRange[1] + insertStartIndex, formatRange[2], formatRange[3] + insertEndIndex]; } else { if (isAction) { sltRangeIndex = [args.start as number,0,args.end,0]; } if (args.insertType === "above") { if ((formatRange[0] <= sltRangeIndex[0] && formatRange[2] >= sltRangeIndex[0])) { insertStartIndex = 0; insertEndIndex = (sltRangeIndex[2] - sltRangeIndex[0]) + 1; } else if (sltRangeIndex[0] < formatRange[0]) { insertStartIndex = insertEndIndex = (sltRangeIndex[2] - sltRangeIndex[0]) + 1; } } else { if ((formatRange[0] <= sltRangeIndex[2] && formatRange[2] >= sltRangeIndex[2])) { insertStartIndex = 0; insertEndIndex = (sltRangeIndex[2] - sltRangeIndex[0]) + 1; } else if (sltRangeIndex[2] < formatRange[2]) { insertStartIndex = insertEndIndex = (sltRangeIndex[2] - sltRangeIndex[0]) + 1; } } return [formatRange[0] + insertStartIndex, formatRange[1], formatRange[2] + insertEndIndex, formatRange[3]]; } } /** * @param {InsertDeleteModelArgs} args - row index * @param {number[]} formatRange - cell range index * @returns {number[]} - retruns data range * @hidden */ export function deleteFormatRange(args: InsertDeleteModelArgs, formatRange: number[]): number[] { let cellRange: number[]; let deleteStartIndex: number = 0; let deleteEndIndex: number = 0; if (args.modelType === 'Column') { cellRange = [0, args.start as number, args.model.usedRange.rowIndex, args.end]; if (cellRange[3] < formatRange[1]) { deleteStartIndex = deleteEndIndex = cellRange[3] - cellRange[1] + 1; } else if (cellRange[1] >= formatRange[1] && cellRange[3] <= formatRange[3]) { deleteEndIndex = cellRange[3] - cellRange[1] + 1; } else if (cellRange[1] >= formatRange[1] && cellRange[1] <= formatRange[3]) { deleteEndIndex = formatRange[3] - cellRange[1] + 1; } else if (cellRange[1] < formatRange[1] && cellRange[3] >= formatRange[1]) { deleteStartIndex = formatRange[1] - cellRange[1]; deleteEndIndex = cellRange[3] - cellRange[1] + 1; } else if (cellRange[1] < formatRange[1] && cellRange[3] < formatRange[3]) { deleteStartIndex = (cellRange[3] - formatRange[1]) + (cellRange[3] - cellRange[1]) + 1; deleteEndIndex = cellRange[3] - cellRange[1] + 1; } return [formatRange[0], formatRange[1] - deleteStartIndex, formatRange[2], formatRange[3] - deleteEndIndex]; } else { cellRange = [args.start as number, 0, args.end, args.model.usedRange.colIndex]; if (cellRange[2] < formatRange[0]) { deleteStartIndex = deleteEndIndex = cellRange[2] - cellRange[0] + 1; } else if (cellRange[0] >= formatRange[0] && cellRange[2] <= formatRange[2]) { deleteEndIndex = cellRange[2] - cellRange[0] + 1; } else if (cellRange[0] >= formatRange[0] && cellRange[0] <= formatRange[2]) { deleteEndIndex = formatRange[2] - cellRange[0] + 1; } else if (cellRange[0] < formatRange[0] && cellRange[2] >= formatRange[0]) { deleteStartIndex = formatRange[0] - cellRange[0]; deleteEndIndex = cellRange[2] - cellRange[0] + 1; } else if (cellRange[0] < formatRange[0] && cellRange[2] < formatRange[2]) { deleteStartIndex = (cellRange[2] - formatRange[0]) + (cellRange[2] - cellRange[0]) + 1; deleteEndIndex = cellRange[2] - cellRange[0] + 1; } return [formatRange[0] - deleteStartIndex, formatRange[1], formatRange[2] - deleteEndIndex, formatRange[3]]; } }
the_stack
import { HttpClient, HttpResponse, HttpEvent } from '@angular/common/http'; import { Inject, Injectable, Optional } from '@angular/core'; import { APIClientInterface } from './api-client.interface'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { USE_DOMAIN, USE_HTTP_OPTIONS, APIClient } from './api-client.service'; import { DefaultHttpOptions, HttpOptions } from './types'; import * as models from './models'; import * as guards from './guards'; @Injectable() export class GuardedAPIClient extends APIClient implements APIClientInterface { constructor( readonly httpClient: HttpClient, @Optional() @Inject(USE_DOMAIN) domain?: string, @Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions, ) { super(httpClient, domain, options); } /** * Gets multiple documents. * * * Documents returned by this method are not guaranteed to be returned in the * same order that they were requested. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.BatchGetDocumentsResponse>; firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.BatchGetDocumentsResponse>>; firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.BatchGetDocumentsResponse>>; firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.BatchGetDocumentsResponse | HttpResponse<models.BatchGetDocumentsResponse> | HttpEvent<models.BatchGetDocumentsResponse>> { return super.firestoreProjectsDatabasesDocumentsBatchGet(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isBatchGetDocumentsResponse(res) || console.error(`TypeGuard for response 'models.BatchGetDocumentsResponse' caught inconsistency.`, res))); } /** * Starts a new transaction. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.BeginTransactionResponse>; firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.BeginTransactionResponse>>; firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.BeginTransactionResponse>>; firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.BeginTransactionResponse | HttpResponse<models.BeginTransactionResponse> | HttpEvent<models.BeginTransactionResponse>> { return super.firestoreProjectsDatabasesDocumentsBeginTransaction(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isBeginTransactionResponse(res) || console.error(`TypeGuard for response 'models.BeginTransactionResponse' caught inconsistency.`, res))); } /** * Commits a transaction, while optionally updating documents. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CommitResponse>; firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CommitResponse>>; firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CommitResponse>>; firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.CommitResponse | HttpResponse<models.CommitResponse> | HttpEvent<models.CommitResponse>> { return super.firestoreProjectsDatabasesDocumentsCommit(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isCommitResponse(res) || console.error(`TypeGuard for response 'models.CommitResponse' caught inconsistency.`, res))); } /** * Listens to changes. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListenResponse>; firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListenResponse>>; firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListenResponse>>; firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ListenResponse | HttpResponse<models.ListenResponse> | HttpEvent<models.ListenResponse>> { return super.firestoreProjectsDatabasesDocumentsListen(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isListenResponse(res) || console.error(`TypeGuard for response 'models.ListenResponse' caught inconsistency.`, res))); } /** * Rolls back a transaction. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Empty>; firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Empty>>; firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Empty>>; firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Empty | HttpResponse<models.Empty> | HttpEvent<models.Empty>> { return super.firestoreProjectsDatabasesDocumentsRollback(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isEmpty(res) || console.error(`TypeGuard for response 'models.Empty' caught inconsistency.`, res))); } /** * Streams batches of document updates and deletes, in order. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.WriteResponse>; firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.WriteResponse>>; firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.WriteResponse>>; firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.WriteResponse | HttpResponse<models.WriteResponse> | HttpEvent<models.WriteResponse>> { return super.firestoreProjectsDatabasesDocumentsWrite(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isWriteResponse(res) || console.error(`TypeGuard for response 'models.WriteResponse' caught inconsistency.`, res))); } /** * Deletes an index. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Empty>; firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Empty>>; firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Empty>>; firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Empty | HttpResponse<models.Empty> | HttpEvent<models.Empty>> { return super.firestoreProjectsDatabasesIndexesDelete(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isEmpty(res) || console.error(`TypeGuard for response 'models.Empty' caught inconsistency.`, res))); } /** * Gets an index. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Index>; firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Index>>; firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Index>>; firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Index | HttpResponse<models.Index> | HttpEvent<models.Index>> { return super.firestoreProjectsDatabasesIndexesGet(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isIndex(res) || console.error(`TypeGuard for response 'models.Index' caught inconsistency.`, res))); } /** * Updates or inserts a document. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Document>; firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Document>>; firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Document>>; firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Document | HttpResponse<models.Document> | HttpEvent<models.Document>> { return super.firestoreProjectsDatabasesDocumentsPatch(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isDocument(res) || console.error(`TypeGuard for response 'models.Document' caught inconsistency.`, res))); } /** * Lists the indexes that match the specified filters. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListIndexesResponse>; firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListIndexesResponse>>; firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListIndexesResponse>>; firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ListIndexesResponse | HttpResponse<models.ListIndexesResponse> | HttpEvent<models.ListIndexesResponse>> { return super.firestoreProjectsDatabasesIndexesList(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isListIndexesResponse(res) || console.error(`TypeGuard for response 'models.ListIndexesResponse' caught inconsistency.`, res))); } /** * Creates the specified index. * A newly created index's initial state is `CREATING`. On completion of the * returned google.longrunning.Operation, the state will be `READY`. * If the index already exists, the call will return an `ALREADY_EXISTS` * status. * * * During creation, the process could result in an error, in which case the * index will move to the `ERROR` state. The process can be recovered by * fixing the data that caused the error, removing the index with * delete, then re-creating the index with * create. * * * Indexes with a single field cannot be created. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Operation>; firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Operation>>; firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Operation>>; firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Operation | HttpResponse<models.Operation> | HttpEvent<models.Operation>> { return super.firestoreProjectsDatabasesIndexesCreate(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isOperation(res) || console.error(`TypeGuard for response 'models.Operation' caught inconsistency.`, res))); } /** * Lists documents. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListDocumentsResponse>; firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListDocumentsResponse>>; firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListDocumentsResponse>>; firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ListDocumentsResponse | HttpResponse<models.ListDocumentsResponse> | HttpEvent<models.ListDocumentsResponse>> { return super.firestoreProjectsDatabasesDocumentsList(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isListDocumentsResponse(res) || console.error(`TypeGuard for response 'models.ListDocumentsResponse' caught inconsistency.`, res))); } /** * Creates a new document. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Document>; firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Document>>; firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Document>>; firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Document | HttpResponse<models.Document> | HttpEvent<models.Document>> { return super.firestoreProjectsDatabasesDocumentsCreateDocument(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isDocument(res) || console.error(`TypeGuard for response 'models.Document' caught inconsistency.`, res))); } /** * Lists all the collection IDs underneath a document. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListCollectionIdsResponse>; firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListCollectionIdsResponse>>; firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListCollectionIdsResponse>>; firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.ListCollectionIdsResponse | HttpResponse<models.ListCollectionIdsResponse> | HttpEvent<models.ListCollectionIdsResponse>> { return super.firestoreProjectsDatabasesDocumentsListCollectionIds(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isListCollectionIdsResponse(res) || console.error(`TypeGuard for response 'models.ListCollectionIdsResponse' caught inconsistency.`, res))); } /** * Runs a query. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RunQueryResponse>; firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RunQueryResponse>>; firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RunQueryResponse>>; firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.RunQueryResponse | HttpResponse<models.RunQueryResponse> | HttpEvent<models.RunQueryResponse>> { return super.firestoreProjectsDatabasesDocumentsRunQuery(args, requestHttpOptions, observe) .pipe(tap((res: any) => guards.isRunQueryResponse(res) || console.error(`TypeGuard for response 'models.RunQueryResponse' caught inconsistency.`, res))); } }
the_stack
import { serve } from '../../tests/support/fixture-server' import { testWorkRoot } from '../../tests/support/test-run-env' import { launchPlaywright, testPlaywright } from '../../tests/support/launch-browser' import { Browser } from './Browser' import { Until } from '../page/Until' import { By } from '../page/By' import { Key } from '../page/Enums' import { DEFAULT_SETTINGS } from './Settings' let playwright: testPlaywright const workRoot = testWorkRoot() const getCurrentPosition = async ( browser: Browser<any> ): Promise<{ top: number; left: number }> => { return await browser.evaluate(() => ({ top: document.documentElement.scrollTop || document.body.scrollTop, left: document.documentElement.scrollLeft || document.body.scrollLeft, })) } describe('Browser', () => { jest.setTimeout(30e3) beforeAll(async () => { playwright = await launchPlaywright() playwright.page.on('console', (msg) => console.log(`>> remote console.${msg.type()}: ${msg.text()}`) ) }) afterAll(async () => { await playwright.close() }) test('fires callbacks on action command calls', async () => { const beforeSpy = jest.fn() const afterSpy = jest.fn() const browser = new Browser( workRoot, playwright, DEFAULT_SETTINGS, async (_browser, actionName) => { beforeSpy(actionName) }, async (_browser, actionName) => { afterSpy(actionName) } ) const url = await serve('forms_with_input_elements.html') await browser.visit(url) expect(beforeSpy).toHaveBeenCalledWith('visit') expect(afterSpy).toHaveBeenCalledWith('visit') }) test('throws an error', async () => { const browser = new Browser( workRoot, playwright, { ...DEFAULT_SETTINGS }, async (name) => {}, async (name) => {} ) const url = await serve('forms_with_input_elements.html') await browser.visit(url) return expect(browser.click('.notanelement')).rejects.toEqual( new Error(`No element was found on the page using '.notanelement'`) ) }) test('returns active element', async () => { const browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) const url = await serve('forms_with_input_elements.html') await browser.visit(url) await browser.wait(Until.elementIsVisible(By.id('new_user_first_name'))) const el1 = await browser.switchTo().activeElement() expect(el1).toBeDefined() expect(el1).not.toBeNull() expect(await el1?.getId()).toBe('new_user_first_name') }) describe('Frame handling', () => { let browser: Browser<any> beforeEach(async () => { browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) const url = await serve('frames.html') await browser.visit(url) }) test('can list all frames', async () => { const frames = browser.frames expect(frames).toHaveLength(3) expect(frames.map((f) => f.name())).toEqual(['', 'frame1', 'frame2']) }) test('can switch frame by index', async () => { await browser.switchTo().frame(0) expect(browser.target.name()).toBe('frame1') await browser.switchTo().frame(1) expect(browser.target.name()).toBe('frame2') await browser.switchTo().defaultContent() expect(browser.target.name()).toBe('') }) test('can switch frame by name', async () => { await browser.switchTo().frame('frame1') expect(browser.target.name()).toBe('frame1') await browser.switchTo().frame('frame2') expect(browser.target.name()).toBe('frame2') await browser.switchTo().defaultContent() expect(browser.target.name()).toBe('') }) test('can switch frame using ElementHandle', async () => { const frame = await browser.findElement('frame[name="frame1"]') await browser.switchTo().frame(frame) expect(browser.target.name()).toBe('frame1') }) test('can interact with another frame', async () => { await browser.switchTo().frame('frame1') expect(browser.target.name()).toBe('frame1') const input = await browser.findElement('input[name="senderElement"]') await input.clear() await input.type('Hello World') expect(await input.getProperty('value')).toBe('Hello World') }) }) describe('timing', () => { test.todo('it receives timing data') test.skip('can inject polyfill for TTI', async () => { const browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) await browser.visit('https://www.google.com') const result = await browser.interactionTiming() expect(result).toBeGreaterThan(10) }) }) describe('auto waiting', () => { test('automatically applies a wait step to actions', async () => { const browser = new Browser(workRoot, playwright, { ...DEFAULT_SETTINGS, waitUntil: 'visible', }) const url = await serve('wait.html') await browser.visit(url) await browser.click(By.id('add_select')) const link = await browser.findElement(By.id('languages')) const linkIsVisible = await link.isDisplayed() expect(linkIsVisible).toBe(true) }) test('fails to return a visible link without waiting', async () => { const browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) const url = await serve('wait.html') await browser.visit(url) await browser.click(By.id('add_select')) const selectTag = await browser.findElement(By.id('languages')) const selectTagIsVisible = await selectTag.isDisplayed() expect(selectTagIsVisible).toBe(false) }) }) describe('send key combination', () => { test('can send combination keys', async () => { const browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) const url = await serve('combination_keys.html') await browser.visit(url) const input = await browser.findElement(By.id('text')) await input.focus() // use combination key as document await browser.sendKeys('a') await browser.sendKeyCombinations(Key.SHIFT, 'KeyA') let text = await input.getProperty('value') expect(text).toBe('aA') await input.clear() // use combination key by normal way with lower case await browser.sendKeys('a') await browser.sendKeyCombinations(Key.SHIFT, 'a') text = await input.getProperty('value') expect(text).toBe('aA') await input.clear() // use combination key by normal way with upper case await browser.sendKeys('a') await browser.sendKeyCombinations(Key.SHIFT, 'A') text = await input.getProperty('value') expect(text).toBe('aA') }) }) test('multiple pages handling', async () => { const browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) const url = await serve('page_1.html') await browser.visit(url) await browser.click(By.tagName('a')) const newPage = await browser.waitForNewPage() expect(newPage.url()).toContain('/page_2.html') const pages = await browser.pages expect(pages.length).toEqual(2) await browser.switchTo().page(0) expect(browser.url).toContain('/page_1.html') await browser.switchTo().page(newPage) expect(browser.url).toContain('/page_2.html') }) test('action getCookies()', async () => { const browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) const url = await serve('test-cookies.html') await browser.visit(url, { waitUntil: 'load' }) const getCookiesByStringName = await browser.getCookies({ names: 'element-cookie' }) expect(getCookiesByStringName.length).toStrictEqual(1) expect(getCookiesByStringName[0].name).toStrictEqual('element-cookie') const getCookiesByStringArray = await browser.getCookies({ names: ['element-cookie', 'floodio'], }) expect(getCookiesByStringArray.length).toStrictEqual(2) expect(getCookiesByStringArray[0].name).toStrictEqual('element-cookie') expect(getCookiesByStringArray[1].name).toStrictEqual('floodio') }) test('action getUrl()', async () => { const browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) const URL = 'https://challenge.flood.io/' await browser.visit(URL, { waitUntil: 'load' }) const currentUrl = browser.getUrl() expect(currentUrl).toStrictEqual(URL) }) describe('scrollTo and scrollBy', () => { let browser: Browser<any> let docScrollHeight: number, docScrollWidth: number, docClientHeight: number, docClientWidth: number beforeEach(async () => { browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) const url = await serve('scroll.html') await browser.visit(url) docScrollHeight = await browser.evaluate(() => Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight ) ) docScrollWidth = await browser.evaluate(() => Math.max( document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.body.clientWidth, document.documentElement.clientWidth ) ) docClientHeight = await browser.evaluate(() => document.documentElement.clientHeight) docClientWidth = await browser.evaluate(() => document.documentElement.clientWidth) }) afterEach(async () => { await browser.scrollTo('top') }) test('scrollTo', async () => { await browser.scrollTo('bottom', { behavior: 'smooth' }) await browser.wait(2) const currentPosAfterScrollBot = await getCurrentPosition(browser) expect(docScrollHeight - docClientHeight).toBe(currentPosAfterScrollBot.top) await browser.scrollTo('right') const currentPosAfterScrollRight = await getCurrentPosition(browser) expect(docScrollWidth - docClientWidth).toBe(currentPosAfterScrollRight.left) await browser.scrollTo('left') const currentPosAfterScrollLeft = await getCurrentPosition(browser) expect(currentPosAfterScrollLeft.left).toBe(0) await browser.scrollTo('top') const currentPosAfterScrollTop = await getCurrentPosition(browser) expect(currentPosAfterScrollTop.top).toBe(0) await browser.scrollTo([1000, 500]) const currentPosAfterScrollToPoint = await getCurrentPosition(browser) expect(currentPosAfterScrollToPoint).toStrictEqual({ top: 500, left: 1000 }) const btn = By.css('.btn') await browser.scrollTo(btn, { block: 'center', inline: 'start' }) const btnEl = await browser.findElement(btn) const btnLocation = await btnEl.location() const btnHeight = (await btnEl?.element.boundingBox())!.height expect(Math.round((docClientHeight - btnHeight) / 2)).toBe(btnLocation.y) expect(btnLocation.x).toBe(0) const paragraph = await browser.findElement(By.css('p')) await browser.scrollTo(paragraph, { block: 'start' }) const paragraphLocation = await paragraph.location() expect(paragraphLocation.y).toBe(0) }) test('scrollBy', async () => { const beforeScrollBy = await getCurrentPosition(browser) await browser.scrollBy(700, 400) const currentPosAfterScrollBy = await getCurrentPosition(browser) expect(currentPosAfterScrollBy).toStrictEqual({ top: beforeScrollBy.top + 400, left: beforeScrollBy.left + 700, }) await browser.scrollBy(-700, -400) const currentPosAfterScrollByAgain = await getCurrentPosition(browser) expect(currentPosAfterScrollByAgain).toStrictEqual({ top: currentPosAfterScrollBy.top - 400, left: currentPosAfterScrollBy.left - 700, }) await browser.scrollTo('top') const currentPosAfterScrollTop = await getCurrentPosition(browser) await browser.scrollBy(0, 'window.innerHeight') const currentPosAfterScrollInnerHeight = await getCurrentPosition(browser) expect(currentPosAfterScrollInnerHeight).toStrictEqual({ top: currentPosAfterScrollTop.top + docClientHeight, left: currentPosAfterScrollTop.left, }) await browser.scrollBy('window.innerWidth', 0) const currentPosAfterScrollInnerWidth = await getCurrentPosition(browser) expect(currentPosAfterScrollInnerWidth).toStrictEqual({ top: currentPosAfterScrollInnerHeight.top, left: currentPosAfterScrollInnerHeight.left + docClientWidth, }) }) }) test('drag an element into another element', async () => { const browser = new Browser(workRoot, playwright, DEFAULT_SETTINGS) const url = await serve('html_drag_drop.html') await browser.visit(url) const from = await browser.findElement(By.id('#draggable')) const to = await browser.findElement(By.id('#droppable')) await browser.drag(from, to) const resultText = await to.text() expect(resultText).toBe('Dropped!') }) })
the_stack
/** * @license Copyright © 2016 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Handles the generation of SVG aircraft map markers. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.svgAircraftMarkerAltitudeLineStroke = VRS.globalOptions.svgAircraftMarkerAltitudeLineStroke === undefined ? '#000' : VRS.globalOptions.svgAircraftMarkerAltitudeLineStroke; VRS.globalOptions.svgAircraftMarkerAltitudeLineWidth = VRS.globalOptions.svgAircraftMarkerAltitudeLineWidth === undefined ? 1 : VRS.globalOptions.svgAircraftMarkerAltitudeLineWidth; VRS.globalOptions.svgAircraftMarkerNormalFill = VRS.globalOptions.svgAircraftMarkerNormalFill === undefined ? '#FFFFFF' : VRS.globalOptions.svgAircraftMarkerNormalFill; VRS.globalOptions.svgAircraftMarkerSelectedFill = VRS.globalOptions.svgAircraftMarkerSelectedFill === undefined ? '#FFFF00' : VRS.globalOptions.svgAircraftMarkerSelectedFill; VRS.globalOptions.svgAircraftMarkerTextShadowFilterXml = VRS.globalOptions.svgAircraftMarkerTextShadowFilterXml === undefined ? `<filter xmlns="http://www.w3.org/2000/svg" style="color-interpolation-filters:sRGB" id="vrs-text-shadow-filter"> <feMorphology in="SourceAlpha" operator="dilate" radius="1" result="fat-text" /> <feGaussianBlur in="fat-text" stdDeviation="1.5" result="blur" /> <feComposite in="SourceGraphic" in2="blur" operator="over" /> </filter>` : VRS.globalOptions.svgAircraftMarkerTextShadowFilterXml; VRS.globalOptions.svgAircraftMarkerTextStyle = VRS.globalOptions.svgAircraftMarkerTextStyle === undefined ? { 'font-family': 'Roboto, Sans-Serif', 'font-size': '8pt', 'font-weight': '700', 'fill': '#FFFFFF' } : VRS.globalOptions.svgAircraftMarkerTextStyle; /** * A class that can generate SVG elements and strings. */ export class SvgGenerator { private _DomParser = new DOMParser(); private _XmlSerialiser = new XMLSerializer(); /** * Serialises an SVG element into a string. * @param svg */ public serialiseSvg(svg: Element) : string { return this._XmlSerialiser.serializeToString(svg); } /** * Returns true if SVG graphics should be used, false if they should not. */ public static useSvgGraphics() : boolean { var result = Modernizr.svg; if(result) { var config = VRS.serverConfig.get(); var pageSetting = VRS.globalOptions.isMobile ? config.UseSvgGraphicsOnMobile : config.UseSvgGraphicsOnDesktop; var reportSetting = VRS.globalOptions.isReport ? config.UseSvgGraphicsOnReports : false; result = pageSetting || reportSetting; } return result; } /** * Generates a disconnected DOM element for an aircraft marker's SVG. * @param embeddedSvg * @param fillColour * @param width * @param height * @param rotation * @param addAltitudeStalk * @param pinTextLines * @param pinTextLineHeight * @param isHighDpi */ public generateAircraftMarker(embeddedSvg: EmbeddedSvg, fillColour: string, width: number, height: number, rotation: number, addAltitudeStalk: boolean, pinTextLines: string[], pinTextLineHeight: number, isHighDpi: boolean) : Element { var result = this.createSvgNode(width, height, this.buildViewBox(0, 0, width, height)); var marker = this.convertXmlIntoNode(embeddedSvg.svg); var markerWidth = Number(marker.getAttribute('width')); var markerHeight = Number(marker.getAttribute('height')); if(addAltitudeStalk) { this.addAltitudeStalk(result, width, height, markerHeight); } this.addMarker(result, marker, embeddedSvg, width, height, markerWidth, markerHeight, fillColour, rotation); if(pinTextLines && pinTextLines.length > 0) { this.addPinText(result, width, height, markerHeight, pinTextLines, pinTextLineHeight); } return result; } private addAltitudeStalk(svg: Element, width: number, height: number, markerHeight: number) { var x = (width / 2) - (VRS.globalOptions.svgAircraftMarkerAltitudeLineWidth / 2); this.addSvgElement(svg, 'line', { x1: x, y1: markerHeight / 2, x2: x, y2: height - 2, 'stroke': VRS.globalOptions.svgAircraftMarkerAltitudeLineStroke, 'stroke-width': VRS.globalOptions.svgAircraftMarkerAltitudeLineWidth }); this.addSvgElement(svg, 'line', { x1: x - 2, y1: height - 4, x2: x + 3, y2: height, 'stroke': VRS.globalOptions.svgAircraftMarkerAltitudeLineStroke, 'stroke-width': VRS.globalOptions.svgAircraftMarkerAltitudeLineWidth }); this.addSvgElement(svg, 'line', { x1: x - 3, y1: height, x2: x + 2, y2: height - 4, 'stroke': VRS.globalOptions.svgAircraftMarkerAltitudeLineStroke, 'stroke-width': VRS.globalOptions.svgAircraftMarkerAltitudeLineWidth }); } private addMarker(svg: Element, marker: Element, embeddedSvg: EmbeddedSvg, width: number, height: number, markerWidth: number, markerHeight: number, fillColour: string, rotation: number) { var offsetX = (width / 2) - (markerWidth / 2); var centerMarkerX = offsetX + (markerWidth / 2); var markerGroup = this.addSvgElement(svg, 'g', { id: 'marker-group', x: offsetX, y: 0, width: markerWidth, height: markerHeight }); if(rotation > 0) { this.setAttribute(markerGroup, { transform: 'rotate(' + rotation % 360 + ',' + centerMarkerX + ',' + markerHeight / 2 + ')' }); } this.setAttribute(marker, { x: offsetX, y: 0 }); if(fillColour && embeddedSvg.aircraftMarkerStatusFillPaths && embeddedSvg.aircraftMarkerStatusFillPaths.length) { var length = embeddedSvg.aircraftMarkerStatusFillPaths.length; for(var i = 0;i < length;++i) { var pathID = embeddedSvg.aircraftMarkerStatusFillPaths[i]; var element = marker.querySelector('#' + pathID); if(element) { element.setAttribute('fill', fillColour); } } } markerGroup.appendChild(marker); } private addPinText(svg: Element, width: number, height: number, markerHeight: number, pinTextLines: string[], pinTextLineHeight: number) { var countLines = pinTextLines.length; var filterElementID: string = null; if(VRS.globalOptions.svgAircraftMarkerTextShadowFilterXml) { var filterElement = this.convertXmlIntoNode(VRS.globalOptions.svgAircraftMarkerTextShadowFilterXml); svg.appendChild(filterElement); filterElementID = filterElement.getAttribute('id'); } var centerX = width / 2; var pinTextHeight = pinTextLineHeight * countLines; var startY = height - (pinTextHeight + 5); var pinTextGroup = this.addSvgElement(svg, 'g', { id: 'pin-text', x: 0, y: startY, width: width, height: pinTextHeight }); var textElement = this.addSvgElement(pinTextGroup, 'text', { x: centerX, y: startY, 'text-anchor': 'middle' }); if(filterElementID) { textElement.setAttribute('filter', 'url(#' + filterElementID + ')'); } for(var i = 0;i < countLines;++i) { var text = pinTextLines[i]; if(text === null || text === undefined || text === '') { text = ' '; } var tspan = this.addSvgElement(textElement, 'tspan', { x: centerX, dy: pinTextLineHeight }); tspan.textContent = text; if(VRS.globalOptions.svgAircraftMarkerTextStyle) { this.setAttribute(tspan, VRS.globalOptions.svgAircraftMarkerTextStyle); } } } private buildViewBox(x: number, y: number, width: number, height: number) : string { return '' + x + ' ' + y + ' ' + width + ' ' + height; } private createElement(element: string, namespace: string = 'http://www.w3.org/2000/svg') : any { var result = document.createElementNS(namespace, element); return result; } private createSvgNode(width: number, height: number, viewBox: string, version: string = '1.1', namespace: string = 'http://www.w3.org/2000/svg') : SVGSVGElement { var result = this.createElement('svg', namespace); this.setAttribute(result, { width: width, height: height, viewBox: viewBox, version: version }); return result; } private convertXmlIntoNode(xml: string, namespace: string = 'http://www.w3.org/2000/svg') : Element { var xmlDoc = this._DomParser.parseFromString(xml, 'image/svg+xml'); var result: Element = null; var length = xmlDoc.childNodes.length; for(var i = 0;i < length;++i) { var node = xmlDoc.childNodes[i]; if(node instanceof Element) { result = <Element>node; break; } } return result; } private setAttribute(node: Element, attributes: Object) : Element { for(var property in attributes) { if(attributes.hasOwnProperty(property)) { node.setAttribute(property, String(attributes[property])); } } return node; } private addSvgElement(parent: Element, element: string, attributes: Object = null, namespace: string = 'http://www.w3.org/2000/svg') : Element { var result = this.createElement(element, namespace); if(attributes) { this.setAttribute(result, attributes); } parent.appendChild(result); return result; } } }
the_stack
import QlogConnectionGroup from '@/data/ConnectionGroup'; import * as qlog02 from '@/data/QlogSchema02'; import QlogConnection from '@/data/Connection'; import { IQlogEventParser, IQlogRawEvent, TimeTrackingMethod } from '@/data/QlogEventParser'; import { EventFieldsParser } from './QlogLoader'; // V2 because we wanted a cleaner separation for draft02 from all the "old style" stuff in the QlogLoader class // eventually, this needs to be refactored so that the V2 class is the main, and then have a QlogLoaderLegacy or something for the rest export class QlogLoaderV2 { public static fromJSON(json:any) : QlogConnectionGroup | undefined { if ( json && json.qlog_version ){ const version = json.qlog_version; if ( qlog02.Defaults.versionAliases.indexOf(version) >= 0 ){ return QlogLoaderV2.fromDraft02(json); } else { console.error("QlogLoaderV2: Unknown qlog version! Only " + qlog02.Defaults.versionAliases + " are supported!", version, json); return undefined; } } else { console.error("QlogLoaderV2: qlog files MUST have a qlog_version field in their top-level object!", json); return undefined; } } protected static fromDraft02(json:any) : QlogConnectionGroup { const fileContents:qlog02.IQLog = json as qlog02.IQLog; console.log("QlogLoaderV2:fromDraft02 : ", fileContents, fileContents.traces); const group = new QlogConnectionGroup(); group.version = fileContents.qlog_version; group.format = fileContents.qlog_format ? "" + fileContents.qlog_format : qlog02.LogFormat.JSON; group.title = fileContents.title || ""; group.description = fileContents.description || ""; for ( let jsonconnection of fileContents.traces ){ const qlogconnections:Array<QlogConnection> = new Array<QlogConnection>(); if ( (jsonconnection as qlog02.ITraceError).error_description !== undefined ) { jsonconnection = jsonconnection as qlog02.ITraceError; const conn = new QlogConnection(group); conn.title = "ERROR"; conn.description = jsonconnection.uri + " : " + jsonconnection.error_description; continue; } jsonconnection = jsonconnection as qlog02.ITrace; // from draft-02 onward, we allow both event_fields (csv-alike setup) and "normal" JSON formats in qvis, // even thoug hthe csv-alike setup has been removed from the draft let usesEventFields:boolean = false; if ( (jsonconnection as any).event_fields !== undefined && (jsonconnection as any).event_fields.length > 0 ) { usesEventFields = true; } // a single trace can contain multiple component "traces" if group_id is used and we need to split them out first let needsSplit:boolean = false; let groupIDKey:string|number = "group_id"; if ( usesEventFields ){ groupIDKey = (jsonconnection as any).event_fields.indexOf("group_id"); if ( groupIDKey >= 0 ) { needsSplit = true; } } else { // if needs split, ALL event need a group_id in this mode if ( jsonconnection.events && jsonconnection.events.length > 0 && jsonconnection.events[0][groupIDKey as any] !== undefined ) { needsSplit = true; } } if ( needsSplit ){ const groupLUT:Map<string, QlogConnection> = new Map<string, QlogConnection>(); for ( const event of jsonconnection.events ) { // allow an empy last element to get around trailing comma restrictions in JSON if ( event.length === 0 || Object.keys(event).length === 0 ) { continue; } let groupID = event[ groupIDKey as any ]; // lookup in JS works both if string or number, magic! if ( typeof groupID !== "string" ) { groupID = JSON.stringify(groupID); } let conn = groupLUT.get(groupID as string); if ( !conn ){ conn = new QlogConnection(group); conn.title = "Group " + groupID + " : "; groupLUT.set( groupID as string, conn ); qlogconnections.push( conn ); } conn.getEvents().push( event as any ); // TODO: remove case once QlogConnection is properly updated! } } // just one component trace, easy mode else { const conn = new QlogConnection(group); qlogconnections.push( conn ); conn.setEvents( jsonconnection.events as any ); // allow an empy last element to get around trailing comma restrictions in JSON const lastEvent = jsonconnection.events[ jsonconnection.events.length - 1 ]; if ( lastEvent.length === 0 || Object.keys(lastEvent).length === 0 ) { conn.getEvents().splice( jsonconnection.events.length - 1, 1 ); } } // component traces share most properties of the overlapping parent trace (e.g., vantage point etc.) for ( const connection of qlogconnections ){ connection.title += jsonconnection.title ? jsonconnection.title : ""; connection.description += jsonconnection.description ? jsonconnection.description : ""; connection.vantagePoint = jsonconnection.vantage_point || {} as qlog02.IVantagePoint; if ( !connection.vantagePoint.type ){ connection.vantagePoint.type = qlog02.VantagePointType.unknown; connection.vantagePoint.flow = qlog02.VantagePointType.unknown; connection.vantagePoint.name = "No VantagePoint set"; } connection.commonFields = jsonconnection.common_fields!; connection.configuration = jsonconnection.configuration || {}; if ( usesEventFields ) { connection.eventFieldNames = (jsonconnection as any).event_fields; connection.setEventParser( new EventFieldsParser() ); } else { connection.setEventParser( new DirectEventParser() ); } // TODO: remove! Slows down normal traces! let misOrdered = false; let minimumTime = -1; for ( const evt of connection.getEvents() ){ const parsedEvt = connection.parseEvent(evt); if ( parsedEvt.absoluteTime >= minimumTime ){ minimumTime = parsedEvt.absoluteTime; } else { misOrdered = true; console.error("QlogLoaderV2:draft02 : timestamps were not in the correct order!", parsedEvt.absoluteTime, " < ", minimumTime, parsedEvt); break; } } if ( misOrdered ){ connection.getEvents().sort( (a, b) => { return connection.parseEvent(a).absoluteTime - connection.parseEvent(b).absoluteTime }); console.error("QlogLoaderV2:draft02 : manually sorted trace on timestamps!", connection.getEvents()); // because startTime etc. could have changes because of the re-ordering if ( connection.eventFieldNames !== undefined && connection.eventFieldNames.length > 0 ) { connection.setEventParser( new EventFieldsParser() ); } else { connection.setEventParser( new DirectEventParser() ); } alert("Loaded trace was not absolutely ordered on event timestamps. We performed a sort() in qvis, but this slows things down and isn't guaranteed to be stable if the timestamps aren't unique! The qlog spec requires absolutely ordered timestamps. See the console for more details."); } // TODO: remove eventually. Mainly sanity checks to make sure draft-02 is properly followed, since there were breaking changes between -01 and -02 const O2errors = []; let incorrectSize = false; let incorrectpayloadlength = false; let incorrectType = false; for ( const evt of connection.getEvents() ){ const parsedEvt = connection.parseEvent(evt); const data = parsedEvt.data; if ( data && data.header ) { if ( data.header.packet_size ) { if ( !incorrectSize ) { O2errors.push( "events had data.header.packet_size set, use data.raw.length instead (example: " + parsedEvt.category + ":" + parsedEvt.name + ")" ); incorrectSize = true; } if ( !data.raw ) { data.raw = {}; } data.raw.length = data.header.packet_size; delete data.header.packet_size; } if ( data.header.payload_length ) { if ( !incorrectpayloadlength ) { O2errors.push( "events had data.header.payload_length set, use data.raw.payload_length instead (example: " + parsedEvt.category + ":" + parsedEvt.name + ")"); incorrectpayloadlength = true; } if ( !data.raw ) { data.raw = {}; } data.raw.payload_length = data.header.payload_length; delete data.header.payload_length; } } if ( data && data.packet_type ) { if ( !incorrectType ) { O2errors.push( "events had data.packet_type set: use data.header.packet_type instead (example: " + parsedEvt.category + ":" + parsedEvt.name + ")"); incorrectType = true; } if ( !data.header ) { data.header = {}; } data.header.packet_type = data.packet_type; delete data.packet_type; } } if ( usesEventFields ) { O2errors.push( "Trace still uses event_fields. This method is deprecated in draft-02, though qvis still supports it. Better to use the more traditional -02 JSON or NDJSON formats instead."); } if ( fileContents.qlog_format === undefined || fileContents.qlog_format.length === 0 ) { O2errors.push( "Trace does not specify a qlog_format entry, which is required in draft-02. JSON was assumed."); } if ( O2errors.length !== 0 ) { console.error("QlogLoaderV2:fromDraft02: ERROR: non-compliant qlog draft-02 trace:"); for ( const err of O2errors ) { console.error( err ); } alert( " ERROR: non-compliant qlog draft-02 trace! \n\n" + O2errors.join("\n\n") + "\n\nqvis has attempted to auto-fix these things, so thing should mostly still work." ); } } } return group; } } // tslint:disable max-classes-per-file export class DirectEventParser implements IQlogEventParser { // in draft-02, we switched from having qlog events as arrays of just values (coupled with "column names" in event_fields) // to using normal JSON objects as events // so [500, "transport", "packet_sent", { ... } ] // became { time: 500, name: "transport:packet_sent", "data": {}} // for the old-style, we use the EventFieldsParser class // for the new-style, this DirectEventParser is used instead private timeTrackingMethod = TimeTrackingMethod.ABSOLUTE_TIME; private addTime:number = 0; private subtractTime:number = 0; private timeMultiplier:number = 1; private _timeOffset:number = 0; private categoryCommon:string = "unknown"; private nameCommon:string = "unknown"; private currentEvent:IQlogRawEvent|undefined|any; public get relativeTime():number { if ( this.currentEvent === undefined || this.currentEvent.time === undefined ) { return 0; } // TODO: now we do this calculation whenever we access the .time property // probably faster to do this in a loop for each event in init(), but this doesn't fit well with the streaming use case... // can probably do the parseFloat up-front though? // return parseFloat((this.currentEvent as IQlogRawEvent)[this.timeIndex]) * this.timeMultiplier - this.subtractTime + this._timeOffset; return parseFloat(this.currentEvent!.time) * this.timeMultiplier - this.subtractTime + this._timeOffset; } public get absoluteTime():number { if ( this.currentEvent === undefined || this.currentEvent.time === undefined ) { return 0; } return parseFloat(this.currentEvent!.time) * this.timeMultiplier + this.addTime + this._timeOffset; } public getAbsoluteStartTime():number { // when relative time, this is reference_time, which is stored in this.addTime // when absolute time, this is the time of the first event, which is stored in this.subtractTime if ( this.timeTrackingMethod === TimeTrackingMethod.RELATIVE_TIME ){ return this.addTime; } else if ( this.timeTrackingMethod === TimeTrackingMethod.ABSOLUTE_TIME ){ return this.subtractTime; } else { console.error("QlogLoader: No proper startTime present in qlog file. This tool doesn't support delta_time yet!"); return 0; } } public get timeOffset():number { return this._timeOffset; } // we either have .name = "category:name" and need to split // OR we just have .category directly public get category():string { if ( this.currentEvent && this.currentEvent.category ) { return this.currentEvent.category; } else if ( this.currentEvent && this.currentEvent.name ) { return this.currentEvent.name.split(":")[0]; // TODO: OPTIMIZE SOMEHOW?!? } else { return this.categoryCommon; } } // this is a bit confusing... // in draft-01, we used the term "type" to describe the event type // but in qvis, we used the term "name" // now, in draft-02, there is actually a "name" field, used to describe the concatenation of category and type (i.e., name = "category:type") // so here, we try to deal with that ambiguity, given that qvis expects just the type when asking for event.name, instead of the concatenation public get name():string { if ( this.currentEvent === undefined || this.currentEvent.name === undefined ) { return this.nameCommon; } // .name SHOULD be "category:name", but it CAN also just be "name" so... // ideally, it would be .type, but we've steered away from that out of fear that 'type' would be a reserved keyword in some language const split = this.currentEvent.name.split(":"); // TODO: OPTIMIZE SOMEHOW?!? if ( split.length > 1 ) { return split[1]; } else { return split[0]; } } public set name(val:string) { if ( this.currentEvent === undefined || this.currentEvent.name === undefined ) { return; } // e.g., "transport:packet_sent" becomed "transport:packet_received" if curName === "packet_sent" const curName = this.name; this.currentEvent.name = this.currentEvent.name.replace( curName, val ); } public get data():any|undefined { if ( this.currentEvent === undefined || this.currentEvent.data === undefined ) { return; } return this.currentEvent.data; } public timeToMilliseconds(time: number | string): number { return parseFloat(time as any) * this.timeMultiplier; } public getTimeTrackingMethod():TimeTrackingMethod { return this.timeTrackingMethod; } public init( trace:QlogConnection ) { this.currentEvent = undefined; if ( trace.commonFields ){ if ( trace.commonFields.category ) { this.categoryCommon = trace.commonFields.category; } if ( trace.commonFields.name ) { this.nameCommon = trace.commonFields.name; } if ( trace.commonFields.time_format ) { if ( trace.commonFields.time_format === qlog02.TimeFormat.relative ) { this.timeTrackingMethod = TimeTrackingMethod.RELATIVE_TIME; } else if ( trace.commonFields.time_format === qlog02.TimeFormat.delta ) { this.timeTrackingMethod = TimeTrackingMethod.DELTA_TIME; } else { this.timeTrackingMethod = TimeTrackingMethod.ABSOLUTE_TIME; } } else { // if choosing relative timestamps, they really SHOULD set time_format // though in draft-01 this wasn't required, so cut people some slack if ( trace.commonFields.reference_time !== undefined ) { this.timeTrackingMethod = TimeTrackingMethod.RELATIVE_TIME; // tslint:disable-next-line:max-line-length console.warn("QlogLoaderV2:Parse: the trace sets reference_time but doesn't set time_format! This is needed starting in draft-02, please change your qlogs! We pretend here that time_format was set to \"relative\".", trace.commonFields); } else { this.timeTrackingMethod = TimeTrackingMethod.ABSOLUTE_TIME; } } } // events are normal JSON objects, typically having 3 properties: time, name, data if ( trace.configuration && trace.configuration.time_units && trace.configuration.time_units === "us" ){ this.timeMultiplier = 0.001; // timestamps are in microseconds, we want to view everything in milliseconds } // We have two main time representations: relative or absolute // We want to convert between the two to give outside users their choice of both // to get ABSOLUTE time: // if relative timestamps : need to do reference_time + time // if absolute timestamps : need to do 0 + time // to get RELATIVE time: // if relative: need to return time - 0 // if absolute: need to return time - events[0].time // so: we need two variables: addTime and subtractTime if ( this.timeTrackingMethod === TimeTrackingMethod.ABSOLUTE_TIME ){ this.addTime = 0; this.subtractTime = parseFloat( (trace.getEvents()[0] as any)!.time ); } else if ( this.timeTrackingMethod === TimeTrackingMethod.RELATIVE_TIME ) { if ( trace.commonFields && trace.commonFields.reference_time !== undefined ){ this.addTime = this.parseReferenceTime( trace.commonFields.reference_time, this.timeMultiplier ); this.subtractTime = 0; } else { console.error("QlogLoaderV2: Using time_format === \"relative\" but no reference_time found in common_fields. Assuming 0.", trace.commonFields); this.addTime = 0; this.subtractTime = 0; } } else if ( this.timeTrackingMethod === TimeTrackingMethod.DELTA_TIME ) { // DELTA_TIME is a weird one: timestamps are encoded relatively to the -previous- one // since we don't always want to loop over events in-order, we support this using a pre-processing step here // we basically construct the ABSOLUTE timestamps for all the events and then pretend we had absolute all along // this only works if we have the events set here though... this.timeTrackingMethod = TimeTrackingMethod.ABSOLUTE_TIME; const allEvents = trace.getEvents() if ( !allEvents || allEvents.length === 0 ) { console.error("QlogLoaderV2: DELTA_TIME requires all events to be set before setEventParser is called... was not the case here!"); } else { // allow both a start time in commonFields.reference_time AND as the first event element if ( trace.commonFields && trace.commonFields.reference_time !== undefined ){ this.addTime = 0; this.subtractTime = this.parseReferenceTime( trace.commonFields.reference_time, this.timeMultiplier ); (allEvents[0] as any).time = parseFloat( (allEvents[0] as any).time ) + this.subtractTime; // so we can start from event 1 below // note: it's not just = this.subtractTime: the ref_time could be set when the process starts and stay the same for many connections that start later // put differently: first timestamp isn't always 0 } else { this.addTime = 0; this.subtractTime = parseFloat( (allEvents[0] as any).time ); } } // transform the timestamps into absolute timestamps starting from the initial time found above // e.g., initial time is 1500, then we have 3, 5, 7 // then the total timestamps should be 1500, 1503, 1508, 1515 let previousTime = this.subtractTime; for ( let i = 1; i < allEvents.length; ++i ) { // start at 1, because the first event can be special, see above // console.log("Starting at ", allEvents[i][ this.timeIndex ], "+", previousTime, " gives ", parseFloat(allEvents[i][ this.timeIndex ]) + previousTime); (allEvents[i] as any).time = parseFloat((allEvents[i] as any).time) + previousTime; previousTime = (allEvents[i] as any).time; } } else { console.error("QlogLoaderV2: No time_format present in qlog file. Pick one of either absolute, relative or delta in common_fields", trace.commonFields); } if ( trace.configuration && trace.configuration.time_offset ){ this._timeOffset = parseFloat( trace.configuration.time_offset ) * this.timeMultiplier; } this.addTime *= this.timeMultiplier; this.subtractTime *= this.timeMultiplier; } public setReferenceTime( time_ms:number ) : void { this.addTime = time_ms; // incoming time MUST BE IN MILLISECONDS for this to work! // as such, the next line isn't needed (and was removed because it led to bugs) // this.addTime *= this.timeMultiplier; } public load( evt:IQlogRawEvent ) : IQlogEventParser { this.currentEvent = evt; return this; } protected parseReferenceTime(refTimeIn:string, multiplier:number) : number { // normally, we expect reference time to be in milliseconds or microseconds since the unix epoch // in this case, parseFloat() gives us the value we need and we later adjust it to milliseconds // however, we also want to support time strings like "2020-08-16T20:53:56.582164977+00:00" // for this, we can use Date.parse and hope things go right. if ( typeof refTimeIn === "string" && ( refTimeIn.indexOf(":") >= 0 || refTimeIn.indexOf("-") >= 0 ) ) { // we assume we have a timestring, let's try console.warn("QlogLoader:parseReferenceTime: We think reference_time is not in 'milliseconds since epoch' as a number, but rather as a time string. That is not really supported, though we'll try to parse it here!", refTimeIn); if ( multiplier === 1 ) { // Date.parse is always in ms accuracy return Date.parse( refTimeIn ); } else { return Date.parse( refTimeIn ) * 1000; // only other option is us, so need to do ms * 1000 to get that (small loss of accuracy here) } } return parseFloat( refTimeIn ); } }
the_stack
import * as decoratorsLib from "../../decorators"; import { Yok } from "../../yok"; import { assert } from "chai"; import { CacheDecoratorsTest } from "./mocks/decorators-cache"; import { InvokeBeforeDecoratorsTest } from "./mocks/decorators-invoke-before"; import { isPromise } from "../../helpers"; import * as stubs from "../../../../test/stubs"; import * as sinon from "sinon"; import { PerformanceService } from "../../../services/performance-service"; import { IInjector } from "../../definitions/yok"; import { injector, setGlobalInjector } from "../../yok"; import * as _ from "lodash"; describe("decorators", () => { const moduleName = "moduleName"; // This is the name of the injected dependency that will be resolved, for example fs, devicesService, etc. const propertyName = "propertyName"; // This is the name of the method/property from the resolved module const expectedResults: any[] = [ "string result", 1, { a: 1, b: "2" }, ["string 1", "string2"], true, undefined, null, ]; beforeEach(() => { setGlobalInjector(new Yok()); injector.register("performanceService", stubs.PerformanceService); }); after(() => { // Make sure global injector is clean for next tests that will be executed. setGlobalInjector(new Yok()); }); describe("exported", () => { const generatePublicApiFromExportedDecorator = () => { assert.deepStrictEqual( injector.publicApi.__modules__[moduleName], undefined ); const resultFunction: any = decoratorsLib.exported(moduleName); // Call this line in order to generate publicApi and get the real result resultFunction({}, propertyName, {}); }; it("returns function", () => { const result: any = decoratorsLib.exported("test"); assert.equal(typeof result, "function"); }); it("does not change original method", () => { const exportedFunctionResult: any = decoratorsLib.exported(moduleName); const expectedResult = { originalObject: "originalValue" }; const actualResult = exportedFunctionResult( {}, "myTest1", expectedResult ); assert.deepStrictEqual(actualResult, expectedResult); }); _.each(expectedResults, (expectedResult: any) => { it(`returns correct result when function returns ${ _.isArray(expectedResult) ? "array" : typeof expectedResult }`, () => { injector.register(moduleName, { propertyName: () => expectedResult }); generatePublicApiFromExportedDecorator(); const actualResult: any = injector.publicApi.__modules__[moduleName][ propertyName ](); assert.deepStrictEqual(actualResult, expectedResult); }); it(`passes correct arguments to original function, when argument type is: ${ _.isArray(expectedResult) ? "array" : typeof expectedResult }`, () => { injector.register(moduleName, { propertyName: (arg: any) => arg }); generatePublicApiFromExportedDecorator(); const actualResult: any = injector.publicApi.__modules__[moduleName][ propertyName ](expectedResult); assert.deepStrictEqual(actualResult, expectedResult); }); }); it("returns Promise, which is resolved to correct value (function without arguments)", (done: mocha.Done) => { const expectedResult = "result"; injector.register(moduleName, { propertyName: async () => expectedResult, }); generatePublicApiFromExportedDecorator(); const promise: any = injector.publicApi.__modules__[moduleName][ propertyName ](); promise .then((val: string) => { assert.deepStrictEqual(val, expectedResult); }) .then(done) .catch(done); }); it("returns Promise, which is resolved to correct value (function with arguments)", (done: mocha.Done) => { const expectedArgs = ["result", "result1", "result2"]; injector.register(moduleName, { propertyName: async (functionArgs: string[]) => functionArgs, }); generatePublicApiFromExportedDecorator(); const promise: any = injector.publicApi.__modules__[moduleName][ propertyName ](expectedArgs); promise .then((val: string[]) => { assert.deepStrictEqual(val, expectedArgs); }) .then(done) .catch(done); }); it("returns Promise, which is resolved to correct value (function returning Promise without arguments)", (done: mocha.Done) => { const expectedResult = "result"; injector.register(moduleName, { propertyName: async () => expectedResult, }); generatePublicApiFromExportedDecorator(); const promise: any = injector.publicApi.__modules__[moduleName][ propertyName ](); promise .then((val: string) => { assert.deepStrictEqual(val, expectedResult); }) .then(done) .catch(done); }); it("returns Promise, which is resolved to correct value (function returning Promise with arguments)", (done: mocha.Done) => { const expectedArgs = ["result", "result1", "result2"]; injector.register(moduleName, { propertyName: async (args: string[]) => args, }); generatePublicApiFromExportedDecorator(); const promise: any = injector.publicApi.__modules__[moduleName][ propertyName ](expectedArgs); promise .then((val: string[]) => { assert.deepStrictEqual(val, expectedArgs); }) .then(done) .catch(done); }); it("rejects Promise, which is resolved to correct error (function without arguments throws)", (done: mocha.Done) => { const expectedError = new Error("Test msg"); injector.register(moduleName, { propertyName: async () => { throw expectedError; }, }); generatePublicApiFromExportedDecorator(); const promise: any = injector.publicApi.__modules__[moduleName][ propertyName ](); promise .then( (result: any) => { throw new Error( "Then method MUST not be called when promise is rejected!" ); }, (err: Error) => { assert.deepStrictEqual(err, expectedError); } ) .then(done) .catch(done); }); it("rejects Promise, which is resolved to correct error (function returning Promise without arguments throws)", (done: mocha.Done) => { const expectedError = new Error("Test msg"); injector.register(moduleName, { propertyName: async () => { throw expectedError; }, }); generatePublicApiFromExportedDecorator(); const promise: any = injector.publicApi.__modules__[moduleName][ propertyName ](); promise .then( (result: any) => { throw new Error( "Then method MUST not be called when promise is rejected!" ); }, (err: Error) => { assert.deepStrictEqual(err.message, expectedError.message); } ) .then(done) .catch(done); }); it("returns Promises, which are resolved to correct value (function returning Promise<T>[] without arguments)", (done: mocha.Done) => { const expectedResultsArr = ["result1", "result2", "result3"]; injector.register(moduleName, { propertyName: () => _.map(expectedResultsArr, async (expectedResult) => expectedResult), }); generatePublicApiFromExportedDecorator(); const promises: Promise<string>[] = injector.publicApi.__modules__[ moduleName ][propertyName](); Promise.all<string>(promises) .then((promiseResults: string[]) => { _.each(promiseResults, (val: string, index: number) => { assert.deepStrictEqual(val, expectedResultsArr[index]); }); }) .then(() => done()) .catch(done); }); it("rejects Promises, which are resolved to correct error (function returning Promise<T>[] without arguments throws)", (done: mocha.Done) => { const expectedErrors = [ new Error("result1"), new Error("result2"), new Error("result3"), ]; injector.register(moduleName, { propertyName: () => _.map(expectedErrors, async (expectedError) => { throw expectedError; }), }); generatePublicApiFromExportedDecorator(); new Promise((onFulfilled: Function, onRejected: Function) => { const promises: Promise<string>[] = injector.publicApi.__modules__[ moduleName ][propertyName](); _.each(promises, (promise, index) => promise.then( (result: any) => { onRejected( new Error( `Then method MUST not be called when promise is rejected!. Result of promise is: ${result}` ) ); }, (err: Error) => { if (err.message !== expectedErrors[index].message) { onRejected( new Error( `Error message of rejected promise is not the expected one: expected: "${expectedErrors[index].message}", but was: "${err.message}".` ) ); } if (index + 1 === expectedErrors.length) { onFulfilled(); } } ) ); }) .then(done) .catch(done); }); it("rejects only Promises which throw, resolves the others correctly (function returning Promise<T>[] without arguments)", (done: mocha.Done) => { const expectedResultsArr: any[] = ["result1", new Error("result2")]; injector.register(moduleName, { propertyName: () => _.map(expectedResultsArr, async (expectedResult) => expectedResult), }); generatePublicApiFromExportedDecorator(); new Promise((onFulfilled: Function, onRejected: Function) => { const promises: Promise<string>[] = injector.publicApi.__modules__[ moduleName ][propertyName](); _.each(promises, (promise, index) => promise.then( (val: string) => { assert.deepStrictEqual(val, expectedResultsArr[index]); if (index + 1 === expectedResultsArr.length) { onFulfilled(); } }, (err: Error) => { assert.deepStrictEqual( err.message, expectedResultsArr[index].message ); if (index + 1 === expectedResultsArr.length) { onFulfilled(); } } ) ); }) .then(done) .catch(done); }); it("when function throws, raises the error only when the public API is called, not when decorator is applied", () => { const errorMessage = "This is error message"; injector.register(moduleName, { propertyName: () => { throw new Error(errorMessage); }, }); generatePublicApiFromExportedDecorator(); assert.throws( () => injector.publicApi.__modules__[moduleName][propertyName](), errorMessage ); }); }); describe("cache", () => { it("executes implementation of method only once and returns the same result each time whent it is called (number return type)", () => { let count = 0; const descriptor: TypedPropertyDescriptor<any> = { value: (num: string) => { count++; return num; }, }; // cache calling of propertyName as if it's been method. const declaredMethod = decoratorsLib.cache()( {}, propertyName, descriptor ); const expectedResult = 5; const actualResult = declaredMethod.value(expectedResult); assert.deepStrictEqual(actualResult, expectedResult); _.range(10).forEach((iteration) => { const currentResult = declaredMethod.value(iteration); assert.deepStrictEqual(currentResult, expectedResult); }); assert.deepStrictEqual(count, 1); }); it("works per instance", () => { const instance1 = new CacheDecoratorsTest(); const expectedResultForInstance1 = 1; assert.deepStrictEqual( instance1.method(expectedResultForInstance1), expectedResultForInstance1 ); // the first call should give us the expected result. all consecutive calls must return the same result. _.range(10).forEach((iteration) => { const currentResult = instance1.method(iteration); assert.deepStrictEqual(currentResult, expectedResultForInstance1); }); assert.deepStrictEqual(instance1.counter, 1); const instance2 = new CacheDecoratorsTest(); const expectedResultForInstance2 = 2; assert.deepStrictEqual( instance2.method(expectedResultForInstance2), expectedResultForInstance2, "Instance 2 should return new result." ); // the first call should give us the expected result. all consecutive calls must return the same result. _.range(10).forEach((iteration) => { const currentResult = instance2.method(iteration); assert.deepStrictEqual(currentResult, expectedResultForInstance2); }); assert.deepStrictEqual(instance2.counter, 1); }); it("works with method returning promise", async () => { const instance1 = new CacheDecoratorsTest(); const expectedResultForInstance1 = 1; assert.deepStrictEqual( await instance1.promisifiedMethod(expectedResultForInstance1), expectedResultForInstance1 ); // the first call should give us the expected result. all consecutive calls must return the same result. for (let iteration = 0; iteration < 10; iteration++) { const promise = instance1.promisifiedMethod(iteration); assert.isTrue( isPromise(promise), "Returned result from the decorator should be promise." ); const currentResult = await promise; assert.deepStrictEqual(currentResult, expectedResultForInstance1); } assert.deepStrictEqual(instance1.counter, 1); }); it("works with getters", () => { const instance1 = new CacheDecoratorsTest(); const expectedResultForInstance1 = 1; instance1._property = expectedResultForInstance1; assert.deepStrictEqual(instance1.property, expectedResultForInstance1); // the first call should give us the expected result. all consecutive calls must return the same result. for (let iteration = 0; iteration < 10; iteration++) { instance1._property = iteration; assert.deepStrictEqual(instance1.property, expectedResultForInstance1); } assert.deepStrictEqual(instance1.counter, 1); }); }); describe("invokeBefore", () => { describe("calls method before calling decorated method", () => { const assertIsCalled = async (methodName: string): Promise<void> => { const instance: any = new InvokeBeforeDecoratorsTest(); assert.isFalse(instance.isInvokeBeforeMethodCalled); const expectedResult = 1; assert.deepStrictEqual( await instance[methodName](expectedResult), expectedResult ); assert.isTrue(instance.isInvokeBeforeMethodCalled); }; it("when invokeBefore method is sync", async () => { await assertIsCalled("method"); }); it("when invokeBefore method returns Promise", async () => { await assertIsCalled("methodPromisifiedInvokeBefore"); }); }); describe("calls method each time before calling decorated method", () => { const assertIsCalled = async (methodName: string): Promise<void> => { const instance: any = new InvokeBeforeDecoratorsTest(); assert.isFalse(instance.isInvokeBeforeMethodCalled); const expectedResult = 1; assert.deepStrictEqual( await instance[methodName](expectedResult), expectedResult ); assert.isTrue(instance.isInvokeBeforeMethodCalled); instance.invokedBeforeCount = 0; for (let iteration = 0; iteration < 10; iteration++) { instance.isInvokeBeforeMethodCalled = false; assert.deepStrictEqual( await instance[methodName](iteration), iteration ); assert.isTrue(instance.isInvokeBeforeMethodCalled); assert.deepStrictEqual(instance.invokedBeforeCount, iteration + 1); } }; it("when invokeBefore method is sync", async () => { await assertIsCalled("method"); }); it("when invokeBefore method returns Promise", async () => { await assertIsCalled("methodPromisifiedInvokeBefore"); }); }); describe("throws error in case the invokeBefore method throws", () => { const assertThrows = async (methodName: string): Promise<void> => { const instance: any = new InvokeBeforeDecoratorsTest(); assert.isFalse(instance.isInvokeBeforeMethodCalled); const expectedResult = 1; await assert.isRejected( instance[methodName](expectedResult), expectedResult ); assert.isTrue(instance.isInvokeBeforeMethodCalled); }; it("when invokeBefore method is sync", async () => { await assertThrows("methodInvokeBeforeThrowing"); }); it("when invokeBefore method is sync", async () => { await assertThrows("methodPromisifiedInvokeBeforeThrowing"); }); }); describe("passes correct args to invokeBefore method", () => { const assertIsCalled = async (methodName: string): Promise<void> => { const instance: any = new InvokeBeforeDecoratorsTest(); assert.isFalse(instance.isInvokeBeforeMethodCalled); const expectedResult = 1; assert.deepStrictEqual( await instance[methodName](expectedResult), expectedResult ); assert.isTrue(instance.isInvokeBeforeMethodCalled); assert.deepStrictEqual(instance.invokedBeforeArgument, "arg1"); }; it("when invokeBefore method is sync", async () => { await assertIsCalled("methodCallingInvokeBeforeWithArgs"); }); it("when invokeBefore method is sync", async () => { await assertIsCalled("methodPromisifiedInvokeBeforeWithArgs"); }); }); }); describe("performanceLog", () => { const testErrorMessage = "testError"; let testInjector: IInjector; let sandbox: sinon.SinonSandbox; interface ITestInterface { testMethod(arg: any): any; throwMethod?(): void; testAsyncMehtod(arg: any): Promise<any>; rejectMethod?(): Promise<any>; } let testInstance: ITestInterface; let undecoratedTestInstance: ITestInterface; function createTestInjector(): IInjector { testInjector = new Yok(); testInjector.register("performanceService", PerformanceService); testInjector.register("options", {}); testInjector.register("fs", stubs.FileSystemStub); testInjector.register("logger", stubs.LoggerStub); testInjector.register("analyticsService", { trackEventActionInGoogleAnalytics: () => { return Promise.resolve(); }, }); return testInjector; } beforeEach(() => { sandbox = sinon.createSandbox(); testInjector = createTestInjector(); class TestClass implements ITestInterface { @decoratorsLib.performanceLog(testInjector) testMethod(arg: any) { return arg; } @decoratorsLib.performanceLog(testInjector) throwMethod() { throw new Error("testErrorMessage"); } @decoratorsLib.performanceLog(testInjector) async testAsyncMehtod(arg: any) { return Promise.resolve(arg); } rejectMethod() { return Promise.reject(testErrorMessage); } } class UndecoratedTestClass implements ITestInterface { testMethod(arg: any) { return arg; } async testAsyncMehtod(arg: any) { return Promise.resolve(arg); } } undecoratedTestInstance = new UndecoratedTestClass(); testInstance = new TestClass(); }); afterEach(() => { sandbox.restore(); }); _.each(expectedResults, (expectedResult: any) => { it("returns proper result", () => { const actualResult = testInstance.testMethod(expectedResult); assert.deepStrictEqual(actualResult, expectedResult); }); it("returns proper result when async", () => { const promise = testInstance.testAsyncMehtod(expectedResult); assert.notDeepEqual(promise.then, undefined); return promise.then((actualResult: any) => { assert.deepStrictEqual(actualResult, expectedResult); }); }); }); it("method has same toString", () => { assert.equal( testInstance.testMethod.toString(), undecoratedTestInstance.testMethod.toString() ); }); it("method has same name", () => { assert.equal( testInstance.testMethod.name, undecoratedTestInstance.testMethod.name ); }); it("does not eat errors", () => { assert.throws(testInstance.throwMethod, testErrorMessage); assert.isRejected(testInstance.rejectMethod(), testErrorMessage); }); it("calls performance service on method call", async () => { const performanceService = testInjector.resolve("performanceService"); const processExecutionDataStub: sinon.SinonStub = sinon.stub( performanceService, "processExecutionData" ); const checkSubCall = (call: sinon.SinonSpyCall, methodData: string) => { const callArgs = call.args; const methodInfo = callArgs[0]; const startTime = callArgs[1]; const endTime = callArgs[2]; assert(methodInfo === methodData); assert.isNumber(startTime); assert.isNumber(endTime); assert.isTrue(endTime > startTime); assert.isDefined(callArgs[3][0] === "test"); }; testInstance.testMethod("test"); await testInstance.testAsyncMehtod("test"); checkSubCall(processExecutionDataStub.firstCall, "TestClass__testMethod"); checkSubCall( processExecutionDataStub.secondCall, "TestClass__testAsyncMehtod" ); }); }); describe("deprecated", () => { const testDepMessage = "Just stop using this!"; const warnings: string[] = []; let testInjector: IInjector; interface ITestInterface { testField: string; testProp: string; depMethodWithParam(arg: any): any; depMethodWithoutParam(): void; depAsyncMethod(arg: any): Promise<any>; nonDepMethod(): any; } let testInstance: ITestInterface; function createTestInjector(): IInjector { testInjector = new Yok(); testInjector.register("config", {}); testInjector.register("options", {}); testInjector.register("logger", { warn: (message: string) => { warnings.push(message); }, }); return testInjector; } beforeEach(() => { warnings.splice(0, warnings.length); testInjector = createTestInjector(); class TestClass implements ITestInterface { public testField: string = "test"; @decoratorsLib.deprecated(testDepMessage, testInjector) public get testProp(): string { return "hi"; } public set testProp(value: string) { return; } @decoratorsLib.deprecated(testDepMessage, testInjector) depMethodWithParam(arg: any) { return arg; } @decoratorsLib.deprecated(testDepMessage, testInjector) depMethodWithoutParam() { return; } @decoratorsLib.deprecated(testDepMessage, testInjector) async depAsyncMethod(arg: any) { return Promise.resolve(arg); } nonDepMethod() { return; } } testInstance = new TestClass(); }); it("method without params", () => { testInstance.depMethodWithoutParam(); assert.equal(warnings.length, 1); assert.equal( warnings[0], `depMethodWithoutParam is deprecated. ${testDepMessage}` ); }); it("method with params", () => { const param = 5; const result = testInstance.depMethodWithParam(param); assert.equal(result, param); assert.equal(warnings.length, 1); assert.equal( warnings[0], `depMethodWithParam is deprecated. ${testDepMessage}` ); }); it("async method with params", async () => { const param = 5; const result = await testInstance.depAsyncMethod(param); assert.equal(result, param); assert.equal(warnings.length, 1); assert.equal( warnings[0], `depAsyncMethod is deprecated. ${testDepMessage}` ); }); it("property getter", async () => { const result = testInstance.testProp; assert.equal(result, "hi"); assert.equal(warnings.length, 1); assert.equal(warnings[0], `testProp is deprecated. ${testDepMessage}`); }); it("property setter", async () => { testInstance.testProp = "newValue"; assert.equal(warnings.length, 1); assert.equal(warnings[0], `testProp is deprecated. ${testDepMessage}`); }); it("non deprecated field", async () => { const result = testInstance.testField; assert.equal(result, "test"); assert.equal(warnings.length, 0); }); it("non deprecated method", () => { testInstance.nonDepMethod(); assert.equal(warnings.length, 0); }); it("class", async () => { @decoratorsLib.deprecated(testDepMessage, testInjector) class TestClassDeprecated {} const depClass = new TestClassDeprecated(); assert.isNotNull(depClass); assert.equal(warnings.length, 1); assert.equal( warnings[0], `TestClassDeprecated is deprecated. ${testDepMessage}` ); }); }); });
the_stack
import { Injectable } from '@nestjs/common' import { InjectModel } from '@nestjs/sequelize' import { Sequelize } from 'sequelize-typescript' import { Op } from 'sequelize' import * as kennitala from 'kennitala' import { Actions, Airlines, States, } from '@island.is/air-discount-scheme/consts' import { FlightLegSummary } from './flight.types' import { Flight, FlightLeg, financialStateMachine } from './flight.model' import { CreateFlightBody, GetFlightLegsBody } from './dto' import { NationalRegistryUser } from '../nationalRegistry' export const ADS_POSTAL_CODES = { Reykhólahreppur: 380, // from Reykhólahreppur to Þingeyri Þingeyri: 471, Hólmavík: 510, // from Hólmavík to Öræfi Öræfi: 785, Vestmannaeyjar: 900, } const DEFAULT_AVAILABLE_LEGS = 6 const AVAILABLE_FLIGHT_LEGS: { [year: string]: number } = { '2020': 2, '2021': 6, } const availableFinancialStates = [ financialStateMachine.states[States.awaitingDebit].key, financialStateMachine.states[States.sentDebit].key, ] export const CONNECTING_FLIGHT_GRACE_PERIOD = 48 * (1000 * 60 * 60) // 48 hours in milliseconds export const REYKJAVIK_FLIGHT_CODES = ['RKV', 'REK'] export const AKUREYRI_FLIGHT_CODES = ['AEY'] export const ALLOWED_CONNECTING_FLIGHT_CODES = ['VPN', 'GRY', 'THO'] @Injectable() export class FlightService { constructor( @InjectModel(Flight) private flightModel: typeof Flight, @InjectModel(FlightLeg) private flightLegModel: typeof FlightLeg, ) {} isADSPostalCode(postalcode: number): boolean { if ( postalcode >= ADS_POSTAL_CODES['Reykhólahreppur'] && postalcode <= ADS_POSTAL_CODES['Þingeyri'] ) { return true } else if ( postalcode >= ADS_POSTAL_CODES['Hólmavík'] && postalcode <= ADS_POSTAL_CODES['Öræfi'] ) { return true } else if (postalcode === ADS_POSTAL_CODES['Vestmannaeyjar']) { return true } return false } hasConnectingFlightPotentialFromFlightLegs( firstFlight: FlightLeg, secondFlight: FlightLeg, ): boolean { // If neither flight is connected to Reykjavik in any way // then it is not eligible if ( !REYKJAVIK_FLIGHT_CODES.includes(firstFlight.destination) && !REYKJAVIK_FLIGHT_CODES.includes(firstFlight.origin) && !REYKJAVIK_FLIGHT_CODES.includes(secondFlight.destination) && !REYKJAVIK_FLIGHT_CODES.includes(secondFlight.origin) ) { return false } // If neither flight is connected to the allowed connecting flight places // then it is not eligible if ( !ALLOWED_CONNECTING_FLIGHT_CODES.includes(firstFlight.destination) && !ALLOWED_CONNECTING_FLIGHT_CODES.includes(firstFlight.origin) && !ALLOWED_CONNECTING_FLIGHT_CODES.includes(secondFlight.destination) && !ALLOWED_CONNECTING_FLIGHT_CODES.includes(secondFlight.origin) ) { return false } // Both flights need to touch Akureyri in some way, that is to say, // Akureyri has to be a common point, ex: Reykjavik-Akureyri > Akureyri-Grimsey // Logic: If not (Akureyri in destination or origin of strictly both flights) return false if ( !( AKUREYRI_FLIGHT_CODES.includes(firstFlight.destination) || AKUREYRI_FLIGHT_CODES.includes(firstFlight.origin) ) || !( AKUREYRI_FLIGHT_CODES.includes(secondFlight.destination) || AKUREYRI_FLIGHT_CODES.includes(secondFlight.origin) ) ) { return false } let delta = secondFlight.date.getTime() - firstFlight.date.getTime() // The order must be flipped if we subtract the first intended chronological leg // from the second intended chronological leg if ( REYKJAVIK_FLIGHT_CODES.includes(secondFlight.origin) || REYKJAVIK_FLIGHT_CODES.includes(firstFlight.destination) ) { delta = -delta } if (delta >= 0 && delta <= CONNECTING_FLIGHT_GRACE_PERIOD) { return true } return false } async isFlightLegConnectingFlight( existingFlightId: string, incomingLeg: FlightLeg, ): Promise<boolean> { // Get the corresponding flight for the connection discount code const existingFlight = await this.flightModel.findOne({ where: { id: existingFlightId, }, include: [ { model: this.flightLegModel, where: { financialState: availableFinancialStates }, }, ], }) if (!existingFlight) { return false } // If a user flightLeg exists such that the incoming flightLeg makes a valid connection // pair, return true for (const flightLeg of existingFlight.flightLegs) { if ( this.hasConnectingFlightPotentialFromFlightLegs(flightLeg, incomingLeg) ) { return true } } return false } async findThisYearsConnectableFlightsByNationalId( nationalId: string, ): Promise<Flight[]> { const flights = await this.findThisYearsFlightsByNationalId(nationalId) // Filter out non-Reykjavík and non-Akureyri flights return flights.filter((flight) => flight.connectable) } async countThisYearsFlightLegsByNationalId( nationalId: string, ): Promise<FlightLegSummary> { const currentYear = new Date(Date.now()).getFullYear().toString() let availableLegsThisYear = DEFAULT_AVAILABLE_LEGS if (Object.keys(AVAILABLE_FLIGHT_LEGS).includes(currentYear)) { availableLegsThisYear = AVAILABLE_FLIGHT_LEGS[currentYear] } const noFlightLegs = await this.flightModel.count({ where: Sequelize.and( Sequelize.where( Sequelize.fn( 'date_part', 'year', Sequelize.fn('date', Sequelize.col('booking_date')), ), currentYear, ), { nationalId }, ), include: [ { model: this.flightLegModel, where: { financialState: availableFinancialStates, isConnectingFlight: false, }, }, ], }) return { used: noFlightLegs, unused: availableLegsThisYear - noFlightLegs, total: availableLegsThisYear, } } findAll(): Promise<Flight[]> { return this.flightModel.findAll({ include: [ { model: this.flightLegModel, where: { financialState: availableFinancialStates }, }, ], }) } findAllLegsByFilter(body: GetFlightLegsBody | any): Promise<FlightLeg[]> { const awaitingCredit = financialStateMachine.states[States.awaitingCredit].key return this.flightLegModel.findAll({ where: { ...(body.airline ? { airline: body.airline } : {}), ...(body.state && body.state.length > 0 ? { financialState: body.state } : {}), ...(body.flightLeg?.from ? { origin: body.flightLeg.from } : {}), ...(body.flightLeg?.to ? { destination: body.flightLeg.to } : {}), // We want to show rows that are awaiting credit based on their // financial_state_updated instead of booking_date because if they // were booked long ago and have recently been cancelled they need // to show up on the correct monthly report [Op.or]: [ { [Op.and]: [ { financialState: { [Op.eq]: awaitingCredit } }, { financialStateUpdated: { [Op.gte]: new Date(body.period.from) }, }, { financialStateUpdated: { [Op.lte]: new Date(body.period.to) } }, ], }, { [Op.and]: [ { financialState: { [Op.ne]: awaitingCredit } }, { '$flight.booking_date$': { [Op.gte]: new Date(body.period.from), }, }, { '$flight.booking_date$': { [Op.lte]: new Date(body.period.to) }, }, ], }, ], }, include: [ { model: this.flightModel, where: Sequelize.and( Sequelize.where( Sequelize.literal("(user_info->>'age')::numeric"), '>=', body.age.from, ), Sequelize.where( Sequelize.literal("(user_info->>'age')::numeric"), '<=', body.age.to, ), { ...(body.gender ? { 'userInfo.gender': body.gender } : {}), ...(body.postalCode ? { 'userInfo.postalCode': body.postalCode } : {}), }, ), }, ], }) } findThisYearsFlightsByNationalId(nationalId: string): Promise<Flight[]> { const currentYear = new Date(Date.now()).getFullYear().toString() return this.findFlightsByYearAndNationalId(nationalId, currentYear) } findFlightsByYearAndNationalId( nationalId: string, year: string, ): Promise<Flight[]> { return this.flightModel.findAll({ where: Sequelize.and( Sequelize.where( Sequelize.fn( 'date_part', 'year', Sequelize.fn('date', Sequelize.col('booking_date')), ), year, ), { nationalId }, ), include: [ { model: this.flightLegModel, where: { financialState: availableFinancialStates }, }, ], }) } create( flight: CreateFlightBody, user: NationalRegistryUser, airline: ValueOf<typeof Airlines>, isConnectable: boolean, connectingId?: string, ): Promise<Flight> { const nationalId = user.nationalId if (!isConnectable && connectingId) { this.flightModel.update( { connectable: false, }, { where: { id: connectingId }, }, ) } return this.flightModel.create( { ...flight, flightLegs: flight.flightLegs.map((flightLeg) => ({ ...flightLeg, airline, isConnectingFlight: !isConnectable && Boolean(connectingId), })), nationalId, userInfo: { age: kennitala.info(nationalId).age, gender: user.gender, postalCode: user.postalcode, }, connectable: isConnectable, }, { include: [this.flightLegModel] }, ) } findOne( flightId: string, airline: ValueOf<typeof Airlines>, ): Promise<Flight | null> { return this.flightModel.findOne({ where: { id: flightId, }, include: [ { model: this.flightLegModel, where: { financialState: availableFinancialStates, airline, }, }, ], }) } private updateFinancialState( flightLeg: FlightLeg, action: ValueOf<typeof Actions>, changeByAirline: boolean, ): Promise<FlightLeg> { const financialState = financialStateMachine .transition(flightLeg.financialState, action) .value.toString() return flightLeg.update({ financialState, financialStateUpdated: changeByAirline ? new Date() : flightLeg.financialStateUpdated, }) } finalizeCreditsAndDebits(flightLegs: FlightLeg[]): Promise<FlightLeg[]> { return Promise.all( flightLegs.map((flightLeg) => { const finalizingStates = [States.awaitingDebit, States.awaitingCredit] if (!finalizingStates.includes(flightLeg.financialState)) { return flightLeg } return this.updateFinancialState(flightLeg, Actions.send, false) }), ) } delete(flight: Flight): Promise<FlightLeg[]> { return Promise.all( flight.flightLegs.map((flightLeg: FlightLeg) => this.deleteFlightLeg(flightLeg), ), ) } deleteFlightLeg(flightLeg: FlightLeg): Promise<FlightLeg> { return this.updateFinancialState(flightLeg, Actions.revoke, true) } }
the_stack
import * as React from 'react'; import * as actions from '../../actions'; import './index.less'; import '../../index.less'; import { Modal, Button, Input, Transfer, Tooltip, Select } from 'antd'; import { CustomBreadcrumb, CommonHead } from '../../component/CustomComponent'; import { getAgentListColumns, agentBreadcrumb, getQueryFormColumns } from './config'; import { IAgentHostVo, IAgentHostParams, IAgentVersion, IService, IAgentQueryFormColumns, IAgentHostSet, IOperationTasksParams } from '../../interface/agent'; import { agentHead, empty } from '../../constants/common'; import { getAgent, getAgentVersion, getServices, getTaskExists, createOperationTasks } from '../../api/agent'; import { connect } from "react-redux"; import { BasicTable } from 'antd-advanced'; import { regIp } from '../../constants/reg'; import { Dispatch } from 'redux'; import { findDOMNode } from 'react-dom'; const mapDispatchToProps = (dispatch: Dispatch) => ({ setModalId: (modalId: string, params?: any) => dispatch(actions.setModalId(modalId, params)), setDrawerId: (drawerId: string, params?: any) => dispatch(actions.setDrawerId(drawerId, params)), }); type Props = ReturnType<typeof mapDispatchToProps>; @connect(null, mapDispatchToProps) export class AgentList extends React.Component<Props> { public versionRef = null as any; public healthRef = null as any; public containerRef = null as any; constructor(props: any) { super(props) this.versionRef = React.createRef(); this.healthRef = React.createRef(); this.containerRef = React.createRef(); } public state = { loading: true, selectedRowKeys: [], includedInstalled: false, noInstalledHosts: [] as IAgentHostSet[], agentIds: [] as number[], includednoInstalled: false, installedHosts: [] as IAgentHostSet[], agentList: [], agentVersionList: [], servicesList: [], hidefer: false, targetKeys: [], applyInput: '', direction: 'left', total: 0, form: '', queryParams: { pageNo: 1, pageSize: 20, agentHealthLevelList: [], agentVersionIdList: [], containerList: [], hostCreateTimeEnd: empty, hostCreateTimeStart: empty, serviceIdList: [], hostName: empty, ip: empty, } as IAgentHostParams, } public filterApplyOption = (inputValue: any, option: any) => { return option.servicename.indexOf(inputValue) > -1; } public onApplyChange = (targetKeys: any, direction: any) => { this.setState({ applyInput: `已选择${targetKeys?.length}项`, hidefer: true, targetKeys, direction, }); }; public onApplySearch = (dir: any, value: any) => { // console.log('search:', dir, value); }; public onInputClick = () => { const { targetKeys, direction, servicesList } = this.state; let keys = [] as number[]; if (direction === 'right') { keys = targetKeys; } else if (direction === 'left') { if (targetKeys?.length === servicesList?.length) { keys = []; } else { keys = targetKeys; } } this.setState({ applyInput: keys?.length ? `已选择${keys?.length}项` : '', hidefer: true, targetKeys: keys, }); } public handleClickOutside(e: any) { // 组件已挂载且事件触发对象不在div内 let result = findDOMNode(this.refs.refTest)?.contains(e.target); if (!result) { this.setState({ hidefer: false }); } } public queryFormColumns() { const { agentVersionList, servicesList, targetKeys, hidefer, applyInput, form } = this.state; const applyObj = { type: 'custom', title: '承载应用', dataIndex: 'serviceIdList', component: ( <div className='apply-box'> <Select // mode="multiple" placeholder='请选择' // ref={containerRef} allowClear={true} showArrow={true} // onInputKeyDown={() => { // form.resetFields(['containerList']); // containerRef.current.blur(); // }} // maxTagCount={0} // maxTagPlaceholder={(values) => values?.length ? `已选择${values?.length}项` : '请选择'} > {servicesList.map((d: any, index) => { return <Select.Option value={d.id} key={index}>{d.servicename}</ Select.Option> })} </Select> {/* <Input value={applyInput} placeholder='请选择' onClick={this.onInputClick} /> {hidefer && <div className='apply' ref="refTest"> <Transfer dataSource={servicesList} showSearch filterOption={this.filterApplyOption} targetKeys={targetKeys} onChange={this.onApplyChange} onSearch={this.onApplySearch} render={item => item.servicename} className="customTransfer" /> </div>} */} </div> ), }; const queryColumns = getQueryFormColumns(agentVersionList, this.versionRef, this.healthRef, this.containerRef, form); queryColumns.splice(3, 0, applyObj); return queryColumns; } public setServiceIdList = () => { const { servicesList, targetKeys } = this.state; const serviceIds = [] as number[]; servicesList.map((ele: IService, index) => { if (targetKeys?.includes(index as never)) { serviceIds.push(ele.id); } }); return serviceIds; } public onChangeParams = (values: IAgentQueryFormColumns, form: any) => { // 表单的值改变时触发的回调 const { pageNo, pageSize } = this.state.queryParams; let ip = ''; let hostName = ''; if (new RegExp(regIp).test(values?.hostNameOrIp)) { ip = values?.hostNameOrIp || ''; } else { hostName = values?.hostNameOrIp || ''; } this.setState({ form, queryParams: { pageNo, pageSize, agentHealthLevelList: values?.agentHealthLevelList || [], agentVersionIdList: values?.agentVersionIdList ? [values.agentVersionIdList] : [], containerList: values?.containerList ? [values?.containerList] : [], hostCreateTimeStart: values?.hostCreateTime?.length ? values?.hostCreateTime[0]?.valueOf() : '', hostCreateTimeEnd: values?.hostCreateTime?.length ? values?.hostCreateTime[1]?.valueOf() : '', serviceIdList: this.setServiceIdList(), hostName, ip, } as IAgentHostParams, }) } public onSearchParams = () => { // 点击查询按钮的回调 const { queryParams, targetKeys } = this.state; if (targetKeys?.length > 0) { queryParams.serviceIdList = this.setServiceIdList(); } else { queryParams.serviceIdList = [] this.setState({ targetKeys: [], applyInput: '', direction: 'left', }); } this.getAgentData(this.state.queryParams); } public onResetParams = () => { const resetParams = { pageNo: 1, pageSize: 20, agentHealthLevelList: [], agentVersionIdList: [], containerList: [], hostCreateTimeEnd: empty, hostCreateTimeStart: empty, serviceIdList: [], hostName: empty, ip: empty, } as IAgentHostParams; this.setState({ queryParams: resetParams, targetKeys: [], applyInput: '', direction: 'left', }); this.getAgentData(resetParams); } public getData = () => { this.setState({ selectedRowKeys: [], includedInstalled: false, noInstalledHosts: [], agentIds: [], includednoInstalled: false, installedHosts: [], }); this.getAgentData(this.state.queryParams) } public agentListColumns() { const getData = () => this.getData(); const columns = getAgentListColumns(this.props.setModalId, this.props.setDrawerId, getData); return columns; } public handleNewHost = () => { this.props.setModalId('NewHost', { cb: () => this.getAgentData(this.state.queryParams), }); } public handleHost = (taskType: number, hosts: IAgentHostSet[]) => { this.props.setModalId('InstallHost', { taskType, hosts, cb: () => this.getData(), }); } public handleInstallHost = () => { // 安装 0 const { includedInstalled, noInstalledHosts } = this.state; if (!noInstalledHosts?.length) { return Modal.confirm({ title: `请先选择需要安装的主机!` }); } if (includedInstalled) { return Modal.confirm({ title: `存在已安装Agent的主机,已为您自动取消!`, onOk: () => this.handleHost(0, noInstalledHosts), }); } return this.handleHost(0, noInstalledHosts); } public handleUpgradeHost = () => { // 升级 2 const { installedHosts, includednoInstalled } = this.state; if (!installedHosts?.length) { return Modal.confirm({ title: `请先选择需要升级的主机!` }); } if (includednoInstalled) { return Modal.confirm({ title: `存在未安装Agent的主机,已为您自动取消!`, onOk: () => this.openUpgradeHost(), }); } return this.openUpgradeHost(); } public openUpgradeHost = () => { const { agentIds, installedHosts } = this.state; getTaskExists(JSON.stringify(agentIds)).then((res: boolean) => { if (res) { return Modal.confirm({ title: <a className='fail'>选中agent有采集任务正在运行,升级操作将会中断采集,是否继续?</a>, onOk: () => this.handleHost(2, installedHosts), }); } return this.handleHost(2, installedHosts); }).catch((err: any) => { // console.log(err); }); } public handleUninstallHost = () => { // 卸载 1 const { installedHosts, includednoInstalled } = this.state; if (!installedHosts?.length) { return Modal.confirm({ title: `请先选择需要卸载的主机!` }); } if (includednoInstalled) { return Modal.confirm({ title: `存在未安装Agent的主机,已为您自动取消!`, onOk: () => this.openUninstallHost(), }); } return this.openUninstallHost(); } public openUninstallHost = () => { const { agentIds } = this.state; getTaskExists(JSON.stringify(agentIds)).then((res: boolean) => { if (res) { return Modal.confirm({ title: <a className='fail'>选中agent有采集任务正在运行,需要操作将会中断采集,是否继续?</a>, onOk: () => this.uninstallHostModal(res), }); } return this.uninstallHostModal(res); }).catch((err: any) => { // console.log(err); }); } public uninstallHostModal = (check: boolean) => { Modal.confirm({ title: `确认卸载选中Agent吗?`, content: <a className="fail">卸载操作不可恢复,请谨慎操作!</a>, onOk: () => this.uninstallHost(check), }); } public uninstallHost = (check: boolean) => { const { agentIds, installedHosts } = this.state; const params = { agentIds, checkAgentCompleteCollect: check ? 1 : 0, // 1检查 0 不检查 agentVersionId: empty, hostIds: [], taskType: 1, } as IOperationTasksParams; createOperationTasks(params).then((res: number) => { Modal.success({ title: <><a href="/agent/operationTasks">{agentIds?.length > 1 ? '批量' : installedHosts[0]?.hostName}卸载Agent任务(任务ID:{res})</a>创建成功!</>, content: '可点击标题跳转,或至“Agent中心”>“运维任务”模块查看详情', okText: '确认', onOk: () => { this.setState({ selectedRowKeys: [] }); this.getAgentData(this.state.queryParams); }, }); }).catch((err: any) => { // console.log(err); }); } public onSelectChange = (selectedRowKeys: any, selectedRows: IAgentHostSet[]) => { const noInstalledHosts = selectedRows?.filter((d: any) => !d.agentId); // 筛选出未安装的agent const installedHosts = selectedRows?.filter((d: any) => d.agentId); // 筛选出已安装的agent this.setState({ selectedRowKeys, includedInstalled: noInstalledHosts?.length < selectedRows?.length, // 包含已安装agent noInstalledHosts, includednoInstalled: installedHosts?.length < selectedRows?.length, // 包含已安装agent installedHosts, // 0:安装 1:卸载 2:升级 agentIds: installedHosts.map(ele => ele.agentId), }); }; public onPageChange = (current: number, size: number | undefined) => { const { queryParams } = this.state; const pageParams = { // pageNo: current, // pageSize: size, agentHealthLevelList: queryParams?.agentHealthLevelList || [], agentVersionIdList: queryParams?.agentVersionIdList || [], containerList: queryParams?.containerList || [], hostCreateTimeStart: queryParams?.hostCreateTimeStart, hostCreateTimeEnd: queryParams?.hostCreateTimeEnd, serviceIdList: this.setServiceIdList(), hostName: queryParams?.hostName, ip: queryParams?.ip, } as IAgentHostParams; this.setState({ queryParams: pageParams }); this.getAgentData(pageParams, current, size); } public getAgentData = (queryParams: IAgentHostParams, current?: number, size?: number) => { queryParams.pageNo = current || 1; queryParams.pageSize = size || 20; this.setState({ loading: true }); getAgent(queryParams).then((res: IAgentHostVo) => { const data = res?.resultSet?.map((ele: IAgentHostSet, index: number) => { return { key: index, ...ele } }); this.setState({ loading: false, agentList: data, total: res.total, }); }).catch((err: any) => { this.setState({ loading: false }); }); } public getAgentVersionData = () => { getAgentVersion().then((res: IAgentVersion[]) => { this.setState({ agentVersionList: res }); }).catch((err: any) => { // console.log(err); }); } public getServicesData = () => { getServices().then((res: IService[]) => { const data = res.map((ele, index) => { return { ...ele, key: index, }; }); this.setState({ servicesList: data, }) }).catch((err: any) => { // console.log(err); }); } public componentWillUnmount = () => { this.setState = () => { return }; document.removeEventListener('mousedown', (e) => this.handleClickOutside(e), false); } public componentDidMount() { this.getAgentData(this.state.queryParams); this.getAgentVersionData(); this.getServicesData(); document.addEventListener('mousedown', (e) => this.handleClickOutside(e), false); } public render() { const { loading, total, agentList, selectedRowKeys } = this.state; const { pageNo, pageSize } = this.state.queryParams; const rowSelection = { selectedRowKeys, onChange: this.onSelectChange, }; return ( <> <CustomBreadcrumb btns={agentBreadcrumb} /> <div className="list page-wrapper agent-list"> <CommonHead heads={agentHead} /> <BasicTable rowKey='hostId' showReloadBtn={false} // showQueryCollapseButton={true} loading={loading} reloadBtnPos="left" reloadBtnType="btn" filterType="none" hideContentBorder={true} showSearch={false} columns={this.agentListColumns()} rowSelection={rowSelection} dataSource={agentList} isQuerySearchOnChange={false} queryFormColumns={this.queryFormColumns()} showQueryCollapseButton={this.queryFormColumns().length > 2 ? true : false} pagination={{ current: pageNo, pageSize: pageSize, total, showQuickJumper: true, showSizeChanger: true, pageSizeOptions: ['10', '20', '50', '100', '200', '500'], onChange: (current, size) => this.onPageChange(current, size), onShowSizeChange: (current, size) => this.onPageChange(current, size), showTotal: () => `共 ${total} 条`, }} queryFormProps={{ searchText: '查询', resetText: '重置', onChange: this.onChangeParams, onSearch: this.onSearchParams, onReset: this.onResetParams, }} customHeader={ <div className="table-button"> <p> <Tooltip placement="top" title="更多功能请关注商业版"> <Button disabled onClick={this.handleInstallHost}>安装</Button> </Tooltip> <Tooltip placement="top" title="更多功能请关注商业版"> <Button disabled onClick={this.handleUpgradeHost}>升级</Button> </Tooltip> <Tooltip placement="top" title="更多功能请关注商业版"> <Button disabled onClick={this.handleUninstallHost}>卸载</Button> </Tooltip> </p> <Button type="primary" onClick={this.handleNewHost}>新增主机</Button> </div> } /> </div> </> ); } };
the_stack
import db from "debug"; import * as util from "util"; import * as ld from "lodash"; import * as css from "./css"; import { AdaptComponentElement, AdaptElement, AdaptElementImpl, AdaptElementOrNull, AdaptMountedElement, AnyProps, BuildHelpers, childrenToArray, cloneElement, Component, createElement, FinalDomElement, FunctionComponentTyp, // @ts-ignore - here to deal with issue #71 GenericInstance, isComponentElement, isDeferredElementImpl, isElement, isElementImpl, isFinalDomElement, isMountedElement, isMountedPrimitiveElement, isPartialFinalDomElement, isPrimitiveElement, KeyPath, PartialFinalDomElement, popComponentConstructorData, pushComponentConstructorData, simplifyChildren, WithChildren } from "./jsx"; import { createStateStore, StateNamespace, stateNamespaceForPath, StateStore } from "./state"; import { createObserverManagerDeployment, isObserverNeedsData, ObserverManagerDeployment } from "./observers"; import { isObject, Message, MessageType, notNull, removeUndef } from "@adpt/utils"; import { OmitT, WithPartialT } from "type-ops"; import { DomError, isDomErrorElement } from "./builtin_components"; import { BuildListener, BuildOp, } from "./dom_build_data_recorder"; import { BuildNotImplemented, InternalError, isError, ThrewNonError } from "./error"; import { BuildId, getInternalHandle, Handle } from "./handle"; import { createHookInfo, finishHooks, HookInfo, startHooks } from "./hooks"; import { assignKeysAtPlacement, computeMountKey, ElementKey } from "./keys"; import { DeployOpID } from "./server/deployment_data"; export type DomPath = AdaptElement[]; const debugBuild = db("adapt:dom:build"); const debugState = db("adapt:state"); type CleanupFunc = () => void; class BuildResults { // These reset each build pass mountedOrig: AdaptMountedElement | null; contents: AdaptElementOrNull; cleanups: CleanupFunc[]; mountedElements = new Set<AdaptMountedElement>(); builtElements: AdaptMountedElement[]; stateChanged: boolean; partialBuild: boolean; // These accumulate across build passes buildErr = false; private messages: Message[] = []; constructor( readonly recorder: BuildListener, mountedOrig?: AdaptMountedElement | null, contents?: AdaptElementOrNull, other?: BuildResults) { this.buildPassReset(); if (contents !== undefined) { this.contents = contents; } if (mountedOrig !== undefined) { this.mountedOrig = mountedOrig; } if (other !== undefined) { this.combine(other); } } buildPassReset() { this.mountedOrig = null; this.contents = null; this.cleanups = []; this.mountedElements = new Set(); this.builtElements = []; this.stateChanged = false; this.partialBuild = false; } // Terminology is a little confusing here. Anything that allows the // build to keep progressing should be MessageType.warning. // MessageType.error should only be for catastrophic things where // the build cannot keep running (i.e. an exception that can't be // handled within build). // However, either MessageType.warning or MessageType.error indicates // an unsuccessful build, therefore buildErr = true. /** * Record an error in build data recorder and log a message and mark * the build as errored. * This is the primary interface for most build errors. */ error(err: string | Error, from?: string) { const error = ld.isError(err) ? err : new Error(err); this.recorder({ type: "error", error }); this.message({ type: MessageType.warning, from }, error); } /** * Lower-level message log interface. Does not record to build data * recorder, but does mark build as errored, depending on MessageType. */ message(msg: WithPartialT<Message, "from" | "timestamp">): void; message(msg: WithPartialT<OmitT<Message, "content">, "from" | "timestamp">, err: Error): void; message(msg: WithPartialT<Message, "from" | "timestamp" | "content">, err?: Error): void { const content = err ? err.message : msg.content; if (!content) throw new InternalError(`build message doesn't have content or err`); const copy = { ...msg, content, timestamp: msg.timestamp ? msg.timestamp : Date.now(), from: msg.from ? msg.from : "DOM build", }; this.messages.push(copy); switch (copy.type) { case MessageType.warning: case MessageType.error: this.buildErr = true; this.partialBuild = true; } } combine(other: BuildResults): BuildResults { this.messages.push(...other.messages); this.cleanups.push(...other.cleanups); other.mountedElements.forEach((el) => this.mountedElements.add(el)); this.builtElements.push(...other.builtElements); this.buildErr = this.buildErr || other.buildErr; this.partialBuild = this.partialBuild || other.partialBuild; this.stateChanged = this.stateChanged || other.stateChanged; other.messages = []; other.cleanups = []; other.builtElements = []; other.mountedElements = new Set(); return this; } cleanup() { let clean: CleanupFunc | undefined; do { clean = this.cleanups.pop(); if (clean) clean(); } while (clean); } toBuildOutput(stateStore: StateStore): BuildOutput { if (this.buildErr && this.messages.length === 0) { throw new InternalError(`buildErr is true, but there are ` + `no messages to describe why`); } if (this.partialBuild) { if (this.contents !== null && !isPartialFinalDomElement(this.contents)) { throw new InternalError(`contents is not a mounted element: ${this.contents}`); } return { partialBuild: true, buildErr: this.buildErr, messages: this.messages, contents: this.contents, mountedOrig: this.mountedOrig, }; } if (this.contents !== null && !isFinalDomElement(this.contents)) { throw new InternalError(`contents is not a valid built DOM element: ${this.contents}`); } const builtElements = this.builtElements; return { partialBuild: false, buildErr: false, messages: this.messages, contents: this.contents, mountedOrig: this.mountedOrig, mountedElements: [...this.mountedElements], processStateUpdates: () => processStateUpdates(builtElements, stateStore), }; } } function isClassConstructorError(err: any) { return err instanceof TypeError && typeof err.message === "string" && /Class constructor .* cannot be invoked/.test(err.message); } function recordDomError( cc: BuildResults, element: AdaptElement, err: Error | Message, ): { domError: AdaptElement<{}>, message: string } { let message: string; if (ld.isError(err)) { message = `Component ${element.componentName} cannot be built ` + `with current props` + (err.message ? ": " + err.message : ""); cc.error(message); } else { message = err.content; cc.message(err); } const domError = createElement(DomError, {}, message); const kids = childrenToArray(element.props.children); kids.unshift(domError); replaceChildren(element, kids); return { domError, message }; } export interface BuildHelpersOptions extends BuildId { deployID: string; deployOpID: DeployOpID; observerManager?: ObserverManagerDeployment; } export function makeElementStatus(observerManager?: ObserverManagerDeployment) { return async function elementStatus(handle: Handle) { const elem = handle.mountedOrig; if (elem == null) return { noStatus: true }; if (!isElementImpl(elem)) throw new InternalError("Element is not ElementImpl"); try { return await (observerManager ? elem.statusWithMgr(observerManager) : elem.status()); } catch (e) { if (!isObserverNeedsData(e)) throw e; return undefined; } }; } function buildHelpers(options: BuildHelpersOptions): BuildHelpers { const { buildNum, deployID, deployOpID } = options; const elementStatus = makeElementStatus(options.observerManager); return { buildNum, deployID, deployOpID, elementStatus, }; } async function computeContentsFromElement<P extends object>( element: AdaptMountedElement<P & WithChildren>, options: BuildOptionsInternal): Promise<BuildResults> { const ret = new BuildResults(options.recorder, element); const helpers = buildHelpers(options); try { startHooks({ element, options, helpers }); ret.contents = (element.componentType as FunctionComponentTyp<P>)(element.props); return ret; } catch (e) { if (e instanceof BuildNotImplemented) return buildDone(e); if (!isClassConstructorError(e)) { if (isError(e)) { return buildDone(new Error(`SFC build failed: ${e.message}`)); } throw e; } // element.componentType is a class, not a function. Fall through. } finally { finishHooks(); } if (!isComponentElement(element)) { throw new InternalError(`trying to construct non-component`); } let component: Component; try { component = constructComponent(element, options); } catch (e) { if (e instanceof BuildNotImplemented) return buildDone(e); if (isError(e)) { return buildDone(new Error(`Component construction failed: ${e.message}`)); } throw e; } try { if (!ld.isFunction(component.build)) { throw new BuildNotImplemented(`build is not a function, build = ${util.inspect(component.build)}`); } ret.contents = await component.build(helpers); if (component.cleanup) { ret.cleanups.push(component.cleanup.bind(component)); } return ret; } catch (e) { if (e instanceof BuildNotImplemented) return buildDone(e); if (isError(e)) { return buildDone(new Error(`Component build failed: ${e.message}`)); } throw e; } function buildDone(err?: Error) { ret.contents = element; if (err) recordDomError(ret, element, err); return ret; } } function findOverride(styles: css.StyleList, path: DomPath, options: BuildOptionsInternal) { const element = path[path.length - 1]; const reg = options.matchInfoReg; for (let i = styles.length - 1; i >= 0; i--) { const style = styles[i]; if (css.canMatch(reg, element) && !css.ruleHasMatched(reg, element, style) && style.match(path)) { css.ruleMatches(reg, element, style); return { style, override: style.sfc }; } } return null; } async function computeContents( path: DomPath, options: BuildOptionsInternal): Promise<BuildResults> { const element = ld.last(path); if (element == null) { const ret = new BuildResults(options.recorder); return ret; } if (!isMountedElement(element)) throw new InternalError(`computeContents for umounted element: ${element}`); const hand = getInternalHandle(element); const out = await computeContentsFromElement(element, options); // Default behavior if the component doesn't explicitly call // handle.replaceTarget is to do the replace for them. if (!hand.targetReplaced(options)) hand.replaceTarget(out.contents, options); options.recorder({ type: "step", oldElem: element, newElem: out.contents }); return out; } interface ApplyStyleProps extends BuildId { override: css.BuildOverride<AnyProps>; element: AdaptElement; matchInfoReg: css.MatchInfoReg; } function ApplyStyle(props: ApplyStyleProps) { const origBuild = () => { return props.element; }; const hand = getInternalHandle(props.element); const opts = { buildNum: props.buildNum, origBuild, origElement: props.element, [css.$matchInfoReg]: props.matchInfoReg, }; const ret = props.override(props.element.props, opts); // Default behavior if they don't explicitly call // handle.replaceTarget is to do the replace for them. if (ret !== props.element && !hand.targetReplaced(props)) { hand.replaceTarget(ret, props); } return ret; } //Gross, but we need to provide ApplyStyle to jsx.ts like this to avoid a circular require // tslint:disable-next-line:no-var-requires require("./jsx").ApplyStyle = ApplyStyle; function doOverride( path: DomPath, key: ElementKey, styles: css.StyleList, options: BuildOptionsInternal): AdaptElement { let element = ld.last(path); if (element == null) { throw new Error("Cannot match null element to style rules for empty path"); } const overrideFound = findOverride(styles, path, options); if (overrideFound != null) { const matchInfoReg = options.matchInfoReg; if (isComponentElement(element)) { if (!isMountedElement(element)) throw new InternalError(`Element should be mounted`); if (!isElementImpl(element)) throw new InternalError(`Element should be ElementImpl`); if (element.component == null) { element.component = constructComponent(element, options); } } const hand = getInternalHandle(element); const oldEl = element; element = cloneElement(element, key, element.props.children); css.copyRuleMatches(matchInfoReg, oldEl, element); hand.replaceTarget(element, options); const { style, override } = overrideFound; const props = { ...key, override, element, matchInfoReg, buildNum: options.buildNum, }; const newElem = createElement(ApplyStyle, props); // The ApplyStyle element should never match any CSS rule css.neverMatch(matchInfoReg, newElem); options.recorder({ type: "step", oldElem: element, newElem, style }); return newElem; } else { return element; } } function mountElement( path: DomPath, parentStateNamespace: StateNamespace, options: BuildOptionsInternal): BuildResults { let elem = ld.last(path); if (elem === undefined) { throw new InternalError("Attempt to mount empty path"); } if (elem === null) return new BuildResults(options.recorder, elem, elem); if (isMountedElement(elem)) { throw new Error("Attempt to remount element: " + util.inspect(elem)); } const newKey = computeMountKey(elem, parentStateNamespace); const hand = getInternalHandle(elem); const oldEl = elem; elem = cloneElement(elem, newKey, elem.props.children); css.copyRuleMatches(options.matchInfoReg, oldEl, elem); if (!hand.targetReplaced(options)) hand.replaceTarget(elem, options); if (!isElementImpl(elem)) { throw new Error("Elements must derive from ElementImpl"); } const finalPath = subLastPathElem(path, elem); elem.mount(parentStateNamespace, domPathToString(finalPath), domPathToKeyPath(finalPath), options.deployID, options.deployOpID); if (!isMountedElement(elem)) throw new InternalError(`just mounted element is not mounted ${elem}`); const out = new BuildResults(options.recorder, elem, elem); out.mountedElements.add(elem); return out; } function subLastPathElem(path: DomPath, elem: AdaptElement): DomPath { const ret = path.slice(0, -1); ret.push(elem); return ret; } async function buildElement( path: DomPath, parentStateNamespace: StateNamespace, styles: css.StyleList, options: BuildOptionsInternal): Promise<BuildResults> { const elem = ld.last(path); if (elem === undefined) { throw new InternalError("buildElement called with empty path"); } if (elem === null) return new BuildResults(options.recorder, null, null); if (!isMountedElement(elem)) throw new InternalError(`attempt to build unmounted element ${elem}`); if (!isElementImpl(elem)) throw new Error(`Elements must derive from ElementImpl ${elem}`); const override = doOverride(path, computeMountKey(elem, parentStateNamespace), styles, options); if (override !== elem) { return new BuildResults(options.recorder, elem, override); } if (isPrimitiveElement(elem)) { const res = new BuildResults(options.recorder, elem, elem); try { constructComponent(elem, options); res.builtElements.push(elem); elem.setBuilt(); } catch (err) { if (!isError(err)) throw err; recordDomError(res, elem, new Error(`Component construction failed: ${err.message}`)); } return res; } const out = await computeContents(path, options); if (out.contents != null) { if (Array.isArray(out.contents)) { const name = elem.componentName; throw new Error(`Component build for ${name} returned an ` + `array. Components must return a single root element when ` + `built.`); } } out.builtElements.push(elem); elem.setBuilt(); return out; } function constructComponent<P extends object = {}>( elem: AdaptComponentElement<P>, options: BuildOptionsInternal): Component<P> { const { deployID, deployOpID, observerManager, stateStore } = options; if (!isElementImpl(elem)) { throw new InternalError(`Element is not an ElementImpl`); } pushComponentConstructorData({ deployInfo: { deployID, deployOpID, }, getState: () => stateStore.elementState(elem.stateNamespace), setInitialState: (init) => stateStore.setElementState(elem.stateNamespace, init), stateUpdates: elem.stateUpdates, observerManager }); try { const component = new elem.componentType(elem.props); elem.component = component; return component; } finally { popComponentConstructorData(); } } export interface BuildOptions { depth?: number; shallow?: boolean; recorder?: BuildListener; stateStore?: StateStore; observerManager?: ObserverManagerDeployment; maxBuildPasses?: number; buildOnce?: boolean; deployID?: string; deployOpID?: DeployOpID; } export interface BuildOptionsInternalNoId extends Required<BuildOptions> { buildPass: number; matchInfoReg: css.MatchInfoReg; hookInfo: HookInfo; } export interface BuildOptionsInternal extends BuildOptionsInternalNoId, BuildId {} function computeOptions(optionsIn?: BuildOptions): BuildOptionsInternalNoId { if (optionsIn != null) optionsIn = removeUndef(optionsIn); const defaultBuildOptions = { depth: -1, shallow: false, // Next line shouldn't be needed. VSCode tslint is ok, CLI is not. // tslint:disable-next-line:object-literal-sort-keys recorder: (_op: BuildOp) => { return; }, stateStore: createStateStore(), observerManager: createObserverManagerDeployment(), maxBuildPasses: 200, buildOnce: false, deployID: "<none>", deployOpID: 0, matchInfoReg: css.createMatchInfoReg(), hookInfo: createHookInfo(), }; return { ...defaultBuildOptions, ...optionsIn, buildPass: 0 }; } // Simultaneous builds let buildCount = 0; export interface BuildOutputBase { mountedOrig: AdaptMountedElement | null; messages: Message[]; } export interface BuildOutputPartial extends BuildOutputBase { buildErr: boolean; partialBuild: true; contents: PartialFinalDomElement | null; } export function isBuildOutputPartial(v: any): v is BuildOutputPartial { return ( isObject(v) && v.partialBuild === true && (v.contents === null || isPartialFinalDomElement(v.contents)) ); } export interface BuildOutputError extends BuildOutputPartial { buildErr: true; } export function isBuildOutputError(v: any): v is BuildOutputError { return isBuildOutputPartial(v) && v.buildErr === true; } export type ProcessStateUpdates = () => Promise<{ stateChanged: boolean }>; export const noStateUpdates = () => Promise.resolve({ stateChanged: false }); export interface BuildOutputSuccess extends BuildOutputBase { buildErr: false; mountedElements: AdaptMountedElement[]; partialBuild: false; processStateUpdates: ProcessStateUpdates; contents: FinalDomElement | null; } export function isBuildOutputSuccess(v: any): v is BuildOutputSuccess { return ( isObject(v) && v.partialBuild === false && v.buildErr !== true && (v.contents === null || isFinalDomElement(v.contents)) ); } export type BuildOutput = BuildOutputSuccess | BuildOutputPartial | BuildOutputError; export async function build( root: AdaptElement, styles: AdaptElementOrNull, options?: BuildOptions): Promise<BuildOutput> { const debugBuildBuild = debugBuild.extend("build"); debugBuildBuild(`start`); if (buildCount !== 0) { throw new InternalError(`Attempt to build multiple DOMs concurrently not supported`); } try { buildCount++; const optionsReq = computeOptions(options); const results = new BuildResults(optionsReq.recorder); const styleList = css.buildStyles(styles); if (optionsReq.depth === 0) throw new Error(`build depth cannot be 0: ${options}`); await pathBuild([root], styleList, optionsReq, results); return results.toBuildOutput(optionsReq.stateStore); } finally { debugBuildBuild(`done`); buildCount--; } } export async function buildOnce( root: AdaptElement, styles: AdaptElement | null, options?: BuildOptions): Promise<BuildOutput> { return build(root, styles, { ...options, buildOnce: true }); } function atDepth(options: BuildOptionsInternal, depth: number) { if (options.shallow) return true; if (options.depth === -1) return false; return depth >= options.depth; } async function nextTick(): Promise<void> { await new Promise((res) => { process.nextTick(res); }); } async function pathBuild( path: DomPath, styles: css.StyleList, options: BuildOptionsInternalNoId, results: BuildResults): Promise<void> { options.matchInfoReg = css.createMatchInfoReg(); await pathBuildOnceGuts(path, styles, options, results); if (results.buildErr || options.buildOnce) return; if (results.stateChanged) { await nextTick(); return pathBuild(path, styles, options, results); } } // Unique identifier for a build pass let nextBuildNum = 1; async function pathBuildOnceGuts( path: DomPath, styles: css.StyleList, options: BuildOptionsInternalNoId, results: BuildResults): Promise<void> { const root = path[path.length - 1]; const buildNum = nextBuildNum++; const buildPass = ++options.buildPass; if (buildPass > options.maxBuildPasses) { results.error(`DOM build exceeded maximum number of build iterations ` + `(${options.maxBuildPasses})`); return; } const debug = debugBuild.extend(`pathBuildOnceGuts:${buildPass}`); debug(`start (pass ${buildPass})`); options.recorder({ type: "start", root, buildPass }); results.buildPassReset(); try { const once = await realBuildOnce(path, null, styles, { ...options, buildNum }, null); debug(`build finished`); once.cleanup(); results.combine(once); results.mountedOrig = once.mountedOrig; results.contents = once.contents; } catch (error) { options.recorder({ type: "error", error }); debug(`error: ${error} `); throw error; } if (results.buildErr) return; debug(`validating`); results.builtElements.map((elem) => { if (isMountedPrimitiveElement(elem)) { let msgs: (Message | Error)[]; try { msgs = elem.validate(); } catch (err) { if (!ld.isError(err)) err = new ThrewNonError(err); msgs = [err]; } for (const m of msgs) recordDomError(results, elem, m); } }); if (results.buildErr) return; debug(`postBuild`); options.recorder({ type: "done", root: results.contents }); const { stateChanged } = await processStateUpdates(results.builtElements, options.stateStore); if (stateChanged) results.stateChanged = true; debug(`done (stateChanged=${results.stateChanged})`); } export async function processStateUpdates( builtElements: AdaptElement[], stateStore: StateStore): Promise<{ stateChanged: boolean }> { let stateChanged = false; debugState(`State updates: start`); const updates = builtElements.map(async (elem) => { if (isElementImpl(elem)) { const ret = await elem.postBuild(stateStore); if (ret.stateChanged) stateChanged = true; } }); await Promise.all(updates); debugState(`State updates: complete (stateChanged=${stateChanged})`); return { stateChanged }; } function setOrigChildren(predecessor: AdaptElementImpl<AnyProps>, origChildren: any[]) { predecessor.buildData.origChildren = origChildren; } async function buildChildren( newRoot: AdaptElement, workingPath: DomPath, styles: css.StyleList, options: BuildOptionsInternal): Promise<{ newChildren: any, childBldResults: BuildResults }> { if (!isElementImpl(newRoot)) throw new Error(`Elements must inherit from ElementImpl ${util.inspect(newRoot)}`); const out = new BuildResults(options.recorder); const children = newRoot.props.children; let newChildren: any = null; if (children == null) { return { newChildren: null, childBldResults: out }; } //FIXME(manishv) Make this use an explicit stack //instead of recursion to avoid blowing the call stack //For deep DOMs let childList: any[] = []; if (isElement(children)) { childList = [children]; } else if (ld.isArray(children)) { childList = children; } assignKeysAtPlacement(childList); newChildren = []; const mountedOrigChildren: any[] = []; for (const child of childList) { if (isElementImpl(child)) { if (isMountedElement(child) && child.built()) { newChildren.push(child); //Must be from a deferred build mountedOrigChildren.push(child); continue; } options.recorder({ type: "descend", descendFrom: newRoot, descendTo: child }); const ret = await realBuildOnce( [...workingPath, child], newRoot.stateNamespace, styles, options, null, child); options.recorder({ type: "ascend", ascendTo: newRoot, ascendFrom: child }); ret.cleanup(); // Do lower level cleanups before combining msgs out.combine(ret); newChildren.push(ret.contents); mountedOrigChildren.push(ret.mountedOrig); continue; } else { newChildren.push(child); mountedOrigChildren.push(child); continue; } } setOrigChildren(newRoot, mountedOrigChildren); newChildren = newChildren.filter(notNull); return { newChildren, childBldResults: out }; } export interface BuildData extends BuildId { id: string; deployID: string; deployOpID: DeployOpID; successor?: AdaptMountedElement | null; //Only defined for deferred elements since other elements may never mount their children origChildren?: (AdaptMountedElement | null | unknown)[]; } function setSuccessor(predecessor: AdaptMountedElement | null, succ: AdaptMountedElement | null): void { if (predecessor === null) return; if (!isElementImpl(predecessor)) throw new InternalError(`Element is not ElementImpl: ${predecessor}`); predecessor.buildData.successor = succ; } let realBuildId = 0; async function realBuildOnce( pathIn: DomPath, parentStateNamespace: StateNamespace | null, styles: css.StyleList, options: BuildOptionsInternal, predecessor: AdaptMountedElement | null, workingElem?: AdaptElement): Promise<BuildResults> { const buildId = ++realBuildId; const debug = debugBuild.extend(`realBuildOnce:${buildId}`); debug(`start (id: ${buildId})`); try { let deferring = false; const atDepthFlag = atDepth(options, pathIn.length); if (options.depth === 0) throw new InternalError("build depth 0 not supported"); if (parentStateNamespace == null) { parentStateNamespace = stateNamespaceForPath(pathIn.slice(0, -1)); } const oldElem = ld.last(pathIn); if (oldElem === undefined) throw new InternalError("realBuild called with empty path"); if (oldElem === null) return new BuildResults(options.recorder, null); if (workingElem === undefined) { workingElem = oldElem; } const out = new BuildResults(options.recorder); let mountedElem: AdaptElementOrNull = oldElem; if (isMountedElement(oldElem)) { if (isElementImpl(oldElem) && oldElem.reanimated) { // Reanimated elements get mounted at the time of re-animation, // not during build, but they need to be in the mountedElements // output. out.mountedElements.add(oldElem); } } else { const mountOut = mountElement(pathIn, parentStateNamespace, options); if (mountOut.buildErr) return mountOut; out.contents = mountedElem = mountOut.contents; out.combine(mountOut); } if (!isMountedElement(mountedElem)) throw new InternalError("element not mounted after mount"); out.mountedOrig = mountedElem; setSuccessor(predecessor, mountedElem); if (mountedElem === null) { options.recorder({ type: "elementBuilt", oldElem: workingElem, newElem: out.contents }); return out; } //Element is mounted const mountedPath = subLastPathElem(pathIn, mountedElem); let newRoot: AdaptElementOrNull | undefined; let newPath = mountedPath; if (!isElementImpl(mountedElem)) { throw new Error("Elements must inherit from ElementImpl:" + util.inspect(newRoot)); } if (!isDeferredElementImpl(mountedElem) || mountedElem.shouldBuild()) { const computeOut = await buildElement(mountedPath, parentStateNamespace, styles, options); out.combine(computeOut); out.contents = newRoot = computeOut.contents; if (computeOut.buildErr) return out; if (newRoot !== null) { if (newRoot !== mountedElem) { newPath = subLastPathElem(mountedPath, newRoot); const ret = (await realBuildOnce( newPath, mountedElem.stateNamespace, styles, options, mountedElem, workingElem)).combine(out); ret.mountedOrig = out.mountedOrig; return ret; } else { options.recorder({ type: "elementBuilt", oldElem: workingElem, newElem: newRoot }); return out; } } } else { options.recorder({ type: "defer", elem: mountedElem }); deferring = true; mountedElem.setDeferred(); newRoot = mountedElem; out.contents = newRoot; } if (newRoot === undefined) { out.error(`Root element undefined after build`); out.contents = null; return out; } if (newRoot === null) { setSuccessor(mountedElem, newRoot); options.recorder({ type: "elementBuilt", oldElem: workingElem, newElem: null }); return out; } //Do not process children of DomError nodes in case they result in more DomError children if (!isDomErrorElement(newRoot)) { if (!atDepthFlag) { const { newChildren, childBldResults } = await buildChildren(newRoot, mountedPath, styles, options); out.combine(childBldResults); replaceChildren(newRoot, newChildren); } } else { if (!out.buildErr) { // This could happen if a user instantiates a DomError element. // Treat that as a build error too. out.error("User-created DomError component present in the DOM tree"); } } if (atDepthFlag) out.partialBuild = true; //We are here either because mountedElem was deferred, or because mountedElem === newRoot if (!deferring || atDepthFlag) { options.recorder({ type: "elementBuilt", oldElem: workingElem, newElem: newRoot }); return out; } //FIXME(manishv)? Should this check be if there were no element children instead of just no children? //No built event in this case since we've exited early if (atDepthFlag && newRoot.props.children === undefined) return out; //We must have deferred to get here options.recorder({ type: "buildDeferred", elem: mountedElem }); const deferredRet = (await realBuildOnce( newPath, mountedElem.stateNamespace, styles, options, predecessor, workingElem)).combine(out); deferredRet.mountedOrig = out.mountedOrig; return deferredRet; } catch (err) { debug(`error (id: ${buildId}): ${err}`); throw err; } finally { debug(`done (id: ${buildId})`); } } function replaceChildren(elem: AdaptElement, children: any | any[] | undefined) { children = simplifyChildren(children); if (Object.isFrozen(elem.props)) { const newProps = { ...elem.props }; if (children == null) { delete newProps.children; } else { newProps.children = children; } (elem as any).props = newProps; Object.freeze(elem.props); } else { if (children == null) { delete elem.props.children; } else { elem.props.children = children; } } } export function domPathToString(domPath: DomPath): string { return "/" + domPath.map((el) => el.componentName).join("/"); } function domPathToKeyPath(domPath: DomPath): KeyPath { return domPath.map((el) => { const key = el.props.key; if (typeof key !== "string") { throw new InternalError(`element has no key`); } return key; }); }
the_stack
import 'reflect-metadata'; import * as express from 'express'; import glob = require('glob'); import { Server } from 'http'; import { join } from 'path'; import { ControllerDefinition } from './controller/ControllerDefinition'; import { GiuseppeCorePlugin } from './core/GiuseppeCorePlugin'; import { DefinitionNotRegisteredError, DuplicatePluginError } from './errors'; import { DuplicateRouteError } from './errors/DuplicateRouteError'; import { ControllerDefinitionConstructor, GiuseppePlugin, ParameterDefinitionConstructor, RouteDefinitionConstructor, RouteModificatorConstructor, } from './GiuseppePlugin'; import { GiuseppeRegistrar } from './GiuseppeRegistrar'; import { ReturnTypeHandler } from './ReturnTypeHandler'; import { GiuseppeRoute } from './routes/GiuseppeRoute'; import { ReturnType } from './routes/ReturnType'; import { HttpMethod } from './routes/RouteDefinition'; import { ControllerMetadata } from './utilities/ControllerMetadata'; import { getRandomPort } from './utilities/RandomPort'; /** * Score sort function for route register information. Calculates the sorting score based on segments, url params * and wildcards. * * @param {RouteRegisterInformation} route */ const routeScore = (route: RouteRegisterInformation) => route.segments * 1000 - route.urlParams * 0.001 - route.wildcards; /** * Internal interface for route registering. Convenience objects. * * @export * @interface RouteRegisterInformation */ export interface RouteRegisterInformation { route: GiuseppeRoute; ctrl: Function; instance: object; segments: number; wildcards: number; urlParams: number; } /** * Main entry class for giuseppe. Does contain the necessary methods to get the application running. * Does export the configuration and plugin system. * * @export * @class Giuseppe */ export class Giuseppe { /** * Giuseppes item registrar. Is used to register controllers, routes, parameters and all other things that * giuseppe contains. Can be used even when giuseppe is not instantiated yet. * * @static * @type {GiuseppeRegistrar} * @memberof Giuseppe */ public static readonly registrar: GiuseppeRegistrar = new GiuseppeRegistrar(); /** * The actual server instance of express once the application has started. * * @readonly * @type {(Server | undefined)} * @memberof Giuseppe */ public get server(): Server | undefined { return this._server; } /** * Gets the used port of giuseppe (and the given express app). Returns undefined if the app * is not started yet. * * @readonly * @type {(number | undefined)} * @memberof Giuseppe */ public get port(): number | undefined { return this._port; } /** * The express application behind this instance of giuseppe. Someone might want to change the used express instance * before calling [start()]{@link Giuseppe#start()}. Also, on this propert you can add other things like * compression or body-parser. * * @type {express.Express} * @memberof Giuseppe */ public expressApp: express.Express = express(); /** * The router instance that is used for this instance of giuseppe. Access it to add additional routes or even * switch the whole router. * * @type {express.Router} * @memberof Giuseppe */ public router: express.Router = express.Router(); protected plugins: GiuseppePlugin[] = []; protected routes: { [id: string]: RouteRegisterInformation } = {}; protected _server: Server | undefined; protected _returnTypes: ReturnType<any>[] | null = null; protected _pluginController: ControllerDefinitionConstructor[] | null = null; protected _pluginRoutes: RouteDefinitionConstructor[] | null = null; protected _pluginRouteModificators: RouteModificatorConstructor[] | null = null; protected _pluginParameters: ParameterDefinitionConstructor[] | null = null; private _port: number | undefined; /** * List of registered {@link ReturnType}. * * @readonly * @protected * @type {ReturnType<any>[]} * @memberof Giuseppe */ protected get returnTypes(): ReturnType<any>[] { if (!this._returnTypes) { this._returnTypes = this.plugins .filter(p => !!p.returnTypeHandler) .reduce((all, cur) => all.concat(cur.returnTypeHandler!), [] as ReturnType<any>[]); } return this._returnTypes; } /** * List of registered {@link ControllerDefinitionConstructor}. * * @readonly * @protected * @type {ControllerDefinitionConstructor[]} * @memberof Giuseppe */ protected get pluginController(): ControllerDefinitionConstructor[] { if (!this._pluginController) { this._pluginController = this.plugins .filter(p => !!p.controllerDefinitions) .reduce((all, cur) => all.concat(cur.controllerDefinitions!), [] as ControllerDefinitionConstructor[]); } return this._pluginController; } /** * List of registered {@link RouteDefinitionConstructor}. * * @readonly * @protected * @type {RouteDefinitionConstructor[]} * @memberof Giuseppe */ protected get pluginRoutes(): RouteDefinitionConstructor[] { if (!this._pluginRoutes) { this._pluginRoutes = this.plugins .filter(p => !!p.routeDefinitions) .reduce((all, cur) => all.concat(cur.routeDefinitions!), [] as RouteDefinitionConstructor[]); } return this._pluginRoutes; } /** * List of registered {@link RouteModificatorConstructor}. * * @readonly * @protected * @type {RouteModificatorConstructor[]} * @memberof Giuseppe */ protected get pluginRouteModificators(): RouteModificatorConstructor[] { if (!this._pluginRouteModificators) { this._pluginRouteModificators = this.plugins .filter(p => !!p.routeModificators) .reduce((all, cur) => all.concat(cur.routeModificators!), [] as RouteModificatorConstructor[]); } return this._pluginRouteModificators; } /** * List of registered {@link ParameterDefinitionConstructor}. * * @readonly * @protected * @type {ParameterDefinitionConstructor[]} * @memberof Giuseppe */ protected get pluginParameters(): ParameterDefinitionConstructor[] { if (!this._pluginParameters) { this._pluginParameters = this.plugins .filter(p => !!p.parameterDefinitions) .reduce((all, cur) => all.concat(cur.parameterDefinitions!), [] as ParameterDefinitionConstructor[]); } return this._pluginParameters; } constructor() { this.registerPlugin(new GiuseppeCorePlugin()); } /** * Registers a given plugin into this giuseppe instance. Clears the internal caches when it does so. * Calls the initialize method on a plugin. * * @param {GiuseppePlugin} plugin * @returns {this} * @memberof Giuseppe */ public registerPlugin(plugin: GiuseppePlugin): this { if (this.plugins.find(o => o.name === plugin.name)) { throw new DuplicatePluginError(plugin.name); } this._pluginController = null; this._pluginParameters = null; this._pluginRouteModificators = null; this._pluginRoutes = null; this._returnTypes = null; plugin.initialize(this); this.plugins.push(plugin); return this; } /** * Fires up the express application within giuseppe. Gathers all registered controllers and routes and registers * them on the given [router]{@link Giuseppe#router}. After the router is configured, fires up the express * application with the given parameter. * * @param {number} [port] The port of the web application (express.listen argument). If no port is provided * a random one is used. * @param {string} [baseUrl=''] Base url that is preceeding all urls in the system. * @memberof Giuseppe */ public async start(port?: number, baseUrl: string = ''): Promise<void> { const expressPort = port || await getRandomPort(); const router = this.configureRouter(baseUrl); this.expressApp.use(router); this._server = await this.startup(expressPort); this._port = expressPort; } /** * Closes the server of the application. * * @memberof Giuseppe */ public stop(): Promise<void> { return new Promise(resolve => { if (this._server) { this._server.close(() => { delete this._server; delete this._port; resolve(); }); return; } resolve(); }); } /** * Loads controllers from the actual process directory with a given globbing pattern. The start directory is always * process.cwd(). With globbing, you can exclude, match, find files that should be loaded. * More information here: [glob]{@link https://www.npmjs.com/package/glob#glob-primer}. * * Can be used when you don't want to load all controllers by hand. * * @param {string} globPattern * @returns {Promise<void>} * @memberof Giuseppe * * @example * // load all files in build directory * * const giuseppe = new Giuseppe(); * giuseppe.loadControllers('\* \* /build/ \* \* /*.js'); // <-- without the spaces of course. */ public async loadControllers(globPattern: string): Promise<void> { try { console.info(`Loading controller for the glob pattern "${globPattern}".`); const files = await new Promise<string[]>((resolve, reject) => { glob(globPattern, (err, matches) => { if (err) { reject(err); return; } resolve(matches); }); }); for (const file of files) { console.info(`Loading file '${file}'.`); require(join(process.cwd(), file)); } } catch (e) { console.error(`An error happend during loading of controllers`, { globPattern, err: e, }); } } /** * Configures the actual instance of the express router. Creates the registered routes for the controllers in giuseppe * as the first step. After that, registers each route to the router and returns the router. * * @param {string} [baseUrl=''] Base url, that is preceeding all routes. * @returns {express.Router} The configured router. * @memberof Giuseppe */ public configureRouter(baseUrl: string = ''): express.Router { this.createRoutes(baseUrl); this.registerRoutes(); return this.router; } /** * Ultimatively creates the routes that are registered in the registrar of giuseppe. For each controller there * is the following procedure: * 1. Check if the controller definition is registered as a plugin * 2. Create all routes of the controller (call .createRoutes(baseUrl)) * 3. For each create route: * - Load the routes modificators * - If there are none, add routes to the list and continue * - If there are any, throw the routes at the modificators (can be multiple) * - Add routes to the list * 4. Create {@link RouteRegisterInformation} for each route * * @protected * @param {string} baseUrl * @memberof Giuseppe */ protected createRoutes(baseUrl: string): void { const url = baseUrl.startsWith('/') ? baseUrl.substring(1) : baseUrl; for (const ctrl of Giuseppe.registrar.controller) { this.checkPluginRegistration(ctrl); const meta = new ControllerMetadata(ctrl.ctrlTarget.prototype); const routes = ctrl.createRoutes(url); let ctrlRoutes: GiuseppeRoute[] = []; for (const route of routes) { const mods = meta.modificators(route.name); if (!mods.length) { ctrlRoutes.push(route); continue; } let modifiedRoutes: GiuseppeRoute[] = [route]; for (const mod of mods) { modifiedRoutes = mod.modifyRoute(modifiedRoutes); } ctrlRoutes = ctrlRoutes.concat(modifiedRoutes); } const ctrlInstance = new (ctrl.ctrlTarget as { new(...args: any[]): any; })(); for (const route of ctrlRoutes) { if (this.routes[route.id]) { throw new DuplicateRouteError(route); } this.routes[route.id] = { route, segments: route.url.split('/').length, wildcards: route.url.split('*').length - 1, urlParams: route.url.split('/').filter(s => s.indexOf(':') >= 0).length, ctrl: ctrl.ctrlTarget, instance: ctrlInstance, }; } } } protected registerRoutes(): void { Object.keys(this.routes) .map(k => this.routes[k]) .sort((a, b) => routeScore(b) - routeScore(a)) .forEach(r => (this.router as any)[HttpMethod[r.route.method]]( `/${r.route.url}`, ...r.route.middlewares, this.createRouteWrapper(r), )); } /** * Helper function that creates the wrapping function around a route for express. This wrapping function * ensures the right `this` context, does parse the actual param values and handles errors. * * The resulting function is then passed to the express router. * * @protected * @param {RouteRegisterInformation} routeInfo * @returns {express.RequestHandler} * @memberof Giuseppe */ protected createRouteWrapper(routeInfo: RouteRegisterInformation): express.RequestHandler { const meta = new ControllerMetadata(routeInfo.ctrl.prototype); const params = meta.parameters(routeInfo.route.name); const returnTypeHandler = new ReturnTypeHandler(this.returnTypes); return async (req: express.Request, res: express.Response) => { const paramValues: any[] = []; try { for (const param of params) { paramValues[param.index] = param.getValue(req, res); } let result = routeInfo.route.function.apply(routeInfo.instance, paramValues); if (result instanceof Promise) { result = await result; } if (params.some(p => p.canHandleResponse)) { return; } returnTypeHandler.handleValue(result, res); } catch (e) { meta.errorHandler().handleError(routeInfo.instance, req, res, e); } }; } /** * Check if a given controller, the routes of the controller, the modificators and parameters of the route are * registered within a plugin in giuseppe. If not, throw an exception. * * @protected * @throws {DefinitionNotRegisteredError} * @param {ControllerDefinition} controller * @returns {boolean} * @memberof Giuseppe */ protected checkPluginRegistration(controller: ControllerDefinition): boolean { if (!this.pluginController.some(p => controller instanceof p)) { throw new DefinitionNotRegisteredError(controller.constructor.name); } const meta = new ControllerMetadata(controller.ctrlTarget.prototype); for (const route of meta.routes()) { if (!this.pluginRoutes.some(p => route instanceof p)) { throw new DefinitionNotRegisteredError(route.constructor.name); } for (const mod of meta.modificators(route.name)) { if (!this.pluginRouteModificators.some(p => mod instanceof p)) { throw new DefinitionNotRegisteredError(mod.constructor.name); } } for (const param of meta.parameters(route.name)) { if (!this.pluginParameters.some(p => param instanceof p)) { throw new DefinitionNotRegisteredError(param.constructor.name); } } } return true; } private startup(port: number): Promise<Server> { return new Promise(resolve => { const server = this.expressApp.listen(port, () => { resolve(server); }); }); } }
the_stack
import * as React from 'react'; import * as PropTypes from 'prop-types'; import ReactDropdown from 'react-dropdown-now'; import {connect} from 'react-redux'; import {randomBytes} from 'crypto'; import RenameFileEditor, {RenameFileEditorProps} from './renameFileEditor'; import {FileAPIContext} from '../util/fileUtils'; import { DistanceMode, DistanceRound, jsonToScenarioAndTabletop, ScenarioType, TabletopType } from '../util/scenarioUtils'; import {AnyProperties, DriveMetadata, GridType, TabletopFileAppProperties} from '../util/googleDriveUtils'; import {getAllFilesFromStore, getTabletopIdFromStore, GtoveDispatchProp, ReduxStoreType} from '../redux/mainReducer'; import {updateTabletopAction} from '../redux/tabletopReducer'; import InputField from './inputField'; import {FileIndexReducerType} from '../redux/fileIndexReducer'; import {CommsStyle} from '../util/commsNode'; import InputButton from './inputButton'; import HelpButton from './helpButton'; import PiecesRosterConfiguration from './piecesRosterConfiguration'; import './tabletopEditor.scss'; interface TabletopEditorProps extends RenameFileEditorProps<TabletopFileAppProperties, AnyProperties>, GtoveDispatchProp { files: FileIndexReducerType; tabletopId: string; } interface TabletopEditorState { tabletop: TabletopType | null; } class TabletopEditor extends React.Component<TabletopEditorProps, TabletopEditorState> { static contextTypes = { fileAPI: PropTypes.object }; static defaultGridStrings = { [GridType.NONE]: undefined, [GridType.SQUARE]: 'Squares', [GridType.HEX_VERT]: 'Hexagons (Vertical)', [GridType.HEX_HORZ]: 'Hexagons (Horizontal)' }; static distanceModeStrings = { [DistanceMode.STRAIGHT]: 'along a straight line', [DistanceMode.GRID_DIAGONAL_ONE_ONE]: 'following the grid, diagonals cost one square', [DistanceMode.GRID_DIAGONAL_THREE_EVERY_TWO]: 'following the grid, diagonals cost three squares every two' }; static distanceRoundStrings = { [DistanceRound.ROUND_OFF]: 'rounded off', [DistanceRound.ROUND_UP]: 'rounded up', [DistanceRound.ROUND_DOWN]: 'rounded down', [DistanceRound.ONE_DECIMAL]: 'shown to one decimal place' }; static commsStyleStrings = { [CommsStyle.PeerToPeer]: 'Peer-to-peer', [CommsStyle.MultiCast]: 'Multicast (experimental)' }; context: FileAPIContext; constructor(props: TabletopEditorProps) { super(props); this.onSave = this.onSave.bind(this); this.state = { tabletop: null }; } async componentDidMount() { // Need to load the private tabletop to get gmSecret const metadataId = this.props.metadata.appProperties.gmFile; const combined: ScenarioType & TabletopType = await this.context.fileAPI.getJsonFileContents({id: metadataId}); const [, tabletop] = jsonToScenarioAndTabletop(combined, this.props.files.driveMetadata); if (!tabletop.gmSecret) { // since we weren't loading the private tabletop before, the gmSecret may have been lost with previous editing. tabletop.gmSecret = randomBytes(48).toString('hex'); } this.setState({tabletop}); } async onSave(gmFileMetadata: DriveMetadata): Promise<void> { if (this.state.tabletop && this.props.metadata.id === this.props.tabletopId) { // If current, can just dispatch Redux actions to update the tabletop live. this.props.dispatch(updateTabletopAction(this.state.tabletop)); } else { // Otherwise, merge changes with public and private tabletop files. const combined = await this.context.fileAPI.getJsonFileContents(this.props.metadata); await this.context.fileAPI.saveJsonToFile(this.props.metadata.id, {...combined, ...this.state.tabletop, gmSecret: undefined}); const gmOnly = await this.context.fileAPI.getJsonFileContents(gmFileMetadata); await this.context.fileAPI.saveJsonToFile(gmFileMetadata.id, {...gmOnly, ...this.state.tabletop}); } } renderEnumSelect<E>(enumObject: E, labels: {[key in keyof E]: string | undefined}, field: string, defaultValue: keyof E) { const options = Object.keys(enumObject) .filter((key) => (labels[key])) .map((key) => ({label: labels[key], value: enumObject[key]})); const value = options.find((option) => (option.value === (this.state.tabletop![field] || defaultValue))); return ( <ReactDropdown className='select' options={options} value={value} onChange={(selection) => { this.setState((state) => ({tabletop: {...state.tabletop!, [field]: selection.value}})); }} /> ); } private updateTabletop(update: Partial<TabletopType>) { this.setState({tabletop: {...this.state.tabletop!, ...update}}); } render() { return ( <RenameFileEditor className='tabletopEditor' metadata={this.props.metadata} onClose={this.props.onClose} getSaveMetadata={() => ({})} onSave={this.onSave} > { !this.state.tabletop ? ( <span>Loading...</span> ) : ( <div> <fieldset> <legend>Tabletop grids</legend> <div className='gridDefault'> <label>Default grid on tabletop is</label> {this.renderEnumSelect(GridType, TabletopEditor.defaultGridStrings, 'defaultGrid', GridType.SQUARE)} </div> <div className='gridScaleDiv'> <label>{this.state.tabletop.defaultGrid === GridType.SQUARE ? 'One grid square is' : 'Distance from one hexagon to the next is'}</label> <InputField type='number' initialValue={this.state.tabletop.gridScale || 0} onChange={(value) => { this.updateTabletop({gridScale: Number(value) || undefined}); }} /> <InputField type='text' initialValue={this.state.tabletop.gridUnit || ''} onChange={(value) => { this.updateTabletop({gridUnit: String(value) || undefined}); }} placeholder='Units e.g. foot/feet, meter/meters' /> </div> <div className='gridDiagonalDiv'> <label>Measure distance</label> {this.renderEnumSelect(DistanceMode, TabletopEditor.distanceModeStrings, 'distanceMode', DistanceMode.STRAIGHT)} </div> <div className='gridRoundDiv'> <label>Distances are</label> {this.renderEnumSelect(DistanceRound, TabletopEditor.distanceRoundStrings, 'distanceRound', DistanceRound.ROUND_OFF)} </div> </fieldset> <fieldset> <legend>Permissions</legend> <div className='permissionsDiv'> <label>Restrict who may connect to this tabletop</label> <InputButton type='checkbox' selected={this.state.tabletop.tabletopUserControl !== undefined} onChange={() => { this.updateTabletop({ tabletopUserControl: this.state.tabletop!.tabletopUserControl === undefined ? {whitelist: [], blacklist: []} : undefined }); }}/> </div> { this.state.tabletop && this.state.tabletop.tabletopUserControl === undefined ? null : ( <> <div> Enter email addresses (separated by spaces) or * to control who may connect to this tabletop. <HelpButton> <> <p> A player whose email address appears on the whitelist is allowed to join the tabletop. Anyone with an email address on the blacklist will be automatically rejected. Enter the wildcard character * to match anyone not on the other list... for example, putting * in the blacklist will mean no-one other than the emails in the whitelist can join. </p> <p> If a user connects who doesn't match either list, the GM will be prompted that such-and-such user is attempting to connect, and given options to allow or deny them. The whitelist or blacklist will be updated automatically based on the response. You can use this to more easily populate the whitelist, and then set the blacklist to * to prevent anyone else connecting. </p> </> </HelpButton> </div> <div className='permissionsDiv'> <label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Whitelist:</label> <textarea value={this.state.tabletop.tabletopUserControl!.whitelist.join(' ')} placeholder='Email addresses of players allowed to join' onChange={(evt) => { const tabletopUserControl = this.state.tabletop!.tabletopUserControl!; this.updateTabletop({ tabletopUserControl: { ...tabletopUserControl, whitelist: evt.target.value.split(/,? +/) } }); }} /> </div> <div className='permissionsDiv'> <label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Blacklist:</label> <textarea value={this.state.tabletop.tabletopUserControl!.blacklist.join(' ')} placeholder='Email addresses of people who cannot join' onChange={(evt) => { const tabletopUserControl = this.state.tabletop!.tabletopUserControl!; this.updateTabletop({ tabletopUserControl: { ...tabletopUserControl, blacklist: evt.target.value.split(/,? +/) } }); }} /> </div> </> ) } <div className='permissionsDiv'> <label>Only the GM may ping the map (long-press)</label> <InputButton type='checkbox' selected={this.state.tabletop.gmOnlyPing} onChange={() => { this.setState({tabletop: {...this.state.tabletop!, gmOnlyPing: !this.state.tabletop!.gmOnlyPing}}); }}/> </div> </fieldset> <fieldset> <legend>Communication</legend> <div className='commsStyleDiv'> <label>Client connections</label> {this.renderEnumSelect(CommsStyle, TabletopEditor.commsStyleStrings, 'commsStyle', CommsStyle.PeerToPeer)} </div> </fieldset> <fieldset> <legend>Pieces Roster Columns</legend> <PiecesRosterConfiguration columns={this.state.tabletop.piecesRosterColumns} setColumns={(piecesRosterColumns) => { this.setState({tabletop: {...this.state.tabletop!, piecesRosterColumns}}) }}/> </fieldset> </div> ) } </RenameFileEditor> ); } } function mapStoreToProps(store: ReduxStoreType) { return { tabletopId: getTabletopIdFromStore(store), files: getAllFilesFromStore(store) }; } export default connect(mapStoreToProps)(TabletopEditor);
the_stack
import * as vscode from "vscode"; import * as path from "path"; import { CCppProperties } from "./cCppProperties"; import { ValidatedBuilderBase, IsValid } from "./builderBase"; import type { CCppConfigurationJson, LaunchJson } from "./ntypes"; import { CompileCommands } from "./compileCommands"; import * as console from "../console"; export type WorkspaceSetupVars = { configurationsWorkspace: vscode.WorkspaceFolder | undefined; propertiesWorkspace: vscode.WorkspaceFolder | undefined }; export type WorkspaceKey = string; export type ConfigIndex = string; export const CONFIG_SECTION_C_CPP = "C_Cpp"; export abstract class ProjectCCpp extends ValidatedBuilderBase { private _cCppSettings: Map<WorkspaceKey, vscode.WorkspaceConfiguration | undefined> | undefined; private _cCppProperties: Map<WorkspaceKey, CCppProperties | undefined> | undefined; private _compileCommands: Map<WorkspaceKey, Map<ConfigIndex, CompileCommands>> | undefined; protected constructor() { super(); } protected async cCppPostConstructionSetup(setupVars: Record<WorkspaceKey, WorkspaceSetupVars>): Promise<IsValid> { let isValid = super.basePostConstructionSetup(); if (!isValid) { return false; } const cCppSettings = this.createConfigurations(setupVars); const cCppProperties = await this.createProperties(setupVars); this._cCppSettings = cCppSettings; this._cCppProperties = cCppProperties; return true; } private createConfigurations(setupVars: Record<WorkspaceKey, WorkspaceSetupVars>): Map<WorkspaceKey, vscode.WorkspaceConfiguration | undefined> | undefined { const workspaceConfigurations = new Map<WorkspaceKey, vscode.WorkspaceConfiguration | undefined>(); for (let [key, workspaceSetupVars] of Object.entries(setupVars)) { const workspace = workspaceSetupVars.configurationsWorkspace; if (workspace === undefined) { workspaceConfigurations.set(key, undefined); continue; } const configuration = vscode.workspace.getConfiguration(CONFIG_SECTION_C_CPP, workspace); if (!configuration) { console.error(`Couldn't create ${workspace} workspace settings ${CONFIG_SECTION_C_CPP} configuration;`); return undefined; } workspaceConfigurations.set(key, configuration); } return workspaceConfigurations; } private async createProperties(setupVars: Record<WorkspaceKey, WorkspaceSetupVars>): Promise<Map<WorkspaceKey, CCppProperties | undefined> | undefined> { const workspaceProperties = new Map<WorkspaceKey, CCppProperties | undefined>(); for (let [key, workspaceSetupVars] of Object.entries(setupVars)) { const workspace = workspaceSetupVars.propertiesWorkspace; if (workspace === undefined) { workspaceProperties.set(key, undefined); continue; } const properties = new CCppProperties(workspace); await properties.initialize(); if (!properties.isValid) { return undefined; } workspaceProperties.set(key, properties); } return workspaceProperties; } /** * VSCode workspace configuration settings (non c_cpp_properties.json) * @param key */ public getCCppSettingsConfig(workspaceKey: WorkspaceKey): vscode.WorkspaceConfiguration | undefined { if (this._cCppSettings) { const isKeyValid = this._cCppSettings.has(workspaceKey); if (!isKeyValid) { console.error(`${workspaceKey} in cCppSettings doesn't exits.`); return; } const settings = this._cCppSettings.get(workspaceKey); if (settings) { return settings; } else { console.error(`The ${workspaceKey} CCpp settings wasn't configured to be created at construction setup.`); return; } } else { console.error(`cCppSetting weren't created at construction setup.`); return; } } /** * @param workspaceKey * @returns undefined on error */ protected getCCppProperties(workspaceKey: string): CCppProperties | undefined { if (this._cCppProperties) { const isKeyValid = this._cCppProperties.has(workspaceKey); if (!isKeyValid) { console.error(`${workspaceKey} in cCppProperties doesn't exits.`); return; } const properties = this._cCppProperties.get(workspaceKey); if (properties) { return properties; } else { console.error(`The ${workspaceKey} CCPP properties was configured to not be created at construction setup.`); return; } } else { console.error(`The ${workspaceKey} cCppProperties wasn't enabled at construction setup.`); return; } } /** * Configurations stored in the c_cpp_properties.json * @param workspaceKey * @param index */ public getCCppConfiguration(workspaceKey: WorkspaceKey, index: number): CCppConfigurationJson | undefined { const configurations = this.getCCppProperties(workspaceKey)?.configurations; if (!configurations) { console.log(`No ${workspaceKey} configurations found.`); return undefined; } const configuration = configurations?.[index]; if (!configuration) { console.error(`${workspaceKey} configuration at index ${index} does not exists.`); return undefined; } return configuration; } /** * Configurations stored in the c_cpp_properties.json * @param workspaceKey * @param index */ public getCCppConfigurationsFromWorkspace(workspaceKey: WorkspaceKey): CCppConfigurationJson[] | undefined { const configurations = this.getCCppProperties(workspaceKey)?.configurations; if (!configurations) { console.log(`No ${workspaceKey} configurations found.`); return undefined; } return configurations; } /** * @param workspaceKey defaults to undefined to save all stored c_cpp_properties.json files. */ public saveCCppProperties(workspaceKey: WorkspaceKey | undefined = undefined) { if (!workspaceKey) { const allCCppProperties = this._cCppProperties; if (!allCCppProperties) { return; } for (let [workspaceKey, cCppProperties] of allCCppProperties) { cCppProperties?.writeConfigurationsIfNotEqual(); } return; } const properties = this.getCCppProperties(workspaceKey); if (properties) { properties.writeConfigurationsIfNotEqual(); } } /** * Validated creation * * @param workspaceKey * @param configIndex * * @returns false on error */ public loadCompileCommandsFromConfig(workspaceKey: WorkspaceKey, configIndex: number): boolean { if (!this._compileCommands) { this._compileCommands = new Map<WorkspaceKey, Map<ConfigIndex, CompileCommands>>(); } const cCppProperties = this.getCCppProperties(workspaceKey); if (!cCppProperties) { return false; } const compileCommandsPath = cCppProperties.configurations?.[configIndex].compileCommands; if (!compileCommandsPath) { console.error(`Error getting compile commands path from ${workspaceKey} c_cpp_properties.json at config index ${configIndex}.`); return false; } const compileCommands = new CompileCommands(compileCommandsPath); if (!compileCommands.isValid) { return false; } if (!this._compileCommands.has(workspaceKey)) { this._compileCommands.set(workspaceKey, new Map<ConfigIndex, CompileCommands>()); } const workspaceCompileCommands = this._compileCommands.get(workspaceKey); if (!workspaceCompileCommands) { console.error(`${workspaceKey} Compile Commands wasn't set.`); return false; } workspaceCompileCommands.set(configIndex.toString(), compileCommands); return true; } public getCompileCommandsAtConfigIndex(workspaceKey: WorkspaceKey, configIndex: number): CompileCommands | undefined { return this._compileCommands?.get(workspaceKey)?.get(configIndex.toString()); } /** * Validated creation * * @param workspaceKey * * @returns false on 0 compile commands being loaded */ public loadCompileCommandsFromWorkspace(workspaceKey: WorkspaceKey): boolean { if (!this._compileCommands) { this._compileCommands = new Map<WorkspaceKey, Map<ConfigIndex, CompileCommands>>(); } const cCppProperties = this.getCCppProperties(workspaceKey); if (!cCppProperties) { return false; } if (!cCppProperties.configurations) { return false; } for (const configIndex in cCppProperties.configurations) { const compileCommandsPath = cCppProperties.configurations?.[configIndex].compileCommands; if (!compileCommandsPath) { continue; } const compileCommands = new CompileCommands(compileCommandsPath); if (!compileCommands.isValid) { continue; } if (!this._compileCommands.has(workspaceKey)) { this._compileCommands.set(workspaceKey, new Map<ConfigIndex, CompileCommands>()); } const workspaceCompileCommands = this._compileCommands.get(workspaceKey); if (!workspaceCompileCommands) { console.error(`${workspaceKey} Compile Commands wasn't set.`); continue; } workspaceCompileCommands.set(configIndex.toString(), compileCommands); } if(!this._compileCommands.get(workspaceKey)?.size) { return false; } return true; } public getCompileCommandsFromWorkspace(workspaceKey: WorkspaceKey) : Map<string, CompileCommands> | undefined { return this._compileCommands?.get(workspaceKey); } }
the_stack
import * as slack from 'slack'; import { GradientType, withGradient } from '@getstation/theme'; import ElectronWebview from 'app/common/components/ElectronWebview'; import classNames from 'classnames'; import { clipboard } from 'electron'; // @ts-ignore no declaration file import { fetchFavicon, setFetchFaviconTimeout } from '@getstation/fetch-favicon'; import Maybe from 'graphql/tsutils/Maybe'; // @ts-ignore import * as isBlank from 'is-blank'; // @ts-ignore import * as throttle from 'lodash.throttle'; import * as path from 'path'; import { propEq } from 'ramda'; import { noop, compact } from 'ramda-adjunct'; import * as React from 'react'; import { compose } from 'react-apollo'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; // @ts-ignore no declaration file import { updateUI } from 'redux-ui/transpiled/action-reducer'; import { filter } from 'rxjs/operators'; import { Observable, Subscription } from 'rxjs/Rx'; import { oc } from 'ts-optchain'; import { format as formatUrl } from 'url'; import { injectJS } from '../plugins/helpers'; import { getFavicon, getSizedAndOrderedFavicons } from './uiHelpers'; import { ActionsBus, withActionsBus } from '../store/actionsBus'; import { attachWebcontentsToTab, EXECUTE_WEBVIEW_METHOD, ExecuteWebviewMethodAction, performBasicAuth as performBasicAuthAction, setCrashed, setLoadingError, setNotCrashed, } from '../tab-webcontents/duck'; import { getTabWebcontentsById, getWebcontentsAuthInfo, getWebcontentsAuthState } from '../tab-webcontents/selectors'; import { updateLoadingState, updateTabBadge, updateTabFavicons, updateTabTitle, updateTabURL } from '../tabs/duck'; import { getTabId, getTabLoadingState } from '../tabs/get'; import { StationTabImmutable } from '../tabs/types'; import { RecursiveImmutableMap, StationState } from '../types'; import { isPackaged } from '../utils/env'; import ApplicationContainer from './components/ApplicationContainer'; import { navigateToApplicationTab, setConfigData, uninstallApplication, updateApplicationIcon } from './duck'; import LazyWebview from './LazyWebview'; import { withGetApplicationState } from './queries@local.gql.generated'; import { getApplicationDescription } from './selectors'; import { ApplicationImmutable } from './types'; import { getForeFrontNavigationStateProperty } from './utils'; type WebviewMethod = (webview: ElectronWebview) => void; type WebviewMethods = { [k: string]: WebviewMethod, }; // preload file can only be loaded though file:// URL. // When using webpack-dev-server, we need to force it. declare const __webpack_main_path__: string; const preloadUrl = isPackaged ? './preload.js' : formatUrl({ pathname: path.join(__webpack_main_path__, 'preload.js'), protocol: 'file', slashes: true, }); const toggleDevTools: WebviewMethod = (webview) => { if (webview.isDevToolsOpened()) { webview.closeDevTools(); } else { webview.openDevTools(); } }; const webviewMethods: WebviewMethods = { focus: (webview) => webview.focus(), blur: (webview) => webview.view.blur(), reload: (webview) => webview.isReady() && webview.reload(), 'go-back': (webview) => webview.isReady() && webview.goBack(), 'go-forward': (webview) => webview.isReady() && webview.goForward(), 'toggle-dev-tools': (webview) => webview.isReady() && toggleDevTools(webview), 'copy-url-to-clipboard': (webview) => webview.isReady() && clipboard.write({ bookmark: webview.getTitle(), text: webview.getURL(), }), 'paste-and-match-style': (webview) => webview.isReady() && webview.pasteAndMatchStyle(), }; export interface OwnProps { application: ApplicationImmutable, tab: StationTabImmutable, hidden: boolean, loading: boolean, manifestURL: Maybe<string>, applicationId: string, applicationName: Maybe<string>, applicationIcon: Maybe<string>, themeColor: Maybe<string>, notUseNativeWindowOpen: Maybe<boolean>, appFocus: Maybe<number>, isOnline: Maybe<boolean>, // Improve : move down the chain, only for ApplicationContainer | LazyWebView themeGradient: string, actionsBus: ActionsBus | null, legacyServiceId: Maybe<string>, } export interface StateProps { errorCode?: number, errorDescription?: string, crashed: boolean, // Improve : move down the chain, only for ApplicationContainer email: Maybe<string>, promptBasicAuth: boolean, basicAuthInfo: RecursiveImmutableMap<Electron.AuthInfo>, canGoBack: any, } export interface DispatchProps { onFaviconUpdated: Function, onTitleUpdated: Function, onURLUpdated: Function, onBadgeUpdated: Function, onLoadingStateChanged: Function, onLoadingError: Function, onNotificationClicked: Function, onUpdateApplicationIcon: Function, onWebcontentsAttached: Function, onWebcontentsCrashed: Function, onWebcontentsOk: Function, performBasicAuth: (username: string, password: string) => any, onChooseAccount: Function, onApplicationRemoved: Function, updateResetAppModal: Function, } export interface ComputedProps { askResetApplication: () => void } export type Props = OwnProps & StateProps & DispatchProps & ComputedProps; export type ApplicationImplState = { ready: boolean; }; class ApplicationImpl extends React.PureComponent { static defaultProps = { basicAuthInfo: undefined, errorCode: null, errorDescription: null, email: null, promptBasicAuth: false, }; public props: Props; public state: ApplicationImplState; private webView: ElectronWebview; private busSubscription: Subscription | null = null; constructor(props: Props) { super(props); // throttle tracking Navigate events this.handleDidNavigate = throttle(this.handleDidNavigate, 50, { leading: false }); this.handleDidStartLoading = this.handleDidStartLoading.bind(this); this.handleDidStopLoading = this.handleDidStopLoading.bind(this); this.handleDidFailLoad = this.handleDidFailLoad.bind(this); this.handleDomReady = this.handleDomReady.bind(this); this.setWebviewRef = this.setWebviewRef.bind(this); this.handleTitleUpdated = this.handleTitleUpdated.bind(this); this.handleFaviconUpdated = this.handleFaviconUpdated.bind(this); this.handleWebcontentsCrashed = this.handleWebcontentsCrashed.bind(this); this.handleRemoveApplication = this.handleRemoveApplication.bind(this); this.state = { ready: false, }; } shouldReloadAfterConnectionLoss() { if (!this.props.errorCode) return; // see https://cs.chromium.org/chromium/src/net/base/net_error_list.h return ([-105, -106, -109, -130].includes(this.props.errorCode)); } // tslint:disable-next-line:function-name UNSAFE_componentWillReceiveProps(nextProps: Props) { if (getTabId(nextProps.tab) !== getTabId(this.props.tab)) { this.detachBus(); // bus will be automatically re-attached in the next render } if (nextProps.isOnline && !this.props.isOnline && this.shouldReloadAfterConnectionLoss() ) { this.props.onLoadingError(null, null); if (this.webView && this.webView.isReady()) this.webView.reload(); } } componentDidMount() { this.attachBus(); } componentWillUnmount(): void { this.detachBus(); } attachBus(): void { const { actionsBus } = this.props; if (!actionsBus) return; const tabId = getTabId(this.props.tab); const executeWebviewMethodForTab: Observable<ExecuteWebviewMethodAction> = actionsBus .pipe(filter(propEq('type', EXECUTE_WEBVIEW_METHOD))) .pipe(filter(propEq('tabId', tabId))); this.busSubscription = executeWebviewMethodForTab.subscribe(action => { this.handleExecuteWebviewMethod(action); }); } detachBus() { if (this.busSubscription) { this.busSubscription.unsubscribe(); this.busSubscription = null; } } isWebViewReady() { return this.webView && this.webView.isReady(); } goBack = () => { if (this.isWebViewReady()) this.webView.goBack(); } handleExecuteWebviewMethod(action: ExecuteWebviewMethodAction) { const executeWebviewMethod: WebviewMethod = webviewMethods[action.method] || noop; if (this.webView) { executeWebviewMethod(this.webView); } } handleIPCMessage(e: any) { switch (e.channel) { case 'page-bxmetas-updated': { const metas = e.args[0]; if ('badge' in metas) this.props.onBadgeUpdated(metas.badge); break; } case 'notification-clicked': { this.props.onNotificationClicked(); break; } case 'page-click': { this.handlePageClick(); break; } default: break; } } async handleSlackApiTokenUpdate(apiToken: any) { const res = await slack.team.info({ token: apiToken }); if (!res.team) return; const { icon } = res.team; this.props.onUpdateApplicationIcon(icon.image_34); } handlePageClick() { // ok — <webview/> is not making mouse event (like click) bubble // into the host DOM. // This is apriori a bug coming from Chromium // References: // * https://github.com/electron/electron/issues/6563 // * https://bugs.chromium.org/p/chromium/issues/detail?id=631484 // * https://bugs.chromium.org/p/chromium/issues/detail?id=736623 // So we are doing that manually here so that some UI elements can work. // (example: make react-click-outside and friends to work) if (this.webView && this.webView.view) { this.webView.view.dispatchEvent(new MouseEvent('click', { bubbles: true })); // some libraries are not only hooking into click events but also `mousedown` and `mouseup` this.webView.view.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); this.webView.view.dispatchEvent(new MouseEvent('mouseup', { bubbles: true })); } } handleDidNavigateInPage(e: any) { if (e.isMainFrame) { this.handleDidNavigate(e); } } handleDidNavigate(e: any) { /* * Here it's necessessary to update URL because `loadURLOnTabWebcontents` saga does not handle all the cases * i.e. window.location mutation, etc... */ this.props.onURLUpdated(e.url); } handleDidFailLoad(e: any) { if (!e.isMainFrame) return; // details https://cs.chromium.org/chromium/src/net/base/net_error_list.h const { errorCode, errorDescription } = e; this.props.onLoadingError(errorCode, errorDescription); } handleDidStartLoading() { this.props.onLoadingStateChanged(true); this.props.onLoadingError(null, null); this.props.onWebcontentsOk(); } handleDidStopLoading() { this.props.onLoadingStateChanged(false); } async handleDomReady() { const js = await injectJS(this.props.legacyServiceId); if (js && this.webView && this.webView.view) { this.webView.view.executeJavaScript(js); } this.setState({ ready: true }); } handleRemoveApplication() { const { applicationId } = this.props; this.props.onApplicationRemoved(applicationId); } handleTitleUpdated(e: any) { this.props.onTitleUpdated(e.title); } async handleFaviconUpdated(e: any) { const tabUrl = this.props.tab.get('url'); if (tabUrl) { // get the best quality favicon const favicon = await getFavicon(new URL(tabUrl).origin); const electronFavicons: string[] = e.favicons ?? []; const favicons: string[] = compact([favicon, ...electronFavicons]); // check size for each image const orderedSizedFavicons = await getSizedAndOrderedFavicons(favicons); this.props.onFaviconUpdated(orderedSizedFavicons.map(f => f.url)); } } handleWebcontentsCrashed() { this.props.onWebcontentsCrashed(); } setWebviewRef(wv: ElectronWebview) { this.webView = wv; if (this.webView && this.webView.view) { const webview = this.webView.view; webview.addEventListener('did-attach', () => { const webContents = webview.getWebContents(); webview.addEventListener('did-navigate-in-page', (e: any) => this.handleDidNavigateInPage(e)); webview.addEventListener('did-navigate', (e: any) => this.handleDidNavigate(e)); webview.addEventListener('ipc-message', (e: any) => this.handleIPCMessage(e)); this.props.onWebcontentsAttached(webContents.id); }); } } render() { const { notUseNativeWindowOpen, tab } = this.props; const tabUrl = tab.get('url', ''); const { applicationId, applicationName, applicationIcon, themeColor, manifestURL, askResetApplication, onChooseAccount, crashed, errorCode, errorDescription, canGoBack, themeGradient, email, promptBasicAuth, performBasicAuth, basicAuthInfo, } = this.props; return ( <div> <div className={classNames('l-webview__loader', { 'l-webview__loader-active': getTabLoadingState(tab) })} style={{ backgroundColor: themeColor! }} /> <ApplicationContainer ready={this.state.ready} applicationId={applicationId} applicationName={applicationName} applicationIcon={applicationIcon} manifestURL={manifestURL} askResetApplication={askResetApplication} goBack={this.goBack} onChooseAccount={onChooseAccount} onApplicationRemoved={this.handleRemoveApplication} crashed={crashed} errorCode={errorCode} errorDescription={errorDescription} webView={this.webView} tabUrl={tabUrl} themeGradient={themeGradient} canGoBack={canGoBack} promptBasicAuth={promptBasicAuth} performBasicAuth={performBasicAuth} email={email} authInfoHost={basicAuthInfo && basicAuthInfo.get('host')} authInfoRealm={basicAuthInfo && basicAuthInfo.get('realm')} /> <LazyWebview initialSrc={tabUrl} hidden={this.props.hidden} className="l-webview__content" preload={preloadUrl} allowpopups="true" loading={this.props.loading} webviewRef={this.setWebviewRef} onPageTitleUpdated={this.handleTitleUpdated} onPageFaviconUpdated={this.handleFaviconUpdated} onDidStartLoading={this.handleDidStartLoading} onDidStopLoading={this.handleDidStopLoading} onDidFailLoad={this.handleDidFailLoad} onDomReady={this.handleDomReady} onCrashed={this.handleWebcontentsCrashed} webpreferences={`allowDisplayingInsecureContent,nativeWindowOpen=${notUseNativeWindowOpen ? 'no' : 'yes'}`} /> </div> ); } } const Application = compose( withGetApplicationState({ options: ({ application, tab }: Props) => ({ variables: { applicationId: application.get('applicationId'), tabId: tab.get('tabId'), }, }), props: ({ data }) => { if (!data) return { loading: true }; const { application, stationStatus } = oc(data); const manifestData = application.manifestData; return { manifestURL: application.manifestURL(), applicationId: data.variables.applicationId, applicationName: manifestData.name(), applicationIcon: manifestData.interpretedIconURL(), themeColor: manifestData.theme_color(), notUseNativeWindowOpen: manifestData.bx_not_use_native_window_open_on_host(), isOnline: stationStatus.isOnline(), appFocus: stationStatus.focus(), loading: data.loading, legacyServiceId: manifestData.bx_legacy_service_id(), }; }, }), connect<StateProps, DispatchProps, OwnProps>( (state: StationState, ownProps: OwnProps): StateProps => { const { application, tab } = ownProps; const tabId = getTabId(tab); const tabWebcontents = getTabWebcontentsById(state, tabId); if (tabWebcontents) { return { errorCode: tabWebcontents.get('errorCode'), errorDescription: tabWebcontents.get('errorDescription'), crashed: tabWebcontents.get('crashed'), // ApplicationContainer email: getApplicationDescription(state, application), promptBasicAuth: getWebcontentsAuthState(tabWebcontents), basicAuthInfo: getWebcontentsAuthInfo(tabWebcontents), canGoBack: getForeFrontNavigationStateProperty(state, 'canGoBack'), }; } return { // ApplicationContainer email: getApplicationDescription(state, application), canGoBack: getForeFrontNavigationStateProperty(state, 'canGoBack'), } as StateProps; }, (dispatch: any, ownProps: OwnProps): DispatchProps => { const { applicationId, tab } = ownProps; const tabId = getTabId(tab); return bindActionCreators( { onTitleUpdated: (title) => updateTabTitle(tabId, title), onURLUpdated: (url) => updateTabURL(tabId, url), onBadgeUpdated: (badge) => updateTabBadge(tabId, badge), onFaviconUpdated: (favicons) => updateTabFavicons(tabId, favicons), onLoadingStateChanged: (isLoading) => updateLoadingState(tabId, isLoading), onLoadingError: (errorCode, errorDescription) => setLoadingError(tabId, errorCode, errorDescription), onNotificationClicked: () => navigateToApplicationTab(applicationId, tabId), onUpdateApplicationIcon: (imageURL) => updateApplicationIcon(applicationId, imageURL), onWebcontentsAttached: (webcontentsId) => attachWebcontentsToTab(tabId, webcontentsId, Date.now()), onWebcontentsCrashed: () => setCrashed(tabId), onWebcontentsOk: () => setNotCrashed(tabId), performBasicAuth: (username, password) => performBasicAuthAction(username, password, tabId), onChooseAccount: (identityId) => setConfigData(applicationId, { identityId }), onApplicationRemoved: uninstallApplication, updateResetAppModal: (appFocus) => updateUI('confirmResetApplicationModal', 'isVisible', appFocus), }, dispatch ); }, (stateProps: StateProps, dispatchProps: DispatchProps, ownProps: OwnProps): Props => { const { appFocus } = ownProps; return { ...ownProps, ...stateProps, ...dispatchProps, askResetApplication: () => dispatchProps.updateResetAppModal(appFocus), }; }, ), withActionsBus(), withGradient(GradientType.normal), )(ApplicationImpl); export default Application;
the_stack
import { renderToString } from "./deps.ts"; import { ComponentChildren, h } from "../runtime/deps.ts"; import { DATA_CONTEXT } from "../runtime/hooks.ts"; import { Page, Renderer } from "./types.ts"; import { PageProps } from "../runtime/types.ts"; import { SUSPENSE_CONTEXT } from "../runtime/suspense.ts"; import { HEAD_CONTEXT } from "../runtime/head.ts"; import { REFRESH_JS_URL } from "./constants.ts"; import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts"; import { ContentSecurityPolicy } from "../runtime/csp.ts"; export interface RenderOptions { page: Page; imports: string[]; preloads: string[]; url: URL; params: Record<string, string | string[]>; renderer: Renderer; } export type RenderFn = () => void; export class RenderContext { #id: string; #state: Map<string, unknown> = new Map(); #styles: string[] = []; #url: URL; #route: string; #lang = "en"; constructor(id: string, url: URL, route: string) { this.#id = id; this.#url = url; this.#route = route; } /** A unique ID for this logical JIT render. */ get id(): string { return this.#id; } /** * State that is persisted between multiple renders with the same render * context. This is useful because one logical JIT render could have multiple * preact render passes due to suspense. */ get state(): Map<string, unknown> { return this.#state; } /** * All of the CSS style rules that should be inlined into the document. * Adding to this list across multiple renders is supported (even across * suspense!). The CSS rules will always be inserted on the client in the * order specified here. */ get styles(): string[] { return this.#styles; } /** The URL of the page being rendered. */ get url(): URL { return this.#url; } /** The route matcher (e.g. /blog/:id) that the request matched for this page * to be rendered. */ get route(): string { return this.#route; } /** The language of the page being rendered. Defaults to "en". */ get lang(): string { return this.#lang; } set lang(lang: string) { this.#lang = lang; } } const MAX_SUSPENSE_DEPTH = 10; function defaultCsp() { return { directives: { defaultSrc: [NONE], styleSrc: [UNSAFE_INLINE] }, reportOnly: false, }; } /** * This function renders out a page. Rendering is asynchronous, and streaming. * Rendering happens in multiple steps, because of the need to handle suspense. * * 1. The page's vnode tree is constructed. * 2. The page's vnode tree is passed to the renderer. * - If the rendering throws a promise, the promise is awaited before * continuing. This allows the renderer to handle async hooks. * - Once the rendering throws no more promises, the initial render is * complete and a body string is returned. * - During rendering, every time a `<Suspense>` is rendered, it, and it's * attached children are recorded for later rendering. * 3. Once the inital render is complete, the body string is fitted into the * HTML wrapper template. * 4. The full inital render in the template is yielded to be sent to the * client. * 5. Now the suspended vnodes are rendered. These are individually rendered * like described in step 2 above. Once each node is done rendering, it * wrapped in some boilderplate HTML, and suffixed with some JS, and then * sent to the client. On the client the HTML will be slotted into the DOM * at the location of the original `<Suspense>` node. */ export async function* render( opts: RenderOptions, ): AsyncIterable<string | [string, ContentSecurityPolicy | undefined]> { const props = { params: opts.params, url: opts.url, route: opts.page.route }; const csp: ContentSecurityPolicy | undefined = opts.page.csp ? defaultCsp() : undefined; const dataCache = new Map(); const suspenseQueue: ComponentChildren[] = []; const headComponents: ComponentChildren[] = []; const vnode = h(CSP_CONTEXT.Provider, { value: csp, children: h(HEAD_CONTEXT.Provider, { value: headComponents, children: h(DATA_CONTEXT.Provider, { value: dataCache, children: h(SUSPENSE_CONTEXT.Provider, { value: suspenseQueue, children: h(opts.page.component!, props), }), }), }), }); const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route); let suspended = 0; const renderWithRenderer = (): string | Promise<string> => { if (csp) { // Clear the csp const newCsp = defaultCsp(); csp.directives = newCsp.directives; csp.reportOnly = newCsp.reportOnly; } // Clear the suspense queue suspenseQueue.splice(0, suspenseQueue.length); // Clear the head components headComponents.splice(0, headComponents.length); if (++suspended > MAX_SUSPENSE_DEPTH) { throw new Error( `Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`, ); } let body: string | null = null; let promise: Promise<unknown> | null = null; function render() { try { body = renderToString(vnode); } catch (e) { if (e && e.then) { promise = e; return; } throw e; } } opts.renderer.render(ctx, render); if (body !== null) { return body; } else if (promise !== null) { return (promise as Promise<unknown>).then(renderWithRenderer); } else { throw new Error("`render` function not called by renderer."); } }; const bodyHtml = await renderWithRenderer(); let templateProps: { props: PageProps; data?: [string, unknown][]; } | undefined = { props, data: [...dataCache.entries()] }; if (templateProps.data!.length === 0) { delete templateProps.data; } // If this is a static render (runtimeJS is false), then we don't need to // render the props into the template. if ( opts.imports.length === 0 || (opts.imports.length === 1 && opts.imports[0] === REFRESH_JS_URL) ) { templateProps = undefined; } const imports = opts.imports.map((url) => { const randomNonce = crypto.randomUUID().replace(/-/g, ""); if (csp) { csp.directives.scriptSrc = [ ...csp.directives.scriptSrc ?? [], nonce(randomNonce), ]; } return [url, randomNonce] as const; }); const html = template({ bodyHtml, headComponents, imports, preloads: opts.preloads, styles: ctx.styles, props: templateProps, lang: ctx.lang, }); const suspenseNonces = suspenseQueue.map(() => { const randomNonce = crypto.randomUUID().replace(/-/g, ""); if (csp) { csp.directives.scriptSrc = [ ...csp.directives.scriptSrc ?? [], nonce(randomNonce), ]; } return randomNonce; }); let suspenseScript = ""; if (suspenseQueue.length > 0) { const randomNonce = crypto.randomUUID().replace(/-/g, ""); if (csp) { csp.directives.scriptSrc = [ ...csp.directives.scriptSrc ?? [], nonce(randomNonce), ]; } // minified client-side JS suspenseScript = '<script nonce="' + randomNonce + '">(()=>{window.$SR=t=>{const e=document.getElementById("S:"+t),o=document.getElementById("E:"+t),d=document.getElementById("R:"+t);for(d.parentNode.removeChild(d);e.nextSibling!==o;)e.parentNode.removeChild(e.nextSibling);for(;d.firstChild;)e.parentNode.insertBefore(d.firstChild,o);e.parentNode.removeChild(e),o.parentNode.removeChild(o)};const n=document.getElementById("__FRSH_STYLE"),r=n.childNodes[0]?.textContent.split(`\n`);if(r!==void 0){n.removeChild(n.firstChild);for(const t of r)n.append(document.createTextNode(t))}window.$ST=t=>{for(const[e,o]of t)n.insertBefore(document.createTextNode(e),n.childNodes[o])}})();\n</script>'; } let clientStyles = [...ctx.styles]; yield [html + suspenseScript, csp]; // TODO(lucacasonato): parallelize this for (const [id, children] of suspenseQueue.entries()) { let [fragment, script] = await suspenseRender( opts.renderer, ctx, id + 1, children, ); const cssInserts: [string, number][] = []; for (const [i, style] of ctx.styles.entries()) { if (!clientStyles.includes(style)) { cssInserts.push([style, i]); } } clientStyles = [...ctx.styles]; if (cssInserts.length > 0) { script = `$ST(${JSON.stringify(cssInserts)});\n${script};`; } yield `${fragment}<script nonce="${suspenseNonces[id]}">${script}</script>`; } } export async function suspenseRender( renderer: Renderer, ctx: RenderContext, id: number, children: ComponentChildren, ): Promise<[string, string]> { const dataCache = new Map(); const vnode = h(DATA_CONTEXT.Provider, { value: dataCache, children, }); let suspended = 0; const renderWithRenderer = (): string | Promise<string> => { if (++suspended > MAX_SUSPENSE_DEPTH) { throw new Error( `Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`, ); } let body: string | null = null; let promise: Promise<unknown> | null = null; function render() { try { body = renderToString(vnode); } catch (e) { if (e && e.then) { promise = e; return; } throw e; } } renderer.render(ctx, render); if (body !== null) { return body; } else if (promise !== null) { return (promise as Promise<unknown>).then(renderWithRenderer); } else { throw new Error("`render` function not called by renderer."); } }; const html = await renderWithRenderer(); return [`<div hidden id="R:${id}">${html}</div>`, `$SR(${id});`]; } export interface TemplateOptions { bodyHtml: string; headComponents: ComponentChildren[]; imports: (readonly [string, string])[]; styles: string[]; preloads: string[]; props: unknown; lang: string; } export function template(opts: TemplateOptions): string { const page = ( <html lang={opts.lang}> <head> <meta charSet="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {opts.preloads.map((src) => <link rel="modulepreload" href={src} />)} {opts.imports.map(([src, nonce]) => ( <script src={src} nonce={nonce} type="module"></script> ))} <style id="__FRSH_STYLE" dangerouslySetInnerHTML={{ __html: opts.styles.join("\n") }} /> {opts.headComponents} </head> <body> <div dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} id="__FRSH" /> {opts.props !== undefined ? ( <script id="__FRSH_PROPS" type="application/json" dangerouslySetInnerHTML={{ __html: JSON.stringify(opts.props) }} /> ) : null} </body> </html> ); return "<!DOCTYPE html>" + renderToString(page); }
the_stack
'use strict'; const async = require('async'); const { debug, info, warn, error } = require('portal-env').Logger('kong-adapter:portal'); import * as utils from './utils'; import * as wicked from 'wicked-sdk'; import { Callback, WickedApplication, WickedAuthServer, WickedError, KongPluginRequestTransformer, KongPluginCors, WickedApiPlanCollection, WickedApiPlan, WickedApiCollection, WickedApi, KongApiConfig, KongPluginRateLimiting, WickedSessionStoreType, WickedApiSettings, KongPlugin } from 'wicked-sdk'; import { ConsumerInfo, ApplicationData, ApiDescriptionCollection, ApiDescription } from './types'; const MAX_PARALLEL_CALLS = 10; const REFRESH_API_INTERVAL = 3 * 60 * 1000; // 3 minutes // ======== INTERFACE FUNCTIONS ======= export const portal = { getPortalApis: function (callback: Callback<ApiDescriptionCollection>) { debug('getPortalApis()'); async.parallel({ getApis: callback => getActualApis(callback), getAuthServers: callback => getAuthServerApis(callback) }, function (err, results) { if (err) return callback(err); const apiList = utils.clone(results.getApis) as WickedApiCollection; const authServerList = utils.clone(results.getAuthServers) as WickedAuthServer[]; let portalHost = wicked.getInternalPortalUrl(); if (!portalHost) { debug('portalUrl is not set in globals.json, defaulting to http://portal:3000'); portalHost = 'http://portal:3000'; // Default } // Add the Swagger UI "API" for tunneling const swaggerApi = require('../../resources/swagger-ui.json'); swaggerApi.config.api.upstream_url = portalHost + 'swagger-ui'; checkApiConfig(swaggerApi.config); apiList.apis.push(swaggerApi); // And a Ping end point for monitoring const pingApi = require('../../resources/ping-api.json'); pingApi.config.api.upstream_url = portalHost + 'ping'; checkApiConfig(pingApi.config); apiList.apis.push(pingApi); // And the auth Servers please for (let i = 0; i < authServerList.length; ++i) { // TODO: This is not nice. The property "desc" is not present in authServerList, and thus // it cannot be directly used as an ApiDescription object. But on the other hand, it contains // everything else which we need (a KongApiConfig object) apiList.apis.push(authServerList[i] as any as ApiDescription); } debug('getPortalApis():'); debug(apiList); try { injectAuthPlugins(apiList); } catch (injectErr) { return callback(injectErr); } return callback(null, apiList); }); }, /** * This is what we want from the portal: * * [ * { * "consumer": { * "username": "my-app$petstore", * "custom_id": "3476ghow89e746goihw576iger5how4576" * }, * "plugins": { * "key-auth": [ * { "key": "flkdfjlkdjflkdjflkdfldf" } * ], * "acls": [ * { "group": "petstore" } * ], * "oauth2": [ * { * "name": "My Application", * "client_id": "my-app-petstore", * "client_secret": "uwortiu4eot8g7he59t87je59thoerizuoh", * "redirect_uri": ["http://dummy.org"] * } * ] * }, * "apiPlugins": [ * { * "name": "rate-limiting", * "config": { * "hour": 100, * "fault_tolerant": true * } * } * ] * } * ] * * One app can have multiple consumers (one per subscription). */ getAppConsumers: function (appId, callback: Callback<ConsumerInfo[]>) { debug('getPortalConsumersForApp() ' + appId); const applicationList = [{ id: appId, ownerList: [], name: appId }]; let apiPlans: WickedApiPlanCollection = null; let apiList: ApiDescriptionCollection = null; async.series({ plans: callback => utils.getPlans(function (err, apiPlans_: WickedApiPlanCollection) { if (err) return callback(err); apiPlans = apiPlans_; return callback(null); }), apis: callback => getActualApis(function (err, apiList_: ApiDescriptionCollection) { if (err) return callback(err); apiList = apiList_; return callback(null); }), appConsumers: callback => enrichApplications(applicationList, apiPlans, apiList, callback) // (apiPlans, callback) => enrichApplications(applicationList, apiPlans, callback) }, function (err, results) { if (err) return callback(err); callback(null, results.appConsumers); }); }, getAllPortalConsumers: function (callback: Callback<ConsumerInfo[]>) { debug('getAllPortalConsumers()'); return getAllAppConsumers(callback); }, }; // INTERNAL FUNCTIONS/HELPERS let _actualApis: ApiDescriptionCollection = null; let _actualApisDate = 0; function getActualApis(callback: Callback<ApiDescriptionCollection>) { debug('getActualApis()'); const now = (new Date()).getTime(); if (now - _actualApisDate < REFRESH_API_INTERVAL) { if (_actualApis) return callback(null, _actualApis); } wicked.getApis(function (err, apiList) { if (err) return callback(err); // Get the group list from wicked const groups = utils.getGroups().groups; // HACK_SCOPES: Make the scope lists Kong compatible (wicked has more info than Kong) for (let i = 0; i < apiList.apis.length; ++i) { // HACK_SCOPES: This cast is needed to allow changing the scopes to a simple string array (instead of the structure wicked uses). const api = apiList.apis[i] as any; if (api.auth === 'oauth2' && api.settings) { if (api.settings.scopes) { const newScopes = []; for (let scope in api.settings.scopes) { // Take only the keys. newScopes.push(scope); } api.settings.scopes = newScopes; } else { api.settings.scopes = []; } // Now also add the groups as scopes. for (let g = 0; g < groups.length; ++g) { api.settings.scopes.push(`wicked:${groups[g].id}`); } // HACK_PASSTHROUGH_REFRESH: For APIs with passthrough scopes and passthrough users, // refresh tokens are created via the "password" grant; this means we must allow it in Kong as well. { const _api = api as WickedApi; if (_api.passthroughUsers && _api.passthroughScopeUrl) { _api.settings.enable_password_grant = true; } } } } // Enrich apiList with the configuration. async.eachLimit(apiList.apis, MAX_PARALLEL_CALLS, function (apiDef: ApiDescription, callback) { wicked.getApiConfig(apiDef.id, function (err, apiConfig: KongApiConfig) { if (err) return callback(err); apiDef.config = checkApiConfig(apiConfig); return callback(null); }); }, function (err) { if (err) return callback(err); _actualApis = apiList; _actualApisDate = now; return callback(null, apiList); }); }); } function getAuthServerApis(callback: Callback<WickedAuthServer[]>) { debug('getAuthServerApis()'); wicked.getAuthServerNames(function (err, authServerNames) { if (err) return callback(err); async.mapLimit(authServerNames, MAX_PARALLEL_CALLS, function (authServerName, callback) { wicked.getAuthServer(authServerName, callback); }, function (err, authServers: WickedAuthServer[]) { if (err) return callback(err); debug(JSON.stringify(authServers, null, 2)); // Fix auth server and API auth server IDs; also adapt // the upstream_url (canonicalize it). for (let i = 0; i < authServers.length; ++i) { const as = authServers[i] as WickedAuthServer; const id = `${authServerNames[i]}-auth`; as.id = id; if (as.config.api.hasOwnProperty('id')) delete as.config.api.id; as.config.api.name = id; try { const url = new URL(as.config.api.upstream_url); as.config.api.upstream_url = url.toString(); } catch (err) { const msg = `getAuthServerApis(): upstream_url for auth server ${authServerNames[i]} is not a valid URL: ${as.config.api.upstream_url}`; return callback(new WickedError(msg, 500)); } checkApiConfig(as.config); } callback(null, authServers); }); }); } function checkApiConfig(apiConfig: KongApiConfig): KongApiConfig { debug('checkApiConfig()'); if (apiConfig.plugins) { checkApiPlugins(apiConfig, apiConfig.plugins); checkCorsAndRateLimitingPlugins(apiConfig.api.name, apiConfig.plugins); } return apiConfig; } // Checks plugins which can only be applied on API level function checkApiPlugins(apiConfig: KongApiConfig, plugins: KongPlugin[]): void { for (let i = 0; i < plugins.length; ++i) { const plugin = plugins[i]; switch (plugin.name.toLowerCase()) { case "request-transformer": checkRequestTransformerPlugin(apiConfig, plugin as KongPluginRequestTransformer); break; } } } // Checks plugins which can be applied both on API and Plan level function checkCorsAndRateLimitingPlugins(apiName: string, plugins: KongPlugin[]): void { for (let i = 0; i < plugins.length; ++i) { const plugin = plugins[i]; switch (plugin.name.toLowerCase()) { case "cors": checkCorsPlugin(plugin as KongPluginCors); break; case "rate-limiting": case "response-ratelimiting": checkRateLimitingPlugin(apiName, plugin as KongPluginRateLimiting); break; } } } function checkRequestTransformerPlugin(apiConfig: KongApiConfig, plugin: KongPluginRequestTransformer): void { debug('checkRequestTransformerPlugin()'); if (plugin.config && plugin.config.add && plugin.config.add.headers) { for (let i = 0; i < plugin.config.add.headers.length; ++i) { if (plugin.config.add.headers[i] == '%%Forwarded') { const prefix = apiConfig.api.uris; const proto = wicked.getSchema(); const rawHost = wicked.getExternalApiHost(); let host; let port; if (rawHost.indexOf(':') > 0) { const splitList = rawHost.split(':'); host = splitList[0]; port = splitList[1]; } else { host = rawHost; port = (proto == 'https') ? 443 : 80; } plugin.config.add.headers[i] = 'Forwarded: host=' + host + ';port=' + port + ';proto=' + proto + ';prefix=' + prefix; } } } } function checkCorsPlugin(plugin: KongPluginCors): void { debug('checkCorsPlugin()'); if (plugin.config && plugin.config.origins) { if (typeof (plugin.config.origins) === 'string') { warn(`Detected faulty type of CORS config.origins property, converting to array.`); plugin.config.origins = [plugin.config.origins]; } if (typeof (plugin.config.methods) === 'string') { debug(`checkCorsPlugin: Converting "methods" to string array`); plugin.config.methods = plugin.config.methods.split(','); } } } function checkRateLimitingPlugin(apiName: string, plugin: KongPluginRateLimiting): void { const glob = wicked.getGlobals(); if (!glob.sessionStore) return; if (glob.sessionStore.type !== WickedSessionStoreType.Redis) return; // We have a redis, let's use that for storing rate limiting information if (!plugin.config) { warn(`checkRateLimitingPlugin: Empty configuration for rate-limiting for API ${apiName}`); return; } if (plugin.config.redis_database) { info(`checkRateLimitingPlugin: Configuration for rate-limiting for API ${apiName} already contains a redis_database, not using wicked redis.`); return; } if (plugin.config.policy && plugin.config.policy !== 'redis') { warn(`checkRateLimitingPlugin: Configuration for rate-limiting for API ${apiName} explicitly contains a config.policy "${plugin.config.policy}", not using redis.`); return; } if (glob.sessionStore.host) { info(`checkRateLimitingPlugin: Applying redis caching for rate-limiting for API ${apiName}`); plugin.config.policy = 'redis'; plugin.config.redis_host = glob.sessionStore.host; if (glob.sessionStore.port) plugin.config.redis_port = Number(glob.sessionStore.port); if (glob.sessionStore.password) plugin.config.redis_password = glob.sessionStore.password; if (!plugin.config.redis_timeout) plugin.config.redis_timeout = 2000; // ms } } function getAllAppConsumers(callback: Callback<ConsumerInfo[]>): void { debug('getAllAppConsumers()'); async.parallel({ apiPlans: callback => utils.getPlans(callback), apiList: callback => getActualApis(callback), applicationList: callback => wicked.getApplications({}, callback) }, function (err, results) { if (err) return callback(err); const applicationList = results.applicationList.items as WickedApplication[]; const apiPlans = results.apiPlans as WickedApiPlanCollection; const apiList = results.apiList as ApiDescriptionCollection; enrichApplications(applicationList, apiPlans, apiList, callback); }); } // Returns // { // application: { id: ,... } // subscriptions: [ ... ] // } function getApplicationData(appId: string, callback: Callback<ApplicationData>): void { debug('getApplicationData() ' + appId); async.parallel({ subscriptions: callback => wicked.getSubscriptions(appId, function (err, subsList) { if (err && err.status == 404) { // Race condition; web hook processing was not finished until the application // was deleted again (can normally just happen when doing automatic testing). error('*** Get Subscriptions: Application with ID ' + appId + ' was not found.'); return callback(null, []); // Treat as empty } else if (err) { return callback(err); } return callback(null, subsList); }), application: callback => wicked.getApplication(appId, function (err, appInfo) { if (err && err.status == 404) { // See above. error('*** Get Application: Application with ID ' + appId + ' was not found.'); return callback(null, null); } else if (err) { return callback(err); } return callback(null, appInfo); }) }, function (err, results) { if (err) return callback(err); callback(null, results); }); } function enrichApplications(applicationList: WickedApplication[], apiPlans: WickedApiPlanCollection, apiList: ApiDescriptionCollection, callback: Callback<ConsumerInfo[]>) { debug('enrichApplications(), applicationList = ' + utils.getText(applicationList)); async.mapLimit(applicationList, MAX_PARALLEL_CALLS, function (appInfo, callback) { getApplicationData(appInfo.id, callback); }, function (err, results) { if (err) return callback(err); const consumerList = []; for (let resultIndex = 0; resultIndex < results.length; ++resultIndex) { const appInfo = results[resultIndex].application; const appSubsInfo = results[resultIndex].subscriptions; for (let subsIndex = 0; subsIndex < appSubsInfo.length; ++subsIndex) { const appSubs = appSubsInfo[subsIndex]; // Only propagate approved subscriptions if (!appSubs.approved) continue; let groupName = appSubs.api; // Check if this API is part of a bundle const apiDesc = apiList.apis.find(a => a.id === appSubs.api); if (apiDesc) { // API_BUNDLE: Use bundle as group name; this will mean that access tokens/API Keys for this API // will also work for any other API which is part of this bundle. if (apiDesc.bundle) groupName = apiDesc.bundle; } else { warn(`enrichApplications: Could not find API configuration for API ${appSubs.api}`); } debug(utils.getText(appSubs)); const consumerInfo: ConsumerInfo = { consumer: { username: utils.makeUserName(appSubs.application, appSubs.api), custom_id: appSubs.id }, plugins: { acls: [{ group: groupName }] } }; if ("oauth2" == appSubs.auth) { let redirectUris = appInfo.redirectUris; if (!redirectUris || redirectUris.length == 0) redirectUris = ['https://dummy.org']; consumerInfo.plugins.oauth2 = [{ name: appSubs.application, client_id: appSubs.clientId, client_secret: appSubs.clientSecret, redirect_uri: redirectUris }]; } else if (!appSubs.auth || "key-auth" == appSubs.auth) { consumerInfo.plugins["key-auth"] = [{ key: appSubs.apikey }]; } else { let err2 = new Error('Unknown auth strategy: ' + appSubs.auth + ', for application "' + appSubs.application + '", API "' + appSubs.api + '".'); return callback(err2); } // Now the API level plugins from the Plan const apiPlan = getPlanById(apiPlans, appSubs.plan); if (!apiPlan) { const err = new Error('Unknown API plan strategy: ' + appSubs.plan + ', for application "' + appSubs.application + '", API "' + appSubs.api + '".'); return callback(err); } if (apiPlan.config && apiPlan.config.plugins) { consumerInfo.apiPlugins = utils.clone(apiPlan.config.plugins); } else { consumerInfo.apiPlugins = []; } // Fix #148: Apply Redis also for ratelimiting from Plans checkCorsAndRateLimitingPlugins(apiDesc.name, consumerInfo.apiPlugins); consumerList.push(consumerInfo); } } debug(utils.getText(consumerList)); return callback(null, consumerList); }); } function getPlanById(apiPlans: WickedApiPlanCollection, planId: string): WickedApiPlan { debug('getPlanById(' + planId + ')'); return apiPlans.plans.find(function (plan) { return (plan.id == planId); }); } // ======== INTERNAL FUNCTIONS ======= function injectAuthPlugins(apiList: ApiDescriptionCollection) { debug('injectAuthPlugins()'); for (let i = 0; i < apiList.apis.length; ++i) { const thisApi = apiList.apis[i]; if (!thisApi.auth || "none" == thisApi.auth) continue; if ("key-auth" == thisApi.auth) injectKeyAuth(thisApi); else if ("oauth2" == thisApi.auth) injectOAuth2Auth(thisApi); else throw new Error("Unknown 'auth' setting: " + thisApi.auth); } } function injectKeyAuth(api: ApiDescription): ApiDescription { debug('injectKeyAuth()'); if (!api.config.plugins) api.config.plugins = []; const plugins = api.config.plugins; const keyAuthPlugin = plugins.find(function (plugin) { return plugin.name == "key-auth"; }); if (keyAuthPlugin) throw new Error("If you use 'key-auth' in the apis.json, you must not provide a 'key-auth' plugin yourself. Remove it and retry."); const aclPlugin = plugins.find(function (plugin) { return plugin.name == 'acl'; }); if (aclPlugin) throw new Error("If you use 'key-auth' in the apis.json, you must not provide a 'acl' plugin yourself. Remove it and retry."); let hide_credentials = false; if (api.config.api.hide_credentials) hide_credentials = api.config.api.hide_credentials; plugins.push({ name: 'key-auth', enabled: true, config: { hide_credentials: hide_credentials, key_names: [wicked.getApiKeyHeader()] } }); // API_BUNDLE: Is this API part of a bundle? If so, use the bundle name as the group name let groupName = api.bundle ? api.bundle : api.id; debug(`injectKeyAuth: Using ACL group name ${groupName}`); plugins.push({ name: 'acl', enabled: true, config: { whitelist: [groupName] } }); return api; } function injectOAuth2Auth(api: ApiDescription): void { debug('injectOAuth2Auth()'); if (!api.config.plugins) api.config.plugins = []; const plugins = api.config.plugins; //console.log(JSON.stringify(plugins, null, 2)); const oauth2Plugin = plugins.find(function (plugin) { return plugin.name == "oauth2"; }); if (oauth2Plugin) throw new Error("If you use 'oauth2' in the apis.json, you must not provide a 'oauth2' plugin yourself. Remove it and retry."); const aclPlugin = plugins.find(function (plugin) { return plugin.name == 'acl'; }); if (aclPlugin) throw new Error("If you use 'oauth2' in the apis.json, you must not provide a 'acl' plugin yourself. Remove it and retry."); let scopes = []; let mandatory_scope = false; let token_expiration = 3600; let enable_client_credentials = false; let enable_implicit_grant = false; let enable_authorization_code = false; let enable_password_grant = false; let hide_credentials = false; if (api.settings) { // Check overridden defaults if (api.settings.scopes) scopes = api.settings.scopes as any; // This is correct; this is a hack further above. Search for "HACK_SCOPES" if (api.settings.mandatory_scope) mandatory_scope = api.settings.mandatory_scope; if (api.settings.token_expiration) token_expiration = Number(api.settings.token_expiration); if (api.settings.enable_client_credentials) enable_client_credentials = api.settings.enable_client_credentials; if (api.settings.enable_implicit_grant) enable_implicit_grant = api.settings.enable_implicit_grant; if (api.settings.enable_authorization_code) enable_authorization_code = api.settings.enable_authorization_code; if (api.settings.enable_password_grant) enable_password_grant = api.settings.enable_password_grant; if (api.config.api.hide_credentials) hide_credentials = api.config.api.hide_credentials; } // API_BUNDLE: In case the API is part of a bundle, specify that it's using global credentials. // This is a semi-nice hack for now; it means all APIs which are part of a bundle (any bundle!) // will also share the token. let globalCredentials = false; if (api.bundle) globalCredentials = true; const pluginConfig: any = { scopes: scopes, mandatory_scope: mandatory_scope, token_expiration: token_expiration, enable_authorization_code: enable_authorization_code, enable_client_credentials: enable_client_credentials, enable_implicit_grant: enable_implicit_grant, enable_password_grant: enable_password_grant, hide_credentials: hide_credentials, accept_http_if_already_terminated: true, global_credentials: globalCredentials } // Don't specify if not set; defaults to 2 weeks if (api.settings.refresh_token_ttl) pluginConfig.refresh_token_ttl = api.settings.refresh_token_ttl; plugins.push({ name: 'oauth2', enabled: true, config: pluginConfig }); // API_BUNDLE: Is this API part of a bundle? If so, use the bundle name as the group name let groupName = api.bundle ? api.bundle : api.id; debug(`injectOAuth2Auth: Using ACL group name ${groupName}`); plugins.push({ name: 'acl', enabled: true, config: { whitelist: [groupName] } }); }
the_stack