text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as React from "react"; import { dispatch, getContextMenuService, getDocumentService, getModalDialogService, getProjectService, getState, getStore, } from "@core/service-registry"; import VirtualizedList, { VirtualizedListApi, } from "../../../emu-ide/components/VirtualizedList"; import { SideBarPanelDescriptorBase } from "../side-bar/SideBarService"; import { SideBarPanelBase, SideBarProps } from "../SideBarPanelBase"; import { ITreeNode, ProjectNode } from "@abstractions/project-node"; import { CSSProperties } from "react"; import { Icon } from "../../../emu-ide/components/Icon"; import { AppState, ProjectState } from "@state/AppState"; import { NEW_FOLDER_DIALOG_ID } from "./NewFolderDialog"; import { ConfirmDialogResponse, GetFileContentsResponse, } from "@core/messaging/message-types"; import { TreeNode } from "../../../emu-ide/components/TreeNode"; import { NEW_FILE_DIALOG_ID } from "./NewFileDialog"; import { RENAME_FILE_DIALOG_ID } from "./RenameFileDialog"; import { RENAME_FOLDER_DIALOG_ID } from "./RenameFolderDialog"; import { IProjectService } from "@abstractions/project-service"; import { sendFromIdeToEmu } from "@core/messaging/message-sending"; import { addBuildRootAction, removeBuildRootAction, } from "@state/builder-reducer"; import { NewFileData } from "./NewFileData"; import { MenuItem } from "@abstractions/command-definitions"; type State = { itemsCount: number; selected?: ITreeNode<ProjectNode>; selectedIndex: number; isLoading: boolean; }; /** * Project files panel */ export default class ProjectFilesPanel extends SideBarPanelBase< SideBarProps<{}>, State > { private _listApi: VirtualizedListApi; private _projectService: IProjectService; private _lastProjectState: ProjectState | null = null; private _onProjectChange: (state: ProjectState) => Promise<void>; constructor(props: SideBarProps<{}>) { super(props); this.state = { itemsCount: 0, selectedIndex: -1, isLoading: false, }; this._projectService = getProjectService(); this._onProjectChange = (state) => this.onProjectChange(state); } async componentDidMount(): Promise<void> { this.setState({ itemsCount: this.itemsCount, }); getStore().projectChanged.on(this._onProjectChange); } componentWillUnmount(): void { getStore().projectChanged.off(this._onProjectChange); } /** * Gets the number of items in the list */ get itemsCount(): number { const tree = this._projectService.getProjectTree(); return tree && tree.rootNode ? tree.rootNode.viewItemCount : 0; } /** * Respond to project state changes */ async onProjectChange(state: ProjectState): Promise<void> { if (this._lastProjectState) { if ( this._lastProjectState.isLoading === state.isLoading && this._lastProjectState.path === state.path && this._lastProjectState.hasVm === state.hasVm ) { // --- Just the context of the project has changed this._lastProjectState = state; return; } } // --- The UI should update itself according to the state change if (state.isLoading) { this.setState({ isLoading: true, itemsCount: 0, }); } else { if (!state.path) { this.setState({ isLoading: false, itemsCount: 0, }); } else { this._projectService.setProjectContents(state.directoryContents); this.setState({ isLoading: false, itemsCount: this.itemsCount, }); } } this._lastProjectState = state; } render() { let slice: ITreeNode<ProjectNode>[]; if (this.state.itemsCount > 0) { return ( <VirtualizedList itemHeight={22} numItems={this.state.itemsCount} integralPosition={false} renderItem={( index: number, style: CSSProperties, startIndex: number, endIndex: number ) => { if (index === startIndex) { slice = this.getListItemRange(startIndex, endIndex); } return this.renderItem(index, style, slice[index - startIndex]); }} registerApi={(api) => (this._listApi = api)} handleKeys={(e) => this.handleKeys(e)} onFocus={() => { this.signFocus(true); this._listApi.forceRefresh(); }} onBlur={() => { this.signFocus(false); this._listApi.forceRefresh(); }} /> ); } else { const panelStyle: CSSProperties = { display: "flex", flexDirection: "column", flexGrow: 1, flexShrink: 1, width: "100%", height: "100%", fontSize: "0.8em", color: "var(--information-color)", paddingLeft: 20, paddingRight: 20, }; const buttonStyle: CSSProperties = { backgroundColor: "var(--selected-background-color)", color: "var(--menu-text-color)", width: "100%", border: "none", marginTop: 13, padding: 8, cursor: "pointer", }; return ( <div style={panelStyle}> {!this.state.isLoading && ( <> <span style={{ marginTop: 13 }}> You have not yet opened a folder. </span> <button style={buttonStyle} onClick={async () => { await sendFromIdeToEmu({ type: "OpenProjectFolder", }); }} > Open Folder </button> </> )} </div> ); } } renderItem( index: number, style: CSSProperties, item: ITreeNode<ProjectNode> ) { const itemStyle: CSSProperties = { display: "flex", alignItems: "center", width: "100%", height: 22, fontSize: "0.8em", paddingRight: 16, cursor: "pointer", background: item === this.state.selected ? this.state.focused ? "var(--selected-background-color)" : "var(--list-selected-background-color)" : undefined, border: item === this.state.selected ? this.state.focused ? "1px solid var(--selected-border-color)" : "1px solid transparent" : "1px solid transparent", }; const filename = item.nodeData.fullPath.substr( getState().project.path.length ); const isBuildRoot = getState().builder.roots.includes(filename); return ( <div key={index} className="listlike" style={{ ...style, ...itemStyle }} onContextMenu={(ev) => this.onContextMenu(ev, index, item, isBuildRoot)} onClick={() => this.openDocument(index, item, true)} onDoubleClick={() => this.openDocument(index, item)} > <div style={{ width: 22 + 12 * item.level + (item.nodeData.isFolder ? 0 : 16), flexShrink: 0, flexGrow: 0, }} ></div> {item.nodeData.isFolder && ( <Icon iconName="chevron-right" width={16} height={16} rotate={item.isExpanded ? 90 : 0} style={{ flexShrink: 0, flexGrow: 0 }} /> )} <Icon iconName={ item.nodeData.isFolder ? item.isExpanded ? "@folder-open" : "@folder" : "@file-code" } width={16} height={16} style={{ marginLeft: 4, marginRight: 4, flexShrink: 0, flexGrow: 0 }} fill={ item.nodeData.isFolder ? "--explorer-folder-color" : "--explorer-file-color" } /> <div style={{ marginLeft: 4, width: "100%", flexShrink: 1, flexGrow: 1, overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis", }} > {item.nodeData.name} </div> {isBuildRoot && ( <Icon iconName="combine" width={16} height={16} fill="green" style={{ flexShrink: 0, flexGrow: 0 }} /> )} </div> ); } /** * Retrieves the items slice of the specified range. */ getListItemRange( start: number, end: number, topHidden?: number ): ITreeNode<ProjectNode>[] { const tree = this._projectService.getProjectTree(); const offset = topHidden || 0; if (!tree) { return []; } return tree.getViewNodeRange(start + offset, end + offset); } /** * Collapse or expand the specified item * @param index Item index * @param item Node */ collapseExpand(index: number, item: ITreeNode<ProjectNode>): void { item.isExpanded = !item.isExpanded; this.setState({ itemsCount: this.itemsCount, selected: item, selectedIndex: index, }); this._listApi.forceRefresh(); } /** * Allow moving in the project explorer with keys */ handleKeys(e: React.KeyboardEvent): void { const tree = this._projectService.getProjectTree(); let newIndex = -1; switch (e.code) { case "ArrowUp": if (this.state.selectedIndex <= 0) return; newIndex = this.state.selectedIndex - 1; break; case "ArrowDown": { if (this.state.selectedIndex >= this.state.itemsCount - 1) return; newIndex = this.state.selectedIndex + 1; break; } case "Home": { newIndex = 0; break; } case "End": { newIndex = this.state.itemsCount - 1; break; } case "Space": case "Enter": if (!this.state.selected) return; this.collapseExpand(this.state.selectedIndex, this.state.selected); break; default: return; } if (newIndex >= 0) { this._listApi.ensureVisible(newIndex); this.setState({ selectedIndex: newIndex, selected: tree.getViewNodeByIndex(newIndex), }); this._listApi.forceRefresh(); } } async openDocument( index: number, item: ITreeNode<ProjectNode>, isTemporary: boolean = false ): Promise<void> { if (item.nodeData.isFolder) { this.collapseExpand(index, item); } else { this.setState({ selected: item, selectedIndex: index, }); this._listApi.forceRefresh(); // --- Test if the specified document is already open const id = item.nodeData.fullPath; const documentService = getDocumentService(); const document = documentService.getDocumentById(id); if (document) { if (!isTemporary) { document.temporary = false; document.initialFocus = true; } documentService.setActiveDocument(document); return; } // --- Create a new document const resource = item.nodeData.fullPath; const factory = documentService.getResourceFactory(resource); if (factory) { const contentsResp = await sendFromIdeToEmu<GetFileContentsResponse>({ type: "GetFileContents", name: resource, }); const sourceText = contentsResp?.contents ? (contentsResp.contents as string) : ""; let panel = await factory.createDocumentPanel(resource, sourceText); let index = documentService.getActiveDocument()?.index ?? null; panel.projectNode = item.nodeData; panel.temporary = isTemporary; panel.initialFocus = !isTemporary; if (isTemporary) { const tempDocument = documentService.getTemporaryDocument(); if (tempDocument) { index = tempDocument.index; documentService.unregisterDocument(tempDocument); } } documentService.registerDocument(panel, true, index); } } } /** * Handles the context menu click of the specified item * @param ev Event information * @param index Item index * @param item Item data */ async onContextMenu( ev: React.MouseEvent, index: number, item: ITreeNode<ProjectNode>, isBuildRoot: boolean ): Promise<void> { let menuItems: MenuItem[]; if (item.nodeData.isFolder) { // --- Create menu items menuItems = [ { id: "newFolder", text: "New Folder...", execute: async () => { await this.newFolder(item, index); }, }, { id: "newFile", text: "New File...", execute: async () => { await this.newFile(item, index); }, }, "separator", { id: "copyPath", text: "Copy Path", execute: async () => { await navigator.clipboard.writeText( item.nodeData.fullPath.replace(/\\/g, "/") ); }, }, "separator", { id: "renameFolder", text: "Rename", execute: async () => await this.renameFileOrFolder(item, index, true), }, { id: "deleteFolder", text: "Delete", enabled: index !== 0, execute: async () => await this.deleteFolder(item), }, ]; } else { menuItems = [ { id: "copyPath", text: "Copy Path", execute: async () => { await navigator.clipboard.writeText( item.nodeData.fullPath.replace(/\\/g, "/") ); }, }, "separator", { id: "renameFile", text: "Rename", execute: async () => await this.renameFileOrFolder(item, index), }, { id: "deleteFile", text: "Delete", execute: async () => await this.deleteFile(item), }, ]; const editor = getDocumentService().getCodeEditorInfo( item.nodeData.fullPath ); if (editor?.allowBuildRoot) { menuItems.push("separator"); if (isBuildRoot) { menuItems.push({ id: "removeBuildRoot", text: "Remove Build root", execute: async () => { dispatch( removeBuildRootAction( item.nodeData.fullPath.substr(getState().project.path.length) ) ); this._listApi.forceRefresh(); getDocumentService().fireChanges(); }, }); } else { menuItems.push({ id: "markBuildRoot", text: "Mark as Build root", execute: async () => { dispatch( addBuildRootAction( item.nodeData.fullPath.substr(getState().project.path.length) ) ); this._listApi.forceRefresh(); getDocumentService().fireChanges(); }, }); } } } const rect = (ev.target as HTMLElement).getBoundingClientRect(); await getContextMenuService().openMenu( menuItems, rect.y + 22, ev.clientX, ev.target as HTMLElement ); } /** * Creates a new folder in the specified folder node * @param node Folder node * @param index Node index */ async newFolder(node: ITreeNode<ProjectNode>, index: number): Promise<void> { // --- Get the name of the new folder const folderData = (await getModalDialogService().showModalDialog( NEW_FOLDER_DIALOG_ID, { root: node.nodeData.fullPath, } )) as NewFileData; if (!folderData?.name) { // --- No folder to create return; } // --- Create the new folder const newName = folderData.name; const newFullPath = `${folderData.root}/${newName}`; const resp = await this._projectService.createFolder(newFullPath); if (resp) { // --- Creation failed. The main process has already displayed a message return; } // --- Insert the new node into the tree let newPosition = 0; const childCount = node.childCount; for (let i = 0; i < childCount; i++, newPosition++) { const child = node.getChild(i); if (!child.nodeData.isFolder || newName < child.nodeData.name) break; } const newTreeNode = new TreeNode<ProjectNode>({ isFolder: true, name: newName, fullPath: newFullPath, }); node.insertChildAt(newPosition, newTreeNode); node.isExpanded = true; // --- Refresh the view const selectedIndex = index + newPosition + 1; this.setState({ selectedIndex, selected: newTreeNode, itemsCount: this.itemsCount, }); this._listApi.focus(); this._listApi.ensureVisible(selectedIndex); this._listApi.forceRefresh(); } /** * Creates a new file in the specified folder node * @param node Folder node * @param index Node index */ async newFile(node: ITreeNode<ProjectNode>, index: number): Promise<void> { // --- Get the name of the new folder const fileData = (await getModalDialogService().showModalDialog( NEW_FILE_DIALOG_ID, { root: node.nodeData.fullPath, } )) as NewFileData; if (!fileData?.name) { // --- No folder to create return; } // --- Create the new file const newName = fileData.name; const newFullPath = `${fileData.root}/${newName}`; const resp = await this._projectService.createFile(newFullPath); if (resp) { // --- Creation failed. The main process has already displayed a message return; } // --- Insert the new node into the tree let newPosition = 0; const childCount = node.childCount; for (let i = 0; i < childCount; i++, newPosition++) { const child = node.getChild(i); if (child.nodeData.isFolder) continue; if (newName < child.nodeData.name) break; } const newTreeNode = new TreeNode<ProjectNode>({ isFolder: false, name: newName, fullPath: newFullPath, }); node.insertChildAt(newPosition, newTreeNode); node.isExpanded = true; // --- Refresh the view const selectedIndex = index + newPosition + 1; this.setState({ selectedIndex, selected: newTreeNode, itemsCount: this.itemsCount, }); this._listApi.focus(); this._listApi.ensureVisible(selectedIndex); this._listApi.forceRefresh(); // --- Emulate clicking the item this.openDocument(selectedIndex, newTreeNode); } /** * Deletes the specified file * @param node File node */ async deleteFile(node: ITreeNode<ProjectNode>): Promise<void> { // --- Confirm delete const result = await sendFromIdeToEmu<ConfirmDialogResponse>({ type: "ConfirmDialog", title: "Confirm delete", question: `Are you sure you want to delete the ${node.nodeData.fullPath} file?`, }); if (!result.confirmed) { // --- Delete aborted return; } // --- Delete the file const resp = await this._projectService.deleteFile(node.nodeData.fullPath); if (resp) { // --- Delete failed return; } // --- Refresh the view node.parentNode.removeChild(node); this.setState({ itemsCount: this.itemsCount, }); this._listApi.focus(); this._listApi.forceRefresh(); } /** * Deletes the specified file * @param node File node */ async deleteFolder(node: ITreeNode<ProjectNode>): Promise<void> { // --- Confirm delete const result = await sendFromIdeToEmu<ConfirmDialogResponse>({ type: "ConfirmDialog", title: "Confirm delete", question: `Are you sure you want to delete the ${node.nodeData.fullPath} folder?`, }); if (!result.confirmed) { // --- Delete aborted return; } // --- Delete the file const resp = await this._projectService.deleteFolder( node.nodeData.fullPath ); if (resp) { // --- Delete failed return; } // --- Refresh the view node.parentNode.removeChild(node); this.setState({ itemsCount: this.itemsCount, }); this._listApi.focus(); this._listApi.forceRefresh(); } /** * Renames the specified file * @param node File node * @param index Node index */ async renameFileOrFolder( node: ITreeNode<ProjectNode>, index: number, isFolder: boolean = false ): Promise<void> { // --- Get the new name const oldPath = node.nodeData.fullPath.substr( 0, node.nodeData.fullPath.length - node.nodeData.name.length - 1 ); const fileData = (await getModalDialogService().showModalDialog( isFolder ? RENAME_FOLDER_DIALOG_ID : RENAME_FILE_DIALOG_ID, { root: oldPath, name: node.nodeData.name, newName: node.nodeData.name, } )) as NewFileData; if (!fileData) { // --- No file to rename return; } // --- Rename the file const newFullName = `${oldPath}/${fileData.name}`; const resp = isFolder ? await this._projectService.renameFolder( node.nodeData.fullPath, newFullName ) : await this._projectService.renameFile( node.nodeData.fullPath, newFullName ); if (resp) { // --- Rename failed return; } // --- Rename folder children this._projectService.renameProjectNode( node, node.nodeData.fullPath, newFullName, isFolder ); // --- Refresh the view node.nodeData.name = fileData.name; node.nodeData.fullPath = newFullName; this.setState({ itemsCount: this.itemsCount, selectedIndex: index, selected: node, }); this._listApi.focus(); this._listApi.forceRefresh(); } } /** * Descriptor for the sample side bar panel */ export class ProjectFilesPanelDescriptor extends SideBarPanelDescriptorBase { private _lastProjectState: ProjectState = null; private _shouldRefresh = false; /** * Panel title */ get title(): string { const projectState = getState().project; return projectState?.projectName ? `${projectState.projectName}${projectState?.hasVm ? "" : " (No VM)"}` : "No project opened"; } /** * Creates a node that represents the contents of a side bar panel */ createContentElement(): React.ReactNode { return <ProjectFilesPanel descriptor={this} />; } /** * Respond to state changes * @param state */ async onStateChange(state: AppState): Promise<void> { if (this._lastProjectState !== state.project) { this._lastProjectState = state.project; this.expanded = true; this._shouldRefresh = true; return; } this._shouldRefresh = false; } /** * Should update the panel header? */ async shouldUpdatePanelHeader(): Promise<boolean> { return this._shouldRefresh; } }
the_stack
import { TableOptionsInterface, P_CREATE_TABLE_OPTIONS, O_CREATE_TABLE_OPTION } from '../../../../typings'; import { isString, isDefined } from '../../../../shared/utils'; import { TableOptionsModelInterface, } from './typings'; /** * Class to represent table options as parsed from SQL. */ export class TableOptions implements TableOptionsModelInterface { autoincrement?: number; avgRowLength?: number; charset?: string; checksum?: number; collation?: string; comment?: string; compression?: string; connection?: string; dataDirectory?: string; indexDirectory?: string; delayKeyWrite?: number; encryption?: string; encryptionKeyId?: number; ietfQuotes?: string; engine?: string; insertMethod?: string; keyBlockSize?: number; maxRows?: number; minRows?: number; packKeys?: string | number; pageChecksum?: number; password?: string; rowFormat?: string; statsAutoRecalc?: string | number; statsPersistent?: string | number; statsSamplePages?: string | number; transactional?: number; withSystemVersioning?: boolean; tablespaceName?: string; tablespaceStorage?: string; union?: string[]; /** * Creates table options from a JSON def. * * @param json JSON format parsed from SQL. */ static fromDef(json: P_CREATE_TABLE_OPTIONS): TableOptions { if (json.id === 'P_CREATE_TABLE_OPTIONS') { return TableOptions.fromArray(json.def); } throw new TypeError(`Unknown json id to build table options from: ${json.id}`); } /** * Creates table options instance from an array of options. * * @param options JSON format parsed from SQL. */ static fromArray(options: O_CREATE_TABLE_OPTION[]): TableOptions { const tableOptions = new TableOptions(); options.forEach((option) => { if (isDefined(option.def.autoincrement)) { tableOptions.autoincrement = option.def.autoincrement; } if (isDefined(option.def.avgRowLength)) { tableOptions.avgRowLength = option.def.avgRowLength; } if (isDefined(option.def.charset)) { tableOptions.charset = option.def.charset.toLowerCase(); } if (isDefined(option.def.checksum)) { tableOptions.checksum = option.def.checksum; } if (isDefined(option.def.collation)) { tableOptions.collation = option.def.collation.toLowerCase(); } if (isDefined(option.def.comment)) { tableOptions.comment = option.def.comment; } if (isDefined(option.def.compression)) { tableOptions.compression = option.def.compression.toLowerCase(); } if (isDefined(option.def.connection)) { tableOptions.connection = option.def.connection; } if (isDefined(option.def.dataDirectory)) { tableOptions.dataDirectory = option.def.dataDirectory; } if (isDefined(option.def.indexDirectory)) { tableOptions.indexDirectory = option.def.indexDirectory; } if (isDefined(option.def.delayKeyWrite)) { tableOptions.delayKeyWrite = option.def.delayKeyWrite; } if (isDefined(option.def.encryption)) { tableOptions.encryption = option.def.encryption.toLowerCase(); } if (isDefined(option.def.encryptionKeyId)) { tableOptions.encryptionKeyId = option.def.encryptionKeyId; } if (isDefined(option.def.ietfQuotes)) { tableOptions.ietfQuotes = option.def.ietfQuotes.toLowerCase(); } if (isDefined(option.def.engine)) { tableOptions.engine = option.def.engine; } if (isDefined(option.def.insertMethod)) { tableOptions.insertMethod = option.def.insertMethod.toLowerCase(); } if (isDefined(option.def.keyBlockSize)) { tableOptions.keyBlockSize = option.def.keyBlockSize; } if (isDefined(option.def.maxRows)) { tableOptions.maxRows = option.def.maxRows; } if (isDefined(option.def.minRows)) { tableOptions.minRows = option.def.minRows; } if (isDefined(option.def.packKeys)) { if (isString(option.def.packKeys)) { tableOptions.packKeys = option.def.packKeys.toLowerCase(); } else { tableOptions.packKeys = option.def.packKeys; } } if (isDefined(option.def.pageChecksum)) { tableOptions.pageChecksum = option.def.pageChecksum; } if (isDefined(option.def.password)) { tableOptions.password = option.def.password; } if (isDefined(option.def.rowFormat)) { tableOptions.rowFormat = option.def.rowFormat.toLowerCase(); } if (isDefined(option.def.statsAutoRecalc)) { if (isString(option.def.statsAutoRecalc)) { tableOptions.statsAutoRecalc = option.def.statsAutoRecalc.toLowerCase(); } else { tableOptions.statsAutoRecalc = option.def.statsAutoRecalc; } } if (isDefined(option.def.statsPersistent)) { if (isString(option.def.statsPersistent)) { tableOptions.statsPersistent = option.def.statsPersistent.toLowerCase(); } else { tableOptions.statsPersistent = option.def.statsPersistent; } } if (isDefined(option.def.statsSamplePages)) { if (isString(option.def.statsSamplePages)) { tableOptions.statsSamplePages = option.def.statsSamplePages.toLowerCase(); } else { tableOptions.statsSamplePages = option.def.statsSamplePages; } } if (isDefined(option.def.transactional)) { tableOptions.transactional = option.def.transactional; } if (isDefined(option.def.withSystemVersioning)) { tableOptions.withSystemVersioning = option.def.withSystemVersioning; } if (isDefined(option.def.tablespaceName)) { tableOptions.tablespaceName = option.def.tablespaceName; } if (isDefined(option.def.tablespaceStorage)) { tableOptions.tablespaceStorage = option.def.tablespaceStorage.toLowerCase(); } if (isDefined(option.def.union)) { tableOptions.union = option.def.union; } }); return tableOptions; } /** * JSON casting of this object calls this method. * */ toJSON(): TableOptionsInterface { const json: TableOptionsInterface = {}; if (isDefined(this.autoincrement)) { json.autoincrement = this.autoincrement; } if (isDefined(this.avgRowLength)) { json.avgRowLength = this.avgRowLength; } if (isDefined(this.charset)) { json.charset = this.charset; } if (isDefined(this.checksum)) { json.checksum = this.checksum; } if (isDefined(this.collation)) { json.collation = this.collation; } if (isDefined(this.comment)) { json.comment = this.comment; } if (isDefined(this.compression)) { json.compression = this.compression; } if (isDefined(this.connection)) { json.connection = this.connection; } if (isDefined(this.dataDirectory)) { json.dataDirectory = this.dataDirectory; } if (isDefined(this.indexDirectory)) { json.indexDirectory = this.indexDirectory; } if (isDefined(this.delayKeyWrite)) { json.delayKeyWrite = this.delayKeyWrite; } if (isDefined(this.encryption)) { json.encryption = this.encryption; } if (isDefined(this.encryptionKeyId)) { json.encryptionKeyId = this.encryptionKeyId; } if (isDefined(this.ietfQuotes)) { json.ietfQuotes = this.ietfQuotes; } if (isDefined(this.engine)) { json.engine = this.engine; } if (isDefined(this.insertMethod)) { json.insertMethod = this.insertMethod; } if (isDefined(this.keyBlockSize)) { json.keyBlockSize = this.keyBlockSize; } if (isDefined(this.maxRows)) { json.maxRows = this.maxRows; } if (isDefined(this.minRows)) { json.minRows = this.minRows; } if (isDefined(this.packKeys)) { json.packKeys = this.packKeys; } if (isDefined(this.pageChecksum)) { json.pageChecksum = this.pageChecksum; } if (isDefined(this.password)) { json.password = this.password; } if (isDefined(this.rowFormat)) { json.rowFormat = this.rowFormat; } if (isDefined(this.statsAutoRecalc)) { json.statsAutoRecalc = this.statsAutoRecalc; } if (isDefined(this.statsPersistent)) { json.statsPersistent = this.statsPersistent; } if (isDefined(this.statsSamplePages)) { json.statsSamplePages = this.statsSamplePages; } if (isDefined(this.transactional)) { json.transactional = this.transactional; } if (isDefined(this.withSystemVersioning)) { json.withSystemVersioning = this.withSystemVersioning; } if (isDefined(this.tablespaceName)) { json.tablespaceName = this.tablespaceName; } if (isDefined(this.tablespaceStorage)) { json.tablespaceStorage = this.tablespaceStorage; } if (isDefined(this.union)) { json.union = this.union; } return json; } /** * Create a deep clone of this model. */ clone(): TableOptions { const options = new TableOptions(); if (isDefined(this.autoincrement)) { options.autoincrement = this.autoincrement; } if (isDefined(this.avgRowLength)) { options.avgRowLength = this.avgRowLength; } if (isDefined(this.charset)) { options.charset = this.charset; } if (isDefined(this.checksum)) { options.checksum = this.checksum; } if (isDefined(this.collation)) { options.collation = this.collation; } if (isDefined(this.comment)) { options.comment = this.comment; } if (isDefined(this.compression)) { options.compression = this.compression; } if (isDefined(this.connection)) { options.connection = this.connection; } if (isDefined(this.dataDirectory)) { options.dataDirectory = this.dataDirectory; } if (isDefined(this.indexDirectory)) { options.indexDirectory = this.indexDirectory; } if (isDefined(this.delayKeyWrite)) { options.delayKeyWrite = this.delayKeyWrite; } if (isDefined(this.encryption)) { options.encryption = this.encryption; } if (isDefined(this.encryptionKeyId)) { options.encryptionKeyId = this.encryptionKeyId; } if (isDefined(this.ietfQuotes)) { options.ietfQuotes = this.ietfQuotes; } if (isDefined(this.engine)) { options.engine = this.engine; } if (isDefined(this.insertMethod)) { options.insertMethod = this.insertMethod; } if (isDefined(this.keyBlockSize)) { options.keyBlockSize = this.keyBlockSize; } if (isDefined(this.maxRows)) { options.maxRows = this.maxRows; } if (isDefined(this.minRows)) { options.minRows = this.minRows; } if (isDefined(this.packKeys)) { options.packKeys = this.packKeys; } if (isDefined(this.pageChecksum)) { options.pageChecksum = this.pageChecksum; } if (isDefined(this.password)) { options.password = this.password; } if (isDefined(this.rowFormat)) { options.rowFormat = this.rowFormat; } if (isDefined(this.statsAutoRecalc)) { options.statsAutoRecalc = this.statsAutoRecalc; } if (isDefined(this.statsPersistent)) { options.statsPersistent = this.statsPersistent; } if (isDefined(this.statsSamplePages)) { options.statsSamplePages = this.statsSamplePages; } if (isDefined(this.transactional)) { options.transactional = this.transactional; } if (isDefined(this.withSystemVersioning)) { options.withSystemVersioning = this.withSystemVersioning; } if (isDefined(this.tablespaceName)) { options.tablespaceName = this.tablespaceName; } if (isDefined(this.tablespaceStorage)) { options.tablespaceStorage = this.tablespaceStorage; } if (isDefined(this.union)) { options.union = this.union.slice(); } return options; } /** * Merge this option instance with another one. * Common properties of this instance are overwritten. */ mergeWith(options: TableOptionsInterface): void { if (isDefined(options.autoincrement)) { this.autoincrement = options.autoincrement; } if (isDefined(options.avgRowLength)) { this.avgRowLength = options.avgRowLength; } if (isDefined(options.charset)) { this.charset = options.charset; } if (isDefined(options.checksum)) { this.checksum = options.checksum; } if (isDefined(options.collation)) { this.collation = options.collation; } if (isDefined(options.comment)) { this.comment = options.comment; } if (isDefined(options.compression)) { this.compression = options.compression; } if (isDefined(options.connection)) { this.connection = options.connection; } if (isDefined(options.dataDirectory)) { this.dataDirectory = options.dataDirectory; } if (isDefined(options.indexDirectory)) { this.indexDirectory = options.indexDirectory; } if (isDefined(options.delayKeyWrite)) { this.delayKeyWrite = options.delayKeyWrite; } if (isDefined(options.encryption)) { this.encryption = options.encryption; } if (isDefined(options.encryptionKeyId)) { this.encryptionKeyId = options.encryptionKeyId; } if (isDefined(options.ietfQuotes)) { this.ietfQuotes = options.ietfQuotes; } if (isDefined(options.engine)) { this.engine = options.engine; } if (isDefined(options.insertMethod)) { this.insertMethod = options.insertMethod; } if (isDefined(options.keyBlockSize)) { this.keyBlockSize = options.keyBlockSize; } if (isDefined(options.maxRows)) { this.maxRows = options.maxRows; } if (isDefined(options.minRows)) { this.minRows = options.minRows; } if (isDefined(options.packKeys)) { this.packKeys = options.packKeys; } if (isDefined(options.pageChecksum)) { this.pageChecksum = options.pageChecksum; } if (isDefined(options.password)) { this.password = options.password; } if (isDefined(options.rowFormat)) { this.rowFormat = options.rowFormat; } if (isDefined(options.statsAutoRecalc)) { this.statsAutoRecalc = options.statsAutoRecalc; } if (isDefined(options.statsPersistent)) { this.statsPersistent = options.statsPersistent; } if (isDefined(options.statsSamplePages)) { this.statsSamplePages = options.statsSamplePages; } if (isDefined(options.transactional)) { this.transactional = options.transactional; } if (isDefined(options.withSystemVersioning)) { this.withSystemVersioning = options.withSystemVersioning; } if (isDefined(options.tablespaceName)) { this.tablespaceName = options.tablespaceName; } if (isDefined(options.tablespaceStorage)) { this.tablespaceStorage = options.tablespaceStorage; } if (isDefined(options.union)) { this.union = options.union.slice(); } } }
the_stack
declare module io { export module fabric { export module sdk { export module android { export class ActivityLifecycleManager { public static class: java.lang.Class<io.fabric.sdk.android.ActivityLifecycleManager>; public constructor(param0: globalAndroid.content.Context); public registerCallbacks(param0: io.fabric.sdk.android.ActivityLifecycleManager.Callbacks): boolean; public resetCallbacks(): void; } export module ActivityLifecycleManager { export class ActivityLifecycleCallbacksWrapper { public static class: java.lang.Class<io.fabric.sdk.android.ActivityLifecycleManager.ActivityLifecycleCallbacksWrapper>; } export abstract class Callbacks { public static class: java.lang.Class<io.fabric.sdk.android.ActivityLifecycleManager.Callbacks>; public onActivityPaused(param0: globalAndroid.app.Activity): void; public onActivitySaveInstanceState(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void; public onActivityDestroyed(param0: globalAndroid.app.Activity): void; public constructor(); public onActivityStarted(param0: globalAndroid.app.Activity): void; public onActivityResumed(param0: globalAndroid.app.Activity): void; public onActivityCreated(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void; public onActivityStopped(param0: globalAndroid.app.Activity): void; } } } } } } declare module io { export module fabric { export module sdk { export module android { export class BuildConfig { public static class: java.lang.Class<io.fabric.sdk.android.BuildConfig>; public static DEBUG: boolean; public static APPLICATION_ID: string; public static BUILD_TYPE: string; public static FLAVOR: string; public static VERSION_CODE: number; public static VERSION_NAME: string; public static ARTIFACT_ID: string; public static BUILD_NUMBER: string; public static DEVELOPER_TOKEN: string; public static GROUP: string; public constructor(); } } } } } declare module io { export module fabric { export module sdk { export module android { export class DefaultLogger extends io.fabric.sdk.android.Logger { public static class: java.lang.Class<io.fabric.sdk.android.DefaultLogger>; public i(param0: string, param1: string, param2: java.lang.Throwable): void; public getLogLevel(): number; public v(param0: string, param1: string, param2: java.lang.Throwable): void; public e(param0: string, param1: string, param2: java.lang.Throwable): void; public isLoggable(param0: string, param1: number): boolean; public d(param0: string, param1: string): void; public setLogLevel(param0: number): void; public e(param0: string, param1: string): void; public constructor(); public i(param0: string, param1: string): void; public log(param0: number, param1: string, param2: string, param3: boolean): void; public w(param0: string, param1: string): void; public v(param0: string, param1: string): void; public constructor(param0: number); public d(param0: string, param1: string, param2: java.lang.Throwable): void; public w(param0: string, param1: string, param2: java.lang.Throwable): void; public log(param0: number, param1: string, param2: string): void; } } } } } declare module io { export module fabric { export module sdk { export module android { export class Fabric { public static class: java.lang.Class<io.fabric.sdk.android.Fabric>; public static TAG: string; public getCurrentActivity(): globalAndroid.app.Activity; public getVersion(): string; public getExecutorService(): java.util.concurrent.ExecutorService; public getAppIdentifier(): string; public static getLogger(): io.fabric.sdk.android.Logger; public getIdentifier(): string; public static getKit(param0: java.lang.Class): io.fabric.sdk.android.Kit; public setCurrentActivity(param0: globalAndroid.app.Activity): io.fabric.sdk.android.Fabric; public getAppInstallIdentifier(): string; public getActivityLifecycleManager(): io.fabric.sdk.android.ActivityLifecycleManager; public getMainHandler(): globalAndroid.os.Handler; public static isDebuggable(): boolean; public static with(param0: globalAndroid.content.Context, param1: native.Array<io.fabric.sdk.android.Kit>): io.fabric.sdk.android.Fabric; public static with(param0: io.fabric.sdk.android.Fabric): io.fabric.sdk.android.Fabric; public static isInitialized(): boolean; public getKits(): java.util.Collection<io.fabric.sdk.android.Kit>; } export module Fabric { export class Builder { public static class: java.lang.Class<io.fabric.sdk.android.Fabric.Builder>; public logger(param0: io.fabric.sdk.android.Logger): io.fabric.sdk.android.Fabric.Builder; public constructor(param0: globalAndroid.content.Context); public threadPoolExecutor(param0: io.fabric.sdk.android.services.concurrency.PriorityThreadPoolExecutor): io.fabric.sdk.android.Fabric.Builder; public build(): io.fabric.sdk.android.Fabric; public executorService(param0: java.util.concurrent.ExecutorService): io.fabric.sdk.android.Fabric.Builder; public handler(param0: globalAndroid.os.Handler): io.fabric.sdk.android.Fabric.Builder; public appIdentifier(param0: string): io.fabric.sdk.android.Fabric.Builder; public kits(param0: native.Array<io.fabric.sdk.android.Kit>): io.fabric.sdk.android.Fabric.Builder; public appInstallIdentifier(param0: string): io.fabric.sdk.android.Fabric.Builder; public debuggable(param0: boolean): io.fabric.sdk.android.Fabric.Builder; public initializationCallback(param0: io.fabric.sdk.android.InitializationCallback<io.fabric.sdk.android.Fabric>): io.fabric.sdk.android.Fabric.Builder; } } } } } } declare module io { export module fabric { export module sdk { export module android { export class FabricContext { public static class: java.lang.Class<io.fabric.sdk.android.FabricContext>; public getCacheDir(): java.io.File; public getDatabasePath(param0: string): java.io.File; public constructor(param0: globalAndroid.content.Context, param1: string, param2: string); public getExternalCacheDir(): java.io.File; public getSharedPreferences(param0: string, param1: number): globalAndroid.content.SharedPreferences; public getExternalFilesDir(param0: string): java.io.File; public openOrCreateDatabase(param0: string, param1: number, param2: globalAndroid.database.sqlite.SQLiteDatabase.CursorFactory, param3: globalAndroid.database.DatabaseErrorHandler): globalAndroid.database.sqlite.SQLiteDatabase; public openOrCreateDatabase(param0: string, param1: number, param2: globalAndroid.database.sqlite.SQLiteDatabase.CursorFactory): globalAndroid.database.sqlite.SQLiteDatabase; public getFilesDir(): java.io.File; } } } } } declare module io { export module fabric { export module sdk { export module android { export class FabricKitsFinder extends java.util.concurrent.Callable<java.util.Map<string,io.fabric.sdk.android.KitInfo>> { public static class: java.lang.Class<io.fabric.sdk.android.FabricKitsFinder>; public call(): java.util.Map<string,io.fabric.sdk.android.KitInfo>; public loadApkFile(): java.util.zip.ZipFile; } } } } } declare module io { export module fabric { export module sdk { export module android { export class InitializationCallback<T> extends java.lang.Object { public static class: java.lang.Class<io.fabric.sdk.android.InitializationCallback>; /** * Constructs a new instance of the io.fabric.sdk.android.InitializationCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { success(param0: T): void; failure(param0: java.lang.Exception): void; <clinit>(): void; }); public constructor(); public static EMPTY: io.fabric.sdk.android.InitializationCallback; public failure(param0: java.lang.Exception): void; public success(param0: T): void; } export module InitializationCallback { export class Empty extends io.fabric.sdk.android.InitializationCallback<any> { public static class: java.lang.Class<io.fabric.sdk.android.InitializationCallback.Empty>; public failure(param0: java.lang.Exception): void; public success(param0: any): void; } } } } } } declare module io { export module fabric { export module sdk { export module android { export class InitializationException { public static class: java.lang.Class<io.fabric.sdk.android.InitializationException>; public constructor(param0: string, param1: java.lang.Throwable); public constructor(param0: string); } } } } } declare module io { export module fabric { export module sdk { export module android { export class InitializationTask<Result> extends io.fabric.sdk.android.services.concurrency.PriorityAsyncTask<java.lang.Void,java.lang.Void,any> { public static class: java.lang.Class<io.fabric.sdk.android.InitializationTask>; public isFinished(): boolean; public constructor(param0: io.fabric.sdk.android.Kit<any>); public getDependencies(): java.util.Collection<io.fabric.sdk.android.services.concurrency.Task>; public onPreExecute(): void; public onCancelled(param0: any): void; public setFinished(param0: boolean): void; public getError(): java.lang.Throwable; public addDependency(param0: io.fabric.sdk.android.services.concurrency.Task): void; public getPriority(): io.fabric.sdk.android.services.concurrency.Priority; public areDependenciesMet(): boolean; public getDelegate(): io.fabric.sdk.android.services.concurrency.Dependency; public constructor(); public doInBackground(param0: native.Array<java.lang.Void>): any; public onCancelled(): void; public getDependencies(): java.util.Collection<any>; public setError(param0: java.lang.Throwable): void; public doInBackground(param0: native.Array<any>): any; public onPostExecute(param0: any): void; public addDependency(param0: any): void; } } } } } declare module io { export module fabric { export module sdk { export module android { export abstract class Kit<Result> extends java.lang.Comparable<io.fabric.sdk.android.Kit> { public static class: java.lang.Class<io.fabric.sdk.android.Kit>; public getVersion(): string; public compareTo(param0: io.fabric.sdk.android.Kit): number; public getDependencies(): java.util.Collection<io.fabric.sdk.android.services.concurrency.Task>; public onCancelled(param0: any): void; public onPreExecute(): boolean; public getIdManager(): io.fabric.sdk.android.services.common.IdManager; public getIdentifier(): string; public getPath(): string; public constructor(); public getContext(): globalAndroid.content.Context; public onPostExecute(param0: any): void; public getFabric(): io.fabric.sdk.android.Fabric; public doInBackground(): any; } } } } } declare module io { export module fabric { export module sdk { export module android { export class KitGroup { public static class: java.lang.Class<io.fabric.sdk.android.KitGroup>; /** * Constructs a new instance of the io.fabric.sdk.android.KitGroup interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getKits(): java.util.Collection<any>; }); public constructor(); public getKits(): java.util.Collection<any>; } } } } } declare module io { export module fabric { export module sdk { export module android { export class KitInfo { public static class: java.lang.Class<io.fabric.sdk.android.KitInfo>; public getVersion(): string; public getIdentifier(): string; public constructor(param0: string, param1: string, param2: string); public getBuildType(): string; } } } } } declare module io { export module fabric { export module sdk { export module android { export class Logger { public static class: java.lang.Class<io.fabric.sdk.android.Logger>; /** * Constructs a new instance of the io.fabric.sdk.android.Logger interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { isLoggable(param0: string, param1: number): boolean; getLogLevel(): number; setLogLevel(param0: number): void; d(param0: string, param1: string, param2: java.lang.Throwable): void; v(param0: string, param1: string, param2: java.lang.Throwable): void; i(param0: string, param1: string, param2: java.lang.Throwable): void; w(param0: string, param1: string, param2: java.lang.Throwable): void; e(param0: string, param1: string, param2: java.lang.Throwable): void; d(param0: string, param1: string): void; v(param0: string, param1: string): void; i(param0: string, param1: string): void; w(param0: string, param1: string): void; e(param0: string, param1: string): void; log(param0: number, param1: string, param2: string): void; log(param0: number, param1: string, param2: string, param3: boolean): void; }); public constructor(); public i(param0: string, param1: string, param2: java.lang.Throwable): void; public getLogLevel(): number; public v(param0: string, param1: string, param2: java.lang.Throwable): void; public e(param0: string, param1: string, param2: java.lang.Throwable): void; public isLoggable(param0: string, param1: number): boolean; public d(param0: string, param1: string): void; public setLogLevel(param0: number): void; public e(param0: string, param1: string): void; public i(param0: string, param1: string): void; public log(param0: number, param1: string, param2: string, param3: boolean): void; public w(param0: string, param1: string): void; public v(param0: string, param1: string): void; public d(param0: string, param1: string, param2: java.lang.Throwable): void; public w(param0: string, param1: string, param2: java.lang.Throwable): void; public log(param0: number, param1: string, param2: string): void; } } } } } declare module io { export module fabric { export module sdk { export module android { export class Onboarding extends io.fabric.sdk.android.Kit<java.lang.Boolean> { public static class: java.lang.Class<io.fabric.sdk.android.Onboarding>; public getVersion(): string; public constructor(); public constructor(param0: java.util.concurrent.Future<java.util.Map<string,io.fabric.sdk.android.KitInfo>>, param1: java.util.Collection<io.fabric.sdk.android.Kit>); public onPreExecute(): boolean; public getIdentifier(): string; public doInBackground(): java.lang.Boolean; public doInBackground(): any; } } } } } declare module io { export module fabric { export module sdk { export module android { export class SilentLogger extends io.fabric.sdk.android.Logger { public static class: java.lang.Class<io.fabric.sdk.android.SilentLogger>; public i(param0: string, param1: string, param2: java.lang.Throwable): void; public getLogLevel(): number; public v(param0: string, param1: string, param2: java.lang.Throwable): void; public e(param0: string, param1: string, param2: java.lang.Throwable): void; public isLoggable(param0: string, param1: number): boolean; public d(param0: string, param1: string): void; public e(param0: string, param1: string): void; public setLogLevel(param0: number): void; public constructor(); public i(param0: string, param1: string): void; public log(param0: number, param1: string, param2: string, param3: boolean): void; public w(param0: string, param1: string): void; public v(param0: string, param1: string): void; public d(param0: string, param1: string, param2: java.lang.Throwable): void; public w(param0: string, param1: string, param2: java.lang.Throwable): void; public log(param0: number, param1: string, param2: string): void; } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module cache { export abstract class AbstractValueCache<T> extends io.fabric.sdk.android.services.cache.ValueCache<any> { public static class: java.lang.Class<io.fabric.sdk.android.services.cache.AbstractValueCache>; public constructor(); public constructor(param0: io.fabric.sdk.android.services.cache.ValueCache<any>); public invalidate(param0: globalAndroid.content.Context): void; public doInvalidate(param0: globalAndroid.content.Context): void; public cacheValue(param0: globalAndroid.content.Context, param1: any): void; public getCached(param0: globalAndroid.content.Context): any; public get(param0: globalAndroid.content.Context, param1: io.fabric.sdk.android.services.cache.ValueLoader<any>): any; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module cache { export class MemoryValueCache<T> extends io.fabric.sdk.android.services.cache.AbstractValueCache<any> { public static class: java.lang.Class<io.fabric.sdk.android.services.cache.MemoryValueCache>; public constructor(); public constructor(param0: io.fabric.sdk.android.services.cache.ValueCache<any>); public doInvalidate(param0: globalAndroid.content.Context): void; public cacheValue(param0: globalAndroid.content.Context, param1: any): void; public invalidate(param0: globalAndroid.content.Context): void; public getCached(param0: globalAndroid.content.Context): any; public get(param0: globalAndroid.content.Context, param1: io.fabric.sdk.android.services.cache.ValueLoader<any>): any; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module cache { export class ValueCache<T> extends java.lang.Object { public static class: java.lang.Class<io.fabric.sdk.android.services.cache.ValueCache>; /** * Constructs a new instance of the io.fabric.sdk.android.services.cache.ValueCache interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { get(param0: globalAndroid.content.Context, param1: io.fabric.sdk.android.services.cache.ValueLoader<T>): T; invalidate(param0: globalAndroid.content.Context): void; }); public constructor(); public get(param0: globalAndroid.content.Context, param1: io.fabric.sdk.android.services.cache.ValueLoader<T>): T; public invalidate(param0: globalAndroid.content.Context): void; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module cache { export class ValueLoader<T> extends java.lang.Object { public static class: java.lang.Class<io.fabric.sdk.android.services.cache.ValueLoader>; /** * Constructs a new instance of the io.fabric.sdk.android.services.cache.ValueLoader interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { load(param0: globalAndroid.content.Context): T; }); public constructor(); public load(param0: globalAndroid.content.Context): T; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export abstract class AbstractSpiCall { public static class: java.lang.Class<io.fabric.sdk.android.services.common.AbstractSpiCall>; public static HEADER_API_KEY: string; public static HEADER_DEVELOPER_TOKEN: string; public static HEADER_CLIENT_TYPE: string; public static HEADER_CLIENT_VERSION: string; public static HEADER_REQUEST_ID: string; public static HEADER_USER_AGENT: string; public static HEADER_ACCEPT: string; public static CRASHLYTICS_USER_AGENT: string; public static ACCEPT_JSON_VALUE: string; public static CLS_ANDROID_SDK_DEVELOPER_TOKEN: string; public static DEFAULT_TIMEOUT: number; public static ANDROID_CLIENT_TYPE: string; public kit: io.fabric.sdk.android.Kit; public getUrl(): string; public getHttpRequest(): io.fabric.sdk.android.services.network.HttpRequest; public constructor(param0: io.fabric.sdk.android.Kit, param1: string, param2: string, param3: io.fabric.sdk.android.services.network.HttpRequestFactory, param4: io.fabric.sdk.android.services.network.HttpMethod); public getHttpRequest(param0: java.util.Map<string,string>): io.fabric.sdk.android.services.network.HttpRequest; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class AdvertisingInfo { public static class: java.lang.Class<io.fabric.sdk.android.services.common.AdvertisingInfo>; public advertisingId: string; public limitAdTrackingEnabled: boolean; public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class AdvertisingInfoProvider { public static class: java.lang.Class<io.fabric.sdk.android.services.common.AdvertisingInfoProvider>; public getReflectionStrategy(): io.fabric.sdk.android.services.common.AdvertisingInfoStrategy; public getServiceStrategy(): io.fabric.sdk.android.services.common.AdvertisingInfoStrategy; public getAdvertisingInfo(): io.fabric.sdk.android.services.common.AdvertisingInfo; public getInfoFromPreferences(): io.fabric.sdk.android.services.common.AdvertisingInfo; public constructor(param0: globalAndroid.content.Context); } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class AdvertisingInfoReflectionStrategy extends io.fabric.sdk.android.services.common.AdvertisingInfoStrategy { public static class: java.lang.Class<io.fabric.sdk.android.services.common.AdvertisingInfoReflectionStrategy>; public getAdvertisingInfo(): io.fabric.sdk.android.services.common.AdvertisingInfo; public constructor(param0: globalAndroid.content.Context); } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class AdvertisingInfoServiceStrategy extends io.fabric.sdk.android.services.common.AdvertisingInfoStrategy { public static class: java.lang.Class<io.fabric.sdk.android.services.common.AdvertisingInfoServiceStrategy>; public static GOOGLE_PLAY_SERVICES_INTENT: string; public static GOOGLE_PLAY_SERVICES_INTENT_PACKAGE_NAME: string; public getAdvertisingInfo(): io.fabric.sdk.android.services.common.AdvertisingInfo; public constructor(param0: globalAndroid.content.Context); } export module AdvertisingInfoServiceStrategy { export class AdvertisingConnection { public static class: java.lang.Class<io.fabric.sdk.android.services.common.AdvertisingInfoServiceStrategy.AdvertisingConnection>; public onServiceDisconnected(param0: globalAndroid.content.ComponentName): void; public getBinder(): globalAndroid.os.IBinder; public onServiceConnected(param0: globalAndroid.content.ComponentName, param1: globalAndroid.os.IBinder): void; } export class AdvertisingInterface { public static class: java.lang.Class<io.fabric.sdk.android.services.common.AdvertisingInfoServiceStrategy.AdvertisingInterface>; public static ADVERTISING_ID_SERVICE_INTERFACE_TOKEN: string; public isLimitAdTrackingEnabled(): boolean; public constructor(param0: globalAndroid.os.IBinder); public asBinder(): globalAndroid.os.IBinder; public getId(): string; } } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class AdvertisingInfoStrategy { public static class: java.lang.Class<io.fabric.sdk.android.services.common.AdvertisingInfoStrategy>; /** * Constructs a new instance of the io.fabric.sdk.android.services.common.AdvertisingInfoStrategy interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getAdvertisingInfo(): io.fabric.sdk.android.services.common.AdvertisingInfo; }); public constructor(); public getAdvertisingInfo(): io.fabric.sdk.android.services.common.AdvertisingInfo; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class ApiKey { public static class: java.lang.Class<io.fabric.sdk.android.services.common.ApiKey>; public constructor(); public getApiKeyFromStrings(param0: globalAndroid.content.Context): string; public getApiKeyFromManifest(param0: globalAndroid.content.Context): string; public logErrorOrThrowException(param0: globalAndroid.content.Context): void; public static getApiKey(param0: globalAndroid.content.Context, param1: boolean): string; public buildApiKeyInstructions(): string; public getApiKeyFromFirebaseAppId(param0: globalAndroid.content.Context): string; public static getApiKey(param0: globalAndroid.content.Context): string; public getValue(param0: globalAndroid.content.Context): string; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export abstract class BackgroundPriorityRunnable { public static class: java.lang.Class<io.fabric.sdk.android.services.common.BackgroundPriorityRunnable>; public constructor(); public onRun(): void; public run(): void; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class CommonUtils { public static class: java.lang.Class<io.fabric.sdk.android.services.common.CommonUtils>; public static SHA1_INSTANCE: string; public static SHA256_INSTANCE: string; public static GOOGLE_SDK: string; public static SDK: string; public static DEVICE_STATE_ISSIMULATOR: number; public static DEVICE_STATE_JAILBROKEN: number; public static DEVICE_STATE_DEBUGGERATTACHED: number; public static DEVICE_STATE_BETAOS: number; public static DEVICE_STATE_VENDORINTERNAL: number; public static DEVICE_STATE_COMPROMISEDLIBRARIES: number; public static FILE_MODIFIED_COMPARATOR: java.util.Comparator<java.io.File>; public static logControlledError(param0: globalAndroid.content.Context, param1: string, param2: java.lang.Throwable): void; public static copyStream(param0: java.io.InputStream, param1: java.io.OutputStream, param2: native.Array<number>): void; public static getAppIconResourceId(param0: globalAndroid.content.Context): number; public static isRooted(param0: globalAndroid.content.Context): boolean; public static getBatteryVelocity(param0: globalAndroid.content.Context, param1: boolean): number; public static resolveUnityEditorVersion(param0: globalAndroid.content.Context): string; public static checkPermission(param0: globalAndroid.content.Context, param1: string): boolean; public static logOrThrowIllegalArgumentException(param0: string, param1: string): void; public static isClsTrace(param0: globalAndroid.content.Context): boolean; public static sha1(param0: java.io.InputStream): string; public static createInstanceIdFrom(param0: native.Array<string>): string; public static logPriorityToString(param0: number): string; public static dehexify(param0: string): native.Array<number>; public static closeOrLog(param0: java.io.Closeable, param1: string): void; public static resolveBuildId(param0: globalAndroid.content.Context): string; public static getBooleanResourceValue(param0: globalAndroid.content.Context, param1: string, param2: boolean): boolean; public static createCipher(param0: number, param1: string): javax.crypto.Cipher; public static calculateUsedDiskSpaceInBytes(param0: string): number; public static openKeyboard(param0: globalAndroid.content.Context, param1: globalAndroid.view.View): void; public static finishAffinity(param0: globalAndroid.app.Activity, param1: number): void; public static getAppIconHashOrNull(param0: globalAndroid.content.Context): string; public static streamToString(param0: java.io.InputStream): string; public static getStringsFileValue(param0: globalAndroid.content.Context, param1: string): string; public static flushOrLog(param0: java.io.Flushable, param1: string): void; public static extractFieldFromSystemFile(param0: java.io.File, param1: string): string; public static finishAffinity(param0: globalAndroid.content.Context, param1: number): void; public static isDebuggerAttached(): boolean; public static canTryConnection(param0: globalAndroid.content.Context): boolean; public static getProximitySensorEnabled(param0: globalAndroid.content.Context): boolean; public static closeQuietly(param0: java.io.Closeable): void; public static hideKeyboard(param0: globalAndroid.content.Context, param1: globalAndroid.view.View): void; public static isEmulator(param0: globalAndroid.content.Context): boolean; public static calculateFreeRamInBytes(param0: globalAndroid.content.Context): number; public static getResourcesIdentifier(param0: globalAndroid.content.Context, param1: string, param2: string): number; public static logControlled(param0: globalAndroid.content.Context, param1: string): void; public static hexify(param0: native.Array<number>): string; public static sha1(param0: string): string; public static getResourcePackageName(param0: globalAndroid.content.Context): string; public static logOrThrowIllegalStateException(param0: string, param1: string): void; public static padWithZerosToMaxIntWidth(param0: number): string; public constructor(); public static getAppProcessInfo(param0: string, param1: globalAndroid.content.Context): globalAndroid.app.ActivityManager.RunningAppProcessInfo; public static getBatteryLevel(param0: globalAndroid.content.Context): java.lang.Float; public static getSharedPrefs(param0: globalAndroid.content.Context): globalAndroid.content.SharedPreferences; public static getDeviceState(param0: globalAndroid.content.Context): number; public static isNullOrEmpty(param0: string): boolean; public static stringsEqualIncludingNull(param0: string, param1: string): boolean; public static isLoggingEnabled(param0: globalAndroid.content.Context): boolean; public static isAppDebuggable(param0: globalAndroid.content.Context): boolean; public static getTotalRamInBytes(): number; public static logControlled(param0: globalAndroid.content.Context, param1: number, param2: string, param3: string): void; public static getCpuArchitectureInt(): number; public static sha256(param0: string): string; } export module CommonUtils { export class Architecture { public static class: java.lang.Class<io.fabric.sdk.android.services.common.CommonUtils.Architecture>; public static X86_32: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static X86_64: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static ARM_UNKNOWN: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static PPC: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static PPC64: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static ARMV6: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static ARMV7: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static UNKNOWN: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static ARMV7S: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static ARM64: io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static valueOf(param0: string): io.fabric.sdk.android.services.common.CommonUtils.Architecture; public static values(): native.Array<io.fabric.sdk.android.services.common.CommonUtils.Architecture>; } } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export abstract class Crash { public static class: java.lang.Class<io.fabric.sdk.android.services.common.Crash>; public constructor(param0: string); public constructor(param0: string, param1: string); public getSessionId(): string; public getExceptionName(): string; } export module Crash { export class FatalException extends io.fabric.sdk.android.services.common.Crash { public static class: java.lang.Class<io.fabric.sdk.android.services.common.Crash.FatalException>; public constructor(param0: string, param1: string); public constructor(param0: string); } export class LoggedException extends io.fabric.sdk.android.services.common.Crash { public static class: java.lang.Class<io.fabric.sdk.android.services.common.Crash.LoggedException>; public constructor(param0: string, param1: string); public constructor(param0: string); } } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class CurrentTimeProvider { public static class: java.lang.Class<io.fabric.sdk.android.services.common.CurrentTimeProvider>; /** * Constructs a new instance of the io.fabric.sdk.android.services.common.CurrentTimeProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getCurrentTimeMillis(): number; }); public constructor(); public getCurrentTimeMillis(): number; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class DataCollectionArbiter { public static class: java.lang.Class<io.fabric.sdk.android.services.common.DataCollectionArbiter>; public static getInstance(param0: globalAndroid.content.Context): io.fabric.sdk.android.services.common.DataCollectionArbiter; public shouldAutoInitialize(): boolean; public static resetForTesting(param0: globalAndroid.content.Context): void; public setCrashlyticsDataCollectionEnabled(param0: boolean): void; public isDataCollectionEnabled(): boolean; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class DeliveryMechanism { public static class: java.lang.Class<io.fabric.sdk.android.services.common.DeliveryMechanism>; public static DEVELOPER: io.fabric.sdk.android.services.common.DeliveryMechanism; public static USER_SIDELOAD: io.fabric.sdk.android.services.common.DeliveryMechanism; public static TEST_DISTRIBUTION: io.fabric.sdk.android.services.common.DeliveryMechanism; public static APP_STORE: io.fabric.sdk.android.services.common.DeliveryMechanism; public static BETA_APP_PACKAGE_NAME: string; public static valueOf(param0: string): io.fabric.sdk.android.services.common.DeliveryMechanism; public static determineFrom(param0: string): io.fabric.sdk.android.services.common.DeliveryMechanism; public getId(): number; public toString(): string; public static values(): native.Array<io.fabric.sdk.android.services.common.DeliveryMechanism>; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class DeviceIdentifierProvider { public static class: java.lang.Class<io.fabric.sdk.android.services.common.DeviceIdentifierProvider>; /** * Constructs a new instance of the io.fabric.sdk.android.services.common.DeviceIdentifierProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getDeviceIdentifiers(): java.util.Map<io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType,string>; }); public constructor(); public getDeviceIdentifiers(): java.util.Map<io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType,string>; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class ExecutorUtils { public static class: java.lang.Class<io.fabric.sdk.android.services.common.ExecutorUtils>; public static getNamedThreadFactory(param0: string): java.util.concurrent.ThreadFactory; public static addDelayedShutdownHook(param0: string, param1: java.util.concurrent.ExecutorService, param2: number, param3: java.util.concurrent.TimeUnit): void; public static buildSingleThreadScheduledExecutorService(param0: string): java.util.concurrent.ScheduledExecutorService; public static buildRetryThreadPoolExecutor(param0: string, param1: number, param2: io.fabric.sdk.android.services.concurrency.internal.RetryPolicy, param3: io.fabric.sdk.android.services.concurrency.internal.Backoff): io.fabric.sdk.android.services.concurrency.internal.RetryThreadPoolExecutor; public static buildSingleThreadExecutorService(param0: string): java.util.concurrent.ExecutorService; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class FirebaseApp { public static class: java.lang.Class<io.fabric.sdk.android.services.common.FirebaseApp>; /** * Constructs a new instance of the io.fabric.sdk.android.services.common.FirebaseApp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { isDataCollectionDefaultEnabled(): boolean; }); public constructor(); public isDataCollectionDefaultEnabled(): boolean; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class FirebaseAppImpl extends io.fabric.sdk.android.services.common.FirebaseApp { public static class: java.lang.Class<io.fabric.sdk.android.services.common.FirebaseAppImpl>; public isDataCollectionDefaultEnabled(): boolean; public static getInstance(param0: globalAndroid.content.Context): io.fabric.sdk.android.services.common.FirebaseApp; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class FirebaseInfo { public static class: java.lang.Class<io.fabric.sdk.android.services.common.FirebaseInfo>; public constructor(); public isAutoInitializeFlagEnabled(param0: globalAndroid.content.Context): boolean; public isFirebaseCrashlyticsEnabled(param0: globalAndroid.content.Context): boolean; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class IdManager { public static class: java.lang.Class<io.fabric.sdk.android.services.common.IdManager>; public static COLLECT_DEVICE_IDENTIFIERS: string; public static COLLECT_USER_IDENTIFIERS: string; public static DEFAULT_VERSION_NAME: string; public getWifiMacAddress(): string; public getTelephonyId(): string; public getOsVersionString(): string; public getDeviceIdentifiers(): java.util.Map<io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType,string>; public getModelName(): string; public getAdvertisingId(): string; public getAndroidId(): string; public getAppIdentifier(): string; public constructor(param0: globalAndroid.content.Context, param1: string, param2: string, param3: java.util.Collection<io.fabric.sdk.android.Kit>); public getBluetoothMacAddress(): string; public shouldCollectHardwareIds(): boolean; public getOsDisplayVersionString(): string; public canCollectUserIds(): boolean; public getOsBuildVersionString(): string; public getSerialNumber(): string; public createIdHeaderValue(param0: string, param1: string): string; public getAppInstallIdentifier(): string; public getInstallerPackageName(): string; public isLimitAdTrackingEnabled(): java.lang.Boolean; } export module IdManager { export class DeviceIdentifierType { public static class: java.lang.Class<io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType>; public static WIFI_MAC_ADDRESS: io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType; public static BLUETOOTH_MAC_ADDRESS: io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType; public static FONT_TOKEN: io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType; public static ANDROID_ID: io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType; public static ANDROID_DEVICE_ID: io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType; public static ANDROID_SERIAL: io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType; public static ANDROID_ADVERTISING_ID: io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType; public protobufIndex: number; public static values(): native.Array<io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType>; public static valueOf(param0: string): io.fabric.sdk.android.services.common.IdManager.DeviceIdentifierType; } } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class InstallerPackageNameProvider { public static class: java.lang.Class<io.fabric.sdk.android.services.common.InstallerPackageNameProvider>; public constructor(); public getInstallerPackageName(param0: globalAndroid.content.Context): string; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class QueueFile { public static class: java.lang.Class<io.fabric.sdk.android.services.common.QueueFile>; public peek(param0: io.fabric.sdk.android.services.common.QueueFile.ElementReader): void; public size(): number; public close(): void; public usedBytes(): number; public remove(): void; public clear(): void; public toString(): string; public peek(): native.Array<number>; public constructor(param0: java.io.File); public add(param0: native.Array<number>): void; public forEach(param0: io.fabric.sdk.android.services.common.QueueFile.ElementReader): void; public add(param0: native.Array<number>, param1: number, param2: number): void; public isEmpty(): boolean; public hasSpaceFor(param0: number, param1: number): boolean; } export module QueueFile { export class Element { public static class: java.lang.Class<io.fabric.sdk.android.services.common.QueueFile.Element>; public toString(): string; } export class ElementInputStream { public static class: java.lang.Class<io.fabric.sdk.android.services.common.QueueFile.ElementInputStream>; public read(param0: native.Array<number>, param1: number, param2: number): number; public read(): number; } export class ElementReader { public static class: java.lang.Class<io.fabric.sdk.android.services.common.QueueFile.ElementReader>; /** * Constructs a new instance of the io.fabric.sdk.android.services.common.QueueFile$ElementReader interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { read(param0: java.io.InputStream, param1: number): void; }); public constructor(); public read(param0: java.io.InputStream, param1: number): void; } } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class ResponseParser { public static class: java.lang.Class<io.fabric.sdk.android.services.common.ResponseParser>; public static ResponseActionDiscard: number; public static ResponseActionRetry: number; public constructor(); public static parse(param0: number): number; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class SafeToast { public static class: java.lang.Class<io.fabric.sdk.android.services.common.SafeToast>; public show(): void; public static makeText(param0: globalAndroid.content.Context, param1: string, param2: number): globalAndroid.widget.Toast; public constructor(param0: globalAndroid.content.Context); public static makeText(param0: globalAndroid.content.Context, param1: number, param2: number): globalAndroid.widget.Toast; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class SystemCurrentTimeProvider extends io.fabric.sdk.android.services.common.CurrentTimeProvider { public static class: java.lang.Class<io.fabric.sdk.android.services.common.SystemCurrentTimeProvider>; public constructor(); public getCurrentTimeMillis(): number; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module common { export class TimingMetric { public static class: java.lang.Class<io.fabric.sdk.android.services.common.TimingMetric>; public stopMeasuring(): void; public constructor(param0: string, param1: string); public startMeasuring(): void; public getDuration(): number; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module concurrency { export abstract class AsyncTask<Params, Progress, Result> extends java.lang.Object { public static class: java.lang.Class<io.fabric.sdk.android.services.concurrency.AsyncTask>; public static THREAD_POOL_EXECUTOR: java.util.concurrent.Executor; public static SERIAL_EXECUTOR: java.util.concurrent.Executor; public constructor(); public onPreExecute(): void; public onCancelled(): void; public cancel(param0: boolean): boolean; public get(param0: number, param1: java.util.concurrent.TimeUnit): Result; public isCancelled(): boolean; public get(): Result; public execute(param0: native.Array<Params>): io.fabric.sdk.android.services.concurrency.AsyncTask<Params,Progress,Result>; public onPostExecute(param0: Result): void; public executeOnExecutor(param0: java.util.concurrent.Executor, param1: native.Array<Params>): io.fabric.sdk.android.services.concurrency.AsyncTask<Params,Progress,Result>; public getStatus(): io.fabric.sdk.android.services.concurrency.AsyncTask.Status; public static setDefaultExecutor(param0: java.util.concurrent.Executor): void; public onCancelled(param0: Result): void; public static init(): void; public publishProgress(param0: native.Array<Progress>): void; public onProgressUpdate(param0: native.Array<Progress>): void; public static execute(param0: java.lang.Runnable): void; public doInBackground(param0: native.Array<Params>): Result; } export module AsyncTask { export class AsyncTaskResult<Data> extends java.lang.Object { public static class: java.lang.Class<io.fabric.sdk.android.services.concurrency.AsyncTask.AsyncTaskResult>; } export class InternalHandler { public static class: java.lang.Class<io.fabric.sdk.android.services.concurrency.AsyncTask.InternalHandler>; public handleMessage(param0: globalAndroid.os.Message): void; public constructor(); } export class SerialExecutor { public static class: java.lang.Class<io.fabric.sdk.android.services.concurrency.AsyncTask.SerialExecutor>; public scheduleNext(): void; public execute(param0: java.lang.Runnable): void; } export class Status { public static class: java.lang.Class<io.fabric.sdk.android.services.concurrency.AsyncTask.Status>; public static PENDING: io.fabric.sdk.android.services.concurrency.AsyncTask.Status; public static RUNNING: io.fabric.sdk.android.services.concurrency.AsyncTask.Status; public static FINISHED: io.fabric.sdk.android.services.concurrency.AsyncTask.Status; public static values(): native.Array<io.fabric.sdk.android.services.concurrency.AsyncTask.Status>; public static valueOf(param0: string): io.fabric.sdk.android.services.concurrency.AsyncTask.Status; } export abstract class WorkerRunnable<Params, Result> extends java.util.concurrent.Callable<any> { public static class: java.lang.Class<io.fabric.sdk.android.services.concurrency.AsyncTask.WorkerRunnable>; } } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module concurrency { export class DelegateProvider { public static class: java.lang.Class<io.fabric.sdk.android.services.concurrency.DelegateProvider>; /** * Constructs a new instance of the io.fabric.sdk.android.services.concurrency.DelegateProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getDelegate(): io.fabric.sdk.android.services.concurrency.Dependency; }); public constructor(); public getDelegate(): io.fabric.sdk.android.services.concurrency.Dependency; } } } } } } } declare module io { export module fabric { export module sdk { export module android { export module services { export module concurrency { export class Dependency<T> extends java.lang.Object { public static class: java.lang.Class<io.fabric.sdk.android.services.concurrency.Dependency>; /** * Constructs a new instance of the io.fabric.sdk.android.services.concurrency.Dependency interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { addDependency(param0: T): void; getDependencies(): java.util.Collection<T>; areDependenciesMet(): boolean; }); public constructor(); public getDependencies(): java.util.Collection<T>; public addDependency(param0: T): void; public areDependenciesMet(): boolean; } } } } } } }
the_stack
import Html2React from "@frontity/html2react/src/libraries/component"; import { HelmetProvider } from "frontity"; import { amp, toBeValidAmpHtml } from "./__utilities__/amp-validator"; import { FilledContext, HelmetData } from "react-helmet-async"; import processors from "../processors"; import { render } from "@testing-library/react"; expect.extend({ toBeValidAmpHtml }); // Need to set that flag when testing with jest // https://github.com/staylor/react-helmet-async#usage-in-jest HelmetProvider.canUseDOM = false; const replaceHeadAttributes = (head: HelmetData) => head.script.toString(); test("Validate amp-img", async () => { const { container } = render( <Html2React html="<img src='test.img' width='300' height='300'></img>" processors={processors} /> ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-img height="300" layout="responsive" src="test.img" width="300" /> `); expect(await amp(container.innerHTML)).toBeValidAmpHtml(); }); test("Validate amp-img when height or width are a number", async () => { const { container } = render( <Html2React html="<img src='test.img' width=300 height=300></img>" processors={processors} /> ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-img height="300" layout="responsive" src="test.img" width="300" /> `); expect(await amp(container.innerHTML)).toBeValidAmpHtml(); }); test("Validate amp-img when height and width are missing", async () => { const { container } = render( <Html2React html="<img src='test.img'></img>" processors={processors} /> ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-img class="css-1fbfwfl" layout="fill" src="test.img" /> `); expect(await amp(container.innerHTML)).toBeValidAmpHtml(); }); test("Validate amp-iframe", async () => { const helmetContext = {}; const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<iframe src='test.html' width='auto' height='300'/>" processors={processors} /> </HelmetProvider> ); const head = (helmetContext as FilledContext).helmet; expect(head.script.toString()).toMatchInlineSnapshot( `"<script data-rh=\\"true\\" async custom-element=\\"amp-iframe\\" src=\\"https://cdn.ampproject.org/v0/amp-iframe-0.1.js\\"></script>"` ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-iframe height="300" layout="fixed-height" sandbox="allow-scripts allow-same-origin " src="test.html" title="" width="auto" /> `); // We replace the `async="true"` with just `async` const headScript = replaceHeadAttributes(head); expect(await amp(container.innerHTML, headScript)).toBeValidAmpHtml(); }); test("amp-iframe should concatenate the sandbox properties", () => { const helmetContext = {}; const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<iframe sandbox='allow-scripts allow-popups' src='test.html' width='auto' height='300'/>" processors={processors} /> </HelmetProvider> ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-iframe height="300" layout="fixed-height" sandbox="allow-scripts allow-same-origin allow-scripts allow-popups" src="test.html" title="" width="auto" /> `); }); test("Validate amp-video", async () => { const helmetContext = {}; const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<video width='250' height='150' src='video.mp4' autoplay loop controls muted ></video>" processors={processors} /> </HelmetProvider> ); const head = (helmetContext as FilledContext).helmet; expect(head.script.toString()).toMatchInlineSnapshot( `"<script data-rh=\\"true\\" async custom-element=\\"amp-video\\" src=\\"https://cdn.ampproject.org/v0/amp-video-0.1.js\\"></script>"` ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-video autoplay="" controls="" height="250" layout="responsive" loop="" muted="" src="video.mp4" width="250" /> `); // We replace the `async="true"` with just `async` const headScript = replaceHeadAttributes(head); expect(await amp(container.innerHTML, headScript)).toBeValidAmpHtml(); }); test("Validate amp-audio", async () => { const helmetContext = {}; const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<audio src='audio.mp3'></audio>" processors={processors} /> </HelmetProvider> ); const head = (helmetContext as FilledContext).helmet; expect(head.script.toString()).toMatchInlineSnapshot( `"<script data-rh=\\"true\\" async custom-element=\\"amp-audio\\" src=\\"https://cdn.ampproject.org/v0/amp-audio-0.1.js\\"></script>"` ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-audio src="audio.mp3" /> `); // We replace the `async="true"` with just `async` const headScript = replaceHeadAttributes(head); expect(await amp(container.innerHTML, headScript)).toBeValidAmpHtml(); }); test("amp-audio with child elements", async () => { const helmetContext = {}; const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<audio controls> <source src='http://frontity.com/audio.mp3'></source> <div placeholder=''> this is a placeholder </div> <div placeholder=''> this placeholder should be removed </div> <p fallback=''> and this is a fallback </p> <p fallback=''> this is a fallback should be removed</p> <div> this element should be removed </div> </audio>" processors={processors} /> </HelmetProvider> ); const head = (helmetContext as FilledContext).helmet; expect(head.script.toString()).toMatchInlineSnapshot( `"<script data-rh=\\"true\\" async custom-element=\\"amp-audio\\" src=\\"https://cdn.ampproject.org/v0/amp-audio-0.1.js\\"></script>"` ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-audio controls="" > <source src="https://frontity.com/audio.mp3" /> <div placeholder="" > this is a placeholder </div> <p fallback="" > and this is a fallback </p> </amp-audio> `); }); test("amp-video with child elements", async () => { const helmetContext = {}; const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<video controls> <source src='http://frontity.com/video.mp4'></source> <track src='http://frontity.com/video1.mp4'></source> <track src='http://frontity.com/video2.mp4'></source> <div placeholder=''> this is a placeholder </div> <div placeholder=''> this placeholder should be removed </div> <p fallback=''> and this is a fallback </p> <p fallback=''> this is a fallback should be removed</p> <div> this element should be removed </div> </video>" processors={processors} /> </HelmetProvider> ); const head = (helmetContext as FilledContext).helmet; expect(head.script.toString()).toMatchInlineSnapshot( `"<script data-rh=\\"true\\" async custom-element=\\"amp-video\\" src=\\"https://cdn.ampproject.org/v0/amp-video-0.1.js\\"></script>"` ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-video controls="" height="9" layout="responsive" width="16" > <source src="https://frontity.com/video.mp4" /> <track src="https://frontity.com/video1.mp4" /> <track src="https://frontity.com/video2.mp4" /> <div placeholder="" > this is a placeholder </div> <p fallback="" > and this is a fallback </p> </amp-video> `); }); test("<script /> elements should be removed", async () => { const { container } = render( <Html2React html="<div><script src='test.js'></script></div>" processors={processors} /> ); expect(container.firstChild).toMatchInlineSnapshot(`<div />`); expect(await amp(container.innerHTML)).toBeValidAmpHtml(); }); test("Elements with prohibited class names should be removed", async () => { const { container } = render( <Html2React html=" <div> <div class='other -amp-test this-amp-is-allowed'></div> <div class='other i-amp-test -this-i-amp-is-also-allowed'></div> </div>" processors={processors} /> ); expect(container.firstChild).toMatchInlineSnapshot(` <div> <div class="other this-amp-is-allowed" /> <div class="other -this-i-amp-is-also-allowed" /> </div> `); expect(await amp(container.innerHTML)).toBeValidAmpHtml(); }); test("Elements with prohibited ID values should be removed", async () => { const { container } = render( <Html2React html=" <div> <div id='-amp-test' class='test1'></div> <div id='i-amp-test' class='test2'></div> </div>" processors={processors} /> ); expect(container.firstChild).toMatchInlineSnapshot(` <div> <div class="test1" /> <div class="test2" /> </div> `); expect(await amp(container.innerHTML)).toBeValidAmpHtml(); }); test("Validate amp-twitter", async () => { const { container } = render(<Html2React html="" processors={processors} />); expect(container.firstChild).toMatchInlineSnapshot(`null`); expect(await amp(container.innerHTML)).toBeValidAmpHtml(); }); test("Adding 2 iframes should result in adding only 1 amp-iframe AMP script in the <head />", async () => { const helmetContext = {}; const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<iframe src='a.html' width='auto' height='5'/><iframe src='a.html' width='auto' height='5'/>" processors={processors} /> </HelmetProvider> ); const head = (helmetContext as FilledContext).helmet; expect(head.script.toString()).toMatchInlineSnapshot( `"<script data-rh=\\"true\\" async custom-element=\\"amp-iframe\\" src=\\"https://cdn.ampproject.org/v0/amp-iframe-0.1.js\\"></script>"` ); // We replace the `async="true"` with just `async` const headScript = replaceHeadAttributes(head); expect(await amp(container.innerHTML, headScript)).toBeValidAmpHtml(); }); test("picture element should be replaced with an img", async () => { const { container } = render( <Html2React html=' <picture> <source media="(min-width:650px)" srcset="img_pink_flowers.jpg" /> <source media="(min-width:465px)" srcset="img_white_flower.jpg" /> <img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;" width="300" height="100" /> </picture>' processors={processors} /> ); expect(container.firstChild).toMatchInlineSnapshot(` <amp-img alt="Flowers" class="css-68zbsl" height="100" layout="responsive" src="img_orange_flowers.jpg" width="300" /> `); expect(await amp(container.innerHTML)).toBeValidAmpHtml(); }); describe("Transform http to https and warn about it", () => { const consoleWarn = jest.spyOn(global.console, "warn"); beforeEach(() => { consoleWarn.mockReset(); }); test("amp-iframe", () => { const helmetContext = {}; const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<iframe src='http://frontity.org/test.html' width='auto' height='300'/>" processors={processors} /> </HelmetProvider> ); expect( container.firstElementChild.getAttribute("src").startsWith("https://") ).toBe(true); expect(consoleWarn).toHaveBeenCalledTimes(1); expect(consoleWarn.mock.calls[0][0]).toMatchInlineSnapshot(` "An element with src of https://frontity.org/test.html was found but AMP requires resources to be loaded over HTTPS. Frontity will update the src attribute to point to the HTTPS version but you need to ensure that the asset is available over HTTPS. Visit https://community.frontity.org for help! 🙂 " `); }); test("amp-audio", () => { const helmetContext = {}; const consoleWarn = jest.spyOn(global.console, "warn"); const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<audio src='http://frontity.org/audio.mp3'></audio>" processors={processors} /> </HelmetProvider> ); expect( container .getElementsByTagName("amp-audio")[0] .getAttribute("src") .startsWith("https://") ).toBe(true); expect(consoleWarn).toHaveBeenCalledTimes(1); expect(consoleWarn.mock.calls[0][0]).toMatchInlineSnapshot(` "An element with src of https://frontity.org/audio.mp3 was found but AMP requires resources to be loaded over HTTPS. Frontity will update the src attribute to point to the HTTPS version but you need to ensure that the asset is available over HTTPS. Visit https://community.frontity.org for help! 🙂 " `); }); test("amp-video", () => { const helmetContext = {}; const consoleWarn = jest.spyOn(global.console, "warn"); const { container } = render( <HelmetProvider context={helmetContext}> <Html2React html="<video width='250' height='150' src='http://frontity.org/video.mp4' ></video>" processors={processors} /> </HelmetProvider> ); expect( container .getElementsByTagName("amp-video")[0] .getAttribute("src") .startsWith("https://") ).toBe(true); expect(consoleWarn).toHaveBeenCalledTimes(1); expect(consoleWarn.mock.calls[0][0]).toMatchInlineSnapshot(` "An element with src of https://frontity.org/video.mp4 was found but AMP requires resources to be loaded over HTTPS. Frontity will update the src attribute to point to the HTTPS version but you need to ensure that the asset is available over HTTPS. Visit https://community.frontity.org for help! 🙂 " `); }); });
the_stack
import { Button, Checkbox, CheckboxGroup, FormControl, FormHelperText, FormLabel, Input, Stack, } from "@chakra-ui/react"; import { OWNER_ROLE, defaultAbilities } from "@/features/roles"; import { Organization, Role } from "@prisma/client"; import { PlusIcon } from "@heroicons/react/outline"; import { diff } from "deep-object-diff"; import { isEmpty, isFunction, omit } from "lodash"; import { useBoolean } from "react-use"; import { useCreateRoleMutation, useDeleteRoleMutation, useGetRolesQuery, useUpdateRoleMutation, } from "@/features/roles/api-slice"; import { useOrganizationFromProfile, useSegment } from "@/hooks"; import { useRouter } from "next/router"; import ColumnListItem from "@/components/ColumnListItem"; import Layout from "@/components/Layout"; import LoadingOverlay from "@/components/LoadingOverlay"; import OptionWrapper from "@/features/views/components/OptionWrapper"; import OrganizationSidebar from "@/components/OrganizationSidebar"; import PageWrapper from "@/components/PageWrapper"; import React, { useEffect, useMemo, useState } from "react"; export type Ability = { id: string; label: string; }; // eslint-disable-next-line @typescript-eslint/ban-types const RoleEditor = ({ organization, currentRole = { id: "", name: "", options: {} }, selectRole, }: { organization: Organization; currentRole?: | Role | { id: ""; name: string; options: Record<string, unknown> }; selectRole: (payload: { name: string }) => void; }) => { const isCreateForm = currentRole.id === ""; const [role, setRole] = useState(currentRole); const [abilities, setAbilities] = useState<Ability["id"][]>([]); const isOwnerRole = useMemo( () => currentRole?.name === OWNER_ROLE, [currentRole] ); useSegment("Visited roles page", { page: "roles", }); useEffect(() => { if (currentRole.id !== "") { setRole(currentRole); } if (isOwnerRole) { setAbilities(defaultAbilities.map(({ id }) => id)); } else { // Don't try to set the abilities if you're just creating the role. if (!isCreateForm) { setAbilities( (currentRole?.options as any)?.abilities || defaultAbilities.map(({ id }) => id) ); } } }, [currentRole]); // Create a diff with changes to send to the server on update const changes = useMemo(() => diff(currentRole, role), [currentRole, role]); const roleId = useMemo(() => currentRole?.id?.toString(), [currentRole]); // Prepare mutations for create, update and delete const [createRole, { isLoading: isCreating }] = useCreateRoleMutation(); const [updateRole, { isLoading: isUpdating }] = useUpdateRoleMutation(); const [deleteRole, { isLoading: isDeleting }] = useDeleteRoleMutation(); const handleSubmit = async (e: any) => { e.preventDefault(); if (isCreateForm) { const response = await createRole({ organizationId: organization?.id.toString(), body: { changes: omit(role, ["id"]), }, }); selectRole({ name: (response as any)?.data?.data?.name }); } else { const response = await updateRole({ organizationId: organization?.id.toString(), roleId, body: { changes: role, }, }); selectRole({ name: (response as any)?.data?.data?.name }); } }; const handleDelete = async () => { if (confirm("Are you sure you want to remove this role?")) { await deleteRole({ organizationId: organization?.id?.toString(), roleId, }); if (isFunction(selectRole)) selectRole({ name: OWNER_ROLE }); } }; return ( <div className="w-full h-full flex flex-col justify-between"> <div> <div> <h3 className="uppercase text-md font-semibold"> {isCreateForm ? "Add a new role" : currentRole.name} </h3> </div> <div className="divide-y"> <form onSubmit={handleSubmit}> <OptionWrapper helpText={ isCreateForm ? "Give this role a name to remember" : "You might want to call this role something different" } > <FormControl id="name"> <FormLabel>Role name</FormLabel> <Input type="text" name="name" placeholder="User, Sales, Marketing or something else" value={role?.name} disabled={isOwnerRole} onChange={(e) => { setRole({ ...role, name: e.currentTarget.value, }); }} /> {isOwnerRole && ( <FormHelperText> You can't change the name of this role. </FormHelperText> )} </FormControl> </OptionWrapper> {!isCreateForm && ( <> <OptionWrapper helpText="What can this role do?"> <FormControl id="abilities"> <CheckboxGroup value={abilities} onChange={(value) => { setRole({ ...role, options: { ...(role.options as any), abilities: value, }, }); setAbilities(value as string[]); }} > <FormLabel>Abilities</FormLabel> <Stack direction="column"> {defaultAbilities.map(({ id, label }) => ( <Checkbox isDisabled={isOwnerRole} value={id}> {label} </Checkbox> ))} </Stack> </CheckboxGroup> {isOwnerRole && ( <FormHelperText> You can't change the name of this role. </FormHelperText> )} </FormControl> </OptionWrapper> </> )} </form> </div> </div> <div className="grid grid-cols-3"> <div> {!isCreateForm && !isOwnerRole && ( <a className="text-red-600 text-sm cursor-pointer" onClick={() => !isDeleting && handleDelete()} > Remove role </a> )} </div> <Button colorScheme="blue" size="sm" width="300px" onClick={handleSubmit} disabled={isEmpty(changes)} isLoading={isCreating || isUpdating} > {isCreateForm ? "Create" : "Save"} </Button> <div className="flex justify-end"></div> </div> </div> ); }; function Roles() { const router = useRouter(); const organization = useOrganizationFromProfile({ slug: router.query.organizationSlug as string, }); const [addNewRole, toggleAddNewRole] = useBoolean(false); const [currentRoleName, setCurrentRoleName] = useState<string>(OWNER_ROLE); const { data: rolesResponse, isLoading, isFetching, } = useGetRolesQuery( { organizationId: organization?.id?.toString(), }, { skip: !organization?.id } ); const roles = useMemo( () => (rolesResponse?.ok ? rolesResponse?.data : []), [rolesResponse] ); const currentRole = useMemo( () => roles.find(({ name }: { name: string }) => name === currentRoleName), [roles, currentRoleName] ); return ( <Layout sidebar={<OrganizationSidebar organization={organization} />}> <PageWrapper crumbs={[organization?.name, "Roles"]} flush={true}> <div className="relative flex-1 max-w-full w-full flex"> {(isLoading || isFetching) && <LoadingOverlay inPageWrapper />} <div className="flex flex-shrink-0 w-1/4 border-r"> <div className="w-full relative p-4"> <div className="mb-2">Roles</div> {roles && roles.map((role: Role, idx: number) => ( <ColumnListItem key={role.name} active={role.name === currentRoleName && !addNewRole} onClick={() => { setCurrentRoleName(role.name); toggleAddNewRole(false); }} > {role.name} </ColumnListItem> ))} <div className="mt-2"> <ColumnListItem active={addNewRole} icon={<PlusIcon className="h-4" />} onClick={() => toggleAddNewRole(true)} > Add new role </ColumnListItem> </div> </div> </div> {organization && ( <div className="flex-1 p-4"> {addNewRole && ( <RoleEditor organization={organization} selectRole={({ name }: { name: string }) => { toggleAddNewRole(false); setCurrentRoleName(name); }} /> )} {addNewRole || ( <> {!currentRole && "👈 Please select a role"} {currentRole && ( <RoleEditor organization={organization} currentRole={currentRole} selectRole={({ name }: { name: string }) => { toggleAddNewRole(false); setCurrentRoleName(name); }} /> )} </> )} </div> )} </div> </PageWrapper> </Layout> ); } export default Roles;
the_stack
import Long from "long"; import _m0 from "protobufjs/minimal"; import { Timestamp } from "../google/protobuf/timestamp"; import { BoolValue, Int32Value, StringValue, UInt32Value, Int64Value, } from "../google/protobuf/wrappers"; export const protobufPackage = "nakama.api"; /** The Nakama server RPC protocol for games and apps. */ /** Operator that can be used to override the one set in the leaderboard. */ export enum OverrideOperator { /** NO_OVERRIDE - Do not override the leaderboard operator. */ NO_OVERRIDE = 0, /** BEST - Override the leaderboard operator with BEST. */ BEST = 1, /** SET - Override the leaderboard operator with SET. */ SET = 2, /** INCREMENT - Override the leaderboard operator with INCREMENT. */ INCREMENT = 3, /** DECREMENT - Override the leaderboard operator with DECREMENT. */ DECREMENT = 4, UNRECOGNIZED = -1, } export function overrideOperatorFromJSON(object: any): OverrideOperator { switch (object) { case 0: case "NO_OVERRIDE": return OverrideOperator.NO_OVERRIDE; case 1: case "BEST": return OverrideOperator.BEST; case 2: case "SET": return OverrideOperator.SET; case 3: case "INCREMENT": return OverrideOperator.INCREMENT; case 4: case "DECREMENT": return OverrideOperator.DECREMENT; case -1: case "UNRECOGNIZED": default: return OverrideOperator.UNRECOGNIZED; } } export function overrideOperatorToJSON(object: OverrideOperator): string { switch (object) { case OverrideOperator.NO_OVERRIDE: return "NO_OVERRIDE"; case OverrideOperator.BEST: return "BEST"; case OverrideOperator.SET: return "SET"; case OverrideOperator.INCREMENT: return "INCREMENT"; case OverrideOperator.DECREMENT: return "DECREMENT"; default: return "UNKNOWN"; } } /** A user with additional account details. Always the current user. */ export interface Account { /** The user object. */ user?: User; /** The user's wallet data. */ wallet: string; /** The email address of the user. */ email: string; /** The devices which belong to the user's account. */ devices: AccountDevice[]; /** The custom id in the user's account. */ custom_id: string; /** The UNIX time when the user's email was verified. */ verify_time?: Date; /** The UNIX time when the user's account was disabled/banned. */ disable_time?: Date; } /** Obtain a new authentication token using a refresh token. */ export interface AccountRefresh { /** Refresh token. */ token: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountRefresh_VarsEntry { key: string; value: string; } /** Send a Apple Sign In token to the server. Used with authenticate/link/unlink. */ export interface AccountApple { /** The ID token received from Apple to validate. */ token: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountApple_VarsEntry { key: string; value: string; } /** Send a custom ID to the server. Used with authenticate/link/unlink. */ export interface AccountCustom { /** A custom identifier. */ id: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountCustom_VarsEntry { key: string; value: string; } /** Send a device to the server. Used with authenticate/link/unlink and user. */ export interface AccountDevice { /** A device identifier. Should be obtained by a platform-specific device API. */ id: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountDevice_VarsEntry { key: string; value: string; } /** Send an email with password to the server. Used with authenticate/link/unlink. */ export interface AccountEmail { /** A valid RFC-5322 email address. */ email: string; /** A password for the user account. */ password: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountEmail_VarsEntry { key: string; value: string; } /** Send a Facebook token to the server. Used with authenticate/link/unlink. */ export interface AccountFacebook { /** The OAuth token received from Facebook to access their profile API. */ token: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountFacebook_VarsEntry { key: string; value: string; } /** Send a Facebook Instant Game token to the server. Used with authenticate/link/unlink. */ export interface AccountFacebookInstantGame { /** The OAuth token received from a Facebook Instant Game that may be decoded with the Application Secret (must be available with the nakama configuration) */ signed_player_info: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountFacebookInstantGame_VarsEntry { key: string; value: string; } /** Send Apple's Game Center account credentials to the server. Used with authenticate/link/unlink. */ export interface AccountGameCenter { /** Player ID (generated by GameCenter). */ player_id: string; /** Bundle ID (generated by GameCenter). */ bundle_id: string; /** Time since UNIX epoch when the signature was created. */ timestamp_seconds: number; /** A random "NSString" used to compute the hash and keep it randomized. */ salt: string; /** The verification signature data generated. */ signature: string; /** The URL for the public encryption key. */ public_key_url: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountGameCenter_VarsEntry { key: string; value: string; } /** Send a Google token to the server. Used with authenticate/link/unlink. */ export interface AccountGoogle { /** The OAuth token received from Google to access their profile API. */ token: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountGoogle_VarsEntry { key: string; value: string; } /** Send a Steam token to the server. Used with authenticate/link/unlink. */ export interface AccountSteam { /** The account token received from Steam to access their profile API. */ token: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface AccountSteam_VarsEntry { key: string; value: string; } /** Add one or more friends to the current user. */ export interface AddFriendsRequest { /** The account id of a user. */ ids: string[]; /** The account username of a user. */ usernames: string[]; } /** Add users to a group. */ export interface AddGroupUsersRequest { /** The group to add users to. */ group_id: string; /** The users to add. */ user_ids: string[]; } /** Authenticate against the server with a refresh token. */ export interface SessionRefreshRequest { /** Refresh token. */ token: string; /** Extra information that will be bundled in the session token. */ vars: { [key: string]: string }; } export interface SessionRefreshRequest_VarsEntry { key: string; value: string; } /** Log out a session, invalidate a refresh token, or log out all sessions/refresh tokens for a user. */ export interface SessionLogoutRequest { /** Session token to log out. */ token: string; /** Refresh token to invalidate. */ refresh_token: string; } /** Authenticate against the server with Apple Sign In. */ export interface AuthenticateAppleRequest { /** The Apple account details. */ account?: AccountApple; /** Register the account if the user does not already exist. */ create?: boolean; /** Set the username on the account at register. Must be unique. */ username: string; } /** Authenticate against the server with a custom ID. */ export interface AuthenticateCustomRequest { /** The custom account details. */ account?: AccountCustom; /** Register the account if the user does not already exist. */ create?: boolean; /** Set the username on the account at register. Must be unique. */ username: string; } /** Authenticate against the server with a device ID. */ export interface AuthenticateDeviceRequest { /** The device account details. */ account?: AccountDevice; /** Register the account if the user does not already exist. */ create?: boolean; /** Set the username on the account at register. Must be unique. */ username: string; } /** Authenticate against the server with email+password. */ export interface AuthenticateEmailRequest { /** The email account details. */ account?: AccountEmail; /** Register the account if the user does not already exist. */ create?: boolean; /** Set the username on the account at register. Must be unique. */ username: string; } /** Authenticate against the server with Facebook. */ export interface AuthenticateFacebookRequest { /** The Facebook account details. */ account?: AccountFacebook; /** Register the account if the user does not already exist. */ create?: boolean; /** Set the username on the account at register. Must be unique. */ username: string; /** Import Facebook friends for the user. */ sync?: boolean; } /** Authenticate against the server with Facebook Instant Game token. */ export interface AuthenticateFacebookInstantGameRequest { /** The Facebook Instant Game account details. */ account?: AccountFacebookInstantGame; /** Register the account if the user does not already exist. */ create?: boolean; /** Set the username on the account at register. Must be unique. */ username: string; } /** Authenticate against the server with Apple's Game Center. */ export interface AuthenticateGameCenterRequest { /** The Game Center account details. */ account?: AccountGameCenter; /** Register the account if the user does not already exist. */ create?: boolean; /** Set the username on the account at register. Must be unique. */ username: string; } /** Authenticate against the server with Google. */ export interface AuthenticateGoogleRequest { /** The Google account details. */ account?: AccountGoogle; /** Register the account if the user does not already exist. */ create?: boolean; /** Set the username on the account at register. Must be unique. */ username: string; } /** Authenticate against the server with Steam. */ export interface AuthenticateSteamRequest { /** The Steam account details. */ account?: AccountSteam; /** Register the account if the user does not already exist. */ create?: boolean; /** Set the username on the account at register. Must be unique. */ username: string; /** Import Steam friends for the user. */ sync?: boolean; } /** Ban users from a group. */ export interface BanGroupUsersRequest { /** The group to ban users from. */ group_id: string; /** The users to ban. */ user_ids: string[]; } /** Block one or more friends for the current user. */ export interface BlockFriendsRequest { /** The account id of a user. */ ids: string[]; /** The account username of a user. */ usernames: string[]; } /** A message sent on a channel. */ export interface ChannelMessage { /** The channel this message belongs to. */ channel_id: string; /** The unique ID of this message. */ message_id: string; /** The code representing a message type or category. */ code?: number; /** Message sender, usually a user ID. */ sender_id: string; /** The username of the message sender, if any. */ username: string; /** The content payload. */ content: string; /** The UNIX time when the message was created. */ create_time?: Date; /** The UNIX time when the message was last updated. */ update_time?: Date; /** True if the message was persisted to the channel's history, false otherwise. */ persistent?: boolean; /** The name of the chat room, or an empty string if this message was not sent through a chat room. */ room_name: string; /** The ID of the group, or an empty string if this message was not sent through a group channel. */ group_id: string; /** The ID of the first DM user, or an empty string if this message was not sent through a DM chat. */ user_id_one: string; /** The ID of the second DM user, or an empty string if this message was not sent through a DM chat. */ user_id_two: string; } /** A list of channel messages, usually a result of a list operation. */ export interface ChannelMessageList { /** A list of messages. */ messages: ChannelMessage[]; /** The cursor to send when retrieving the next page, if any. */ next_cursor: string; /** The cursor to send when retrieving the previous page, if any. */ prev_cursor: string; /** Cacheable cursor to list newer messages. Durable and designed to be stored, unlike next/prev cursors. */ cacheable_cursor: string; } /** Create a group with the current user as owner. */ export interface CreateGroupRequest { /** A unique name for the group. */ name: string; /** A description for the group. */ description: string; /** The language expected to be a tag which follows the BCP-47 spec. */ lang_tag: string; /** A URL for an avatar image. */ avatar_url: string; /** Mark a group as open or not where only admins can accept members. */ open: boolean; /** Maximum number of group members. */ max_count: number; } /** Delete one or more friends for the current user. */ export interface DeleteFriendsRequest { /** The account id of a user. */ ids: string[]; /** The account username of a user. */ usernames: string[]; } /** Delete a group the user has access to. */ export interface DeleteGroupRequest { /** The id of a group. */ group_id: string; } /** Delete a leaderboard record. */ export interface DeleteLeaderboardRecordRequest { /** The leaderboard ID to delete from. */ leaderboard_id: string; } /** Delete one or more notifications for the current user. */ export interface DeleteNotificationsRequest { /** The id of notifications. */ ids: string[]; } /** Storage objects to delete. */ export interface DeleteStorageObjectId { /** The collection which stores the object. */ collection: string; /** The key of the object within the collection. */ key: string; /** The version hash of the object. */ version: string; } /** Batch delete storage objects. */ export interface DeleteStorageObjectsRequest { /** Batch of storage objects. */ object_ids: DeleteStorageObjectId[]; } /** Represents an event to be passed through the server to registered event handlers. */ export interface Event { /** An event name, type, category, or identifier. */ name: string; /** Arbitrary event property values. */ properties: { [key: string]: string }; /** The time when the event was triggered. */ timestamp?: Date; /** True if the event came directly from a client call, false otherwise. */ external: boolean; } export interface Event_PropertiesEntry { key: string; value: string; } /** A friend of a user. */ export interface Friend { /** The user object. */ user?: User; /** The friend status. */ state?: number; /** Time of the latest relationship update. */ update_time?: Date; } /** The friendship status. */ export enum Friend_State { /** FRIEND - The user is a friend of the current user. */ FRIEND = 0, /** INVITE_SENT - The current user has sent an invite to the user. */ INVITE_SENT = 1, /** INVITE_RECEIVED - The current user has received an invite from this user. */ INVITE_RECEIVED = 2, /** BLOCKED - The current user has blocked this user. */ BLOCKED = 3, UNRECOGNIZED = -1, } export function friend_StateFromJSON(object: any): Friend_State { switch (object) { case 0: case "FRIEND": return Friend_State.FRIEND; case 1: case "INVITE_SENT": return Friend_State.INVITE_SENT; case 2: case "INVITE_RECEIVED": return Friend_State.INVITE_RECEIVED; case 3: case "BLOCKED": return Friend_State.BLOCKED; case -1: case "UNRECOGNIZED": default: return Friend_State.UNRECOGNIZED; } } export function friend_StateToJSON(object: Friend_State): string { switch (object) { case Friend_State.FRIEND: return "FRIEND"; case Friend_State.INVITE_SENT: return "INVITE_SENT"; case Friend_State.INVITE_RECEIVED: return "INVITE_RECEIVED"; case Friend_State.BLOCKED: return "BLOCKED"; default: return "UNKNOWN"; } } /** A collection of zero or more friends of the user. */ export interface FriendList { /** The Friend objects. */ friends: Friend[]; /** Cursor for the next page of results, if any. */ cursor: string; } /** Fetch a batch of zero or more users from the server. */ export interface GetUsersRequest { /** The account id of a user. */ ids: string[]; /** The account username of a user. */ usernames: string[]; /** The Facebook ID of a user. */ facebook_ids: string[]; } /** A group in the server. */ export interface Group { /** The id of a group. */ id: string; /** The id of the user who created the group. */ creator_id: string; /** The unique name of the group. */ name: string; /** A description for the group. */ description: string; /** The language expected to be a tag which follows the BCP-47 spec. */ lang_tag: string; /** Additional information stored as a JSON object. */ metadata: string; /** A URL for an avatar image. */ avatar_url: string; /** Anyone can join open groups, otherwise only admins can accept members. */ open?: boolean; /** The current count of all members in the group. */ edge_count: number; /** The maximum number of members allowed. */ max_count: number; /** The UNIX time when the group was created. */ create_time?: Date; /** The UNIX time when the group was last updated. */ update_time?: Date; } /** One or more groups returned from a listing operation. */ export interface GroupList { /** One or more groups. */ groups: Group[]; /** A cursor used to get the next page. */ cursor: string; } /** A list of users belonging to a group, along with their role. */ export interface GroupUserList { /** User-role pairs for a group. */ group_users: GroupUserList_GroupUser[]; /** Cursor for the next page of results, if any. */ cursor: string; } /** A single user-role pair. */ export interface GroupUserList_GroupUser { /** User. */ user?: User; /** Their relationship to the group. */ state?: number; } /** The group role status. */ export enum GroupUserList_GroupUser_State { /** SUPERADMIN - The user is a superadmin with full control of the group. */ SUPERADMIN = 0, /** ADMIN - The user is an admin with additional privileges. */ ADMIN = 1, /** MEMBER - The user is a regular member. */ MEMBER = 2, /** JOIN_REQUEST - The user has requested to join the group */ JOIN_REQUEST = 3, UNRECOGNIZED = -1, } export function groupUserList_GroupUser_StateFromJSON( object: any ): GroupUserList_GroupUser_State { switch (object) { case 0: case "SUPERADMIN": return GroupUserList_GroupUser_State.SUPERADMIN; case 1: case "ADMIN": return GroupUserList_GroupUser_State.ADMIN; case 2: case "MEMBER": return GroupUserList_GroupUser_State.MEMBER; case 3: case "JOIN_REQUEST": return GroupUserList_GroupUser_State.JOIN_REQUEST; case -1: case "UNRECOGNIZED": default: return GroupUserList_GroupUser_State.UNRECOGNIZED; } } export function groupUserList_GroupUser_StateToJSON( object: GroupUserList_GroupUser_State ): string { switch (object) { case GroupUserList_GroupUser_State.SUPERADMIN: return "SUPERADMIN"; case GroupUserList_GroupUser_State.ADMIN: return "ADMIN"; case GroupUserList_GroupUser_State.MEMBER: return "MEMBER"; case GroupUserList_GroupUser_State.JOIN_REQUEST: return "JOIN_REQUEST"; default: return "UNKNOWN"; } } /** Import Facebook friends into the current user's account. */ export interface ImportFacebookFriendsRequest { /** The Facebook account details. */ account?: AccountFacebook; /** Reset the current user's friends list. */ reset?: boolean; } /** Import Facebook friends into the current user's account. */ export interface ImportSteamFriendsRequest { /** The Facebook account details. */ account?: AccountSteam; /** Reset the current user's friends list. */ reset?: boolean; } /** Immediately join an open group, or request to join a closed one. */ export interface JoinGroupRequest { /** The group ID to join. The group must already exist. */ group_id: string; } /** The request to join a tournament. */ export interface JoinTournamentRequest { /** The ID of the tournament to join. The tournament must already exist. */ tournament_id: string; } /** Kick a set of users from a group. */ export interface KickGroupUsersRequest { /** The group ID to kick from. */ group_id: string; /** The users to kick. */ user_ids: string[]; } /** Represents a complete leaderboard record with all scores and associated metadata. */ export interface LeaderboardRecord { /** The ID of the leaderboard this score belongs to. */ leaderboard_id: string; /** The ID of the score owner, usually a user or group. */ owner_id: string; /** The username of the score owner, if the owner is a user. */ username?: string; /** The score value. */ score: number; /** An optional subscore value. */ subscore: number; /** The number of submissions to this score record. */ num_score: number; /** Metadata. */ metadata: string; /** The UNIX time when the leaderboard record was created. */ create_time?: Date; /** The UNIX time when the leaderboard record was updated. */ update_time?: Date; /** The UNIX time when the leaderboard record expires. */ expiry_time?: Date; /** The rank of this record. */ rank: number; /** The maximum number of score updates allowed by the owner. */ max_num_score: number; } /** A set of leaderboard records, may be part of a leaderboard records page or a batch of individual records. */ export interface LeaderboardRecordList { /** A list of leaderboard records. */ records: LeaderboardRecord[]; /** A batched set of leaderboard records belonging to specified owners. */ owner_records: LeaderboardRecord[]; /** The cursor to send when retrieving the next page, if any. */ next_cursor: string; /** The cursor to send when retrieving the previous page, if any. */ prev_cursor: string; } /** Leave a group. */ export interface LeaveGroupRequest { /** The group ID to leave. */ group_id: string; } /** Link Facebook to the current user's account. */ export interface LinkFacebookRequest { /** The Facebook account details. */ account?: AccountFacebook; /** Import Facebook friends for the user. */ sync?: boolean; } /** Link Steam to the current user's account. */ export interface LinkSteamRequest { /** The Facebook account details. */ account?: AccountSteam; /** Import Steam friends for the user. */ sync?: boolean; } /** List a channel's message history. */ export interface ListChannelMessagesRequest { /** The channel ID to list from. */ channel_id: string; /** Max number of records to return. Between 1 and 100. */ limit?: number; /** True if listing should be older messages to newer, false if reverse. */ forward?: boolean; /** A pagination cursor, if any. */ cursor: string; } /** List friends for a user. */ export interface ListFriendsRequest { /** Max number of records to return. Between 1 and 100. */ limit?: number; /** The friend state to list. */ state?: number; /** An optional next page cursor. */ cursor: string; } /** List groups based on given filters. */ export interface ListGroupsRequest { /** List groups that contain this value in their names. */ name: string; /** Optional pagination cursor. */ cursor: string; /** Max number of groups to return. Between 1 and 100. */ limit?: number; } /** List all users that are part of a group. */ export interface ListGroupUsersRequest { /** The group ID to list from. */ group_id: string; /** Max number of records to return. Between 1 and 100. */ limit?: number; /** The group user state to list. */ state?: number; /** An optional next page cursor. */ cursor: string; } /** List leaerboard records from a given leaderboard around the owner. */ export interface ListLeaderboardRecordsAroundOwnerRequest { /** The ID of the tournament to list for. */ leaderboard_id: string; /** Max number of records to return. Between 1 and 100. */ limit?: number; /** The owner to retrieve records around. */ owner_id: string; /** Expiry in seconds (since epoch) to begin fetching records from. */ expiry?: number; } /** List leaderboard records from a given leaderboard. */ export interface ListLeaderboardRecordsRequest { /** The ID of the leaderboard to list for. */ leaderboard_id: string; /** One or more owners to retrieve records for. */ owner_ids: string[]; /** Max number of records to return. Between 1 and 100. */ limit?: number; /** A next or previous page cursor. */ cursor: string; /** Expiry in seconds (since epoch) to begin fetching records from. Optional. 0 means from current time. */ expiry?: number; } /** List realtime matches. */ export interface ListMatchesRequest { /** Limit the number of returned matches. */ limit?: number; /** Authoritative or relayed matches. */ authoritative?: boolean; /** Label filter. */ label?: string; /** Minimum user count. */ min_size?: number; /** Maximum user count. */ max_size?: number; /** Arbitrary label query. */ query?: string; } /** Get a list of unexpired notifications. */ export interface ListNotificationsRequest { /** The number of notifications to get. Between 1 and 100. */ limit?: number; /** A cursor to page through notifications. May be cached by clients to get from point in time forwards. */ cacheable_cursor: string; } /** List publicly readable storage objects in a given collection. */ export interface ListStorageObjectsRequest { /** ID of the user. */ user_id: string; /** The collection which stores the object. */ collection: string; /** The number of storage objects to list. Between 1 and 100. */ limit?: number; /** The cursor to page through results from. */ cursor: string; } /** List tournament records from a given tournament around the owner. */ export interface ListTournamentRecordsAroundOwnerRequest { /** The ID of the tournament to list for. */ tournament_id: string; /** Max number of records to return. Between 1 and 100. */ limit?: number; /** The owner to retrieve records around. */ owner_id: string; /** Expiry in seconds (since epoch) to begin fetching records from. */ expiry?: number; } /** List tournament records from a given tournament. */ export interface ListTournamentRecordsRequest { /** The ID of the tournament to list for. */ tournament_id: string; /** One or more owners to retrieve records for. */ owner_ids: string[]; /** Max number of records to return. Between 1 and 100. */ limit?: number; /** A next or previous page cursor. */ cursor: string; /** Expiry in seconds (since epoch) to begin fetching records from. */ expiry?: number; } /** List active/upcoming tournaments based on given filters. */ export interface ListTournamentsRequest { /** The start of the categories to include. Defaults to 0. */ category_start?: number; /** The end of the categories to include. Defaults to 128. */ category_end?: number; /** The start time for tournaments. Defaults to epoch. */ start_time?: number; /** The end time for tournaments. Defaults to +1 year from current Unix time. */ end_time?: number; /** Max number of records to return. Between 1 and 100. */ limit?: number; /** A next page cursor for listings (optional). */ cursor: string; } /** List the groups a user is part of, and their relationship to each. */ export interface ListUserGroupsRequest { /** ID of the user. */ user_id: string; /** Max number of records to return. Between 1 and 100. */ limit?: number; /** The user group state to list. */ state?: number; /** An optional next page cursor. */ cursor: string; } /** Represents a realtime match. */ export interface Match { /** The ID of the match, can be used to join. */ match_id: string; /** True if it's an server-managed authoritative match, false otherwise. */ authoritative: boolean; /** Match label, if any. */ label?: string; /** Current number of users in the match. */ size: number; /** Tick Rate */ tick_rate: number; /** Handler name */ handler_name: string; } /** A list of realtime matches. */ export interface MatchList { /** A number of matches corresponding to a list operation. */ matches: Match[]; } /** A notification in the server. */ export interface Notification { /** ID of the Notification. */ id: string; /** Subject of the notification. */ subject: string; /** Content of the notification in JSON. */ content: string; /** Category code for this notification. */ code: number; /** ID of the sender, if a user. Otherwise 'null'. */ sender_id: string; /** The UNIX time when the notification was created. */ create_time?: Date; /** True if this notification was persisted to the database. */ persistent: boolean; } /** A collection of zero or more notifications. */ export interface NotificationList { /** Collection of notifications. */ notifications: Notification[]; /** Use this cursor to paginate notifications. Cache this to catch up to new notifications. */ cacheable_cursor: string; } /** Promote a set of users in a group to the next role up. */ export interface PromoteGroupUsersRequest { /** The group ID to promote in. */ group_id: string; /** The users to promote. */ user_ids: string[]; } /** Demote a set of users in a group to the next role down. */ export interface DemoteGroupUsersRequest { /** The group ID to demote in. */ group_id: string; /** The users to demote. */ user_ids: string[]; } /** Storage objects to get. */ export interface ReadStorageObjectId { /** The collection which stores the object. */ collection: string; /** The key of the object within the collection. */ key: string; /** The user owner of the object. */ user_id: string; } /** Batch get storage objects. */ export interface ReadStorageObjectsRequest { /** Batch of storage objects. */ object_ids: ReadStorageObjectId[]; } /** Execute an Lua function on the server. */ export interface Rpc { /** The identifier of the function. */ id: string; /** The payload of the function which must be a JSON object. */ payload: string; /** The authentication key used when executed as a non-client HTTP request. */ http_key: string; } /** A user's session used to authenticate messages. */ export interface Session { /** True if the corresponding account was just created, false otherwise. */ created: boolean; /** Authentication credentials. */ token: string; /** Refresh token that can be used for session token renewal. */ refresh_token: string; } /** An object within the storage engine. */ export interface StorageObject { /** The collection which stores the object. */ collection: string; /** The key of the object within the collection. */ key: string; /** The user owner of the object. */ user_id: string; /** The value of the object. */ value: string; /** The version hash of the object. */ version: string; /** The read access permissions for the object. */ permission_read: number; /** The write access permissions for the object. */ permission_write: number; /** The UNIX time when the object was created. */ create_time?: Date; /** The UNIX time when the object was last updated. */ update_time?: Date; } /** A storage acknowledgement. */ export interface StorageObjectAck { /** The collection which stores the object. */ collection: string; /** The key of the object within the collection. */ key: string; /** The version hash of the object. */ version: string; /** The owner of the object. */ user_id: string; } /** Batch of acknowledgements for the storage object write. */ export interface StorageObjectAcks { /** Batch of storage write acknowledgements. */ acks: StorageObjectAck[]; } /** Batch of storage objects. */ export interface StorageObjects { /** The batch of storage objects. */ objects: StorageObject[]; } /** List of storage objects. */ export interface StorageObjectList { /** The list of storage objects. */ objects: StorageObject[]; /** The cursor for the next page of results, if any. */ cursor: string; } /** A tournament on the server. */ export interface Tournament { /** The ID of the tournament. */ id: string; /** The title for the tournament. */ title: string; /** The description of the tournament. May be blank. */ description: string; /** The category of the tournament. e.g. "vip" could be category 1. */ category: number; /** ASC or DESC sort mode of scores in the tournament. */ sort_order: number; /** The current number of players in the tournament. */ size: number; /** The maximum number of players for the tournament. */ max_size: number; /** The maximum score updates allowed per player for the current tournament. */ max_num_score: number; /** True if the tournament is active and can enter. A computed value. */ can_enter: boolean; /** The UNIX time when the tournament stops being active until next reset. A computed value. */ end_active: number; /** The UNIX time when the tournament is next playable. A computed value. */ next_reset: number; /** Additional information stored as a JSON object. */ metadata: string; /** The UNIX time when the tournament was created. */ create_time?: Date; /** The UNIX time when the tournament will start. */ start_time?: Date; /** The UNIX time when the tournament will be stopped. */ end_time?: Date; /** Duration of the tournament in seconds. */ duration: number; /** The UNIX time when the tournament start being active. A computed value. */ start_active: number; } /** A list of tournaments. */ export interface TournamentList { /** The list of tournaments returned. */ tournaments: Tournament[]; /** A pagination cursor (optional). */ cursor: string; } /** A set of tournament records which may be part of a tournament records page or a batch of individual records. */ export interface TournamentRecordList { /** A list of tournament records. */ records: LeaderboardRecord[]; /** A batched set of tournament records belonging to specified owners. */ owner_records: LeaderboardRecord[]; /** The cursor to send when retireving the next page (optional). */ next_cursor: string; /** The cursor to send when retrieving the previous page (optional). */ prev_cursor: string; } /** Update a user's account details. */ export interface UpdateAccountRequest { /** The username of the user's account. */ username?: string; /** The display name of the user. */ display_name?: string; /** A URL for an avatar image. */ avatar_url?: string; /** The language expected to be a tag which follows the BCP-47 spec. */ lang_tag?: string; /** The location set by the user. */ location?: string; /** The timezone set by the user. */ timezone?: string; } /** Update fields in a given group. */ export interface UpdateGroupRequest { /** The ID of the group to update. */ group_id: string; /** Name. */ name?: string; /** Description string. */ description?: string; /** Lang tag. */ lang_tag?: string; /** Avatar URL. */ avatar_url?: string; /** Open is true if anyone should be allowed to join, or false if joins must be approved by a group admin. */ open?: boolean; } /** A user in the server. */ export interface User { /** The id of the user's account. */ id: string; /** The username of the user's account. */ username: string; /** The display name of the user. */ display_name: string; /** A URL for an avatar image. */ avatar_url: string; /** The language expected to be a tag which follows the BCP-47 spec. */ lang_tag: string; /** The location set by the user. */ location: string; /** The timezone set by the user. */ timezone: string; /** Additional information stored as a JSON object. */ metadata: string; /** The Facebook id in the user's account. */ facebook_id: string; /** The Google id in the user's account. */ google_id: string; /** The Apple Game Center in of the user's account. */ gamecenter_id: string; /** The Steam id in the user's account. */ steam_id: string; /** Indicates whether the user is currently online. */ online: boolean; /** Number of related edges to this user. */ edge_count: number; /** The UNIX time when the user was created. */ create_time?: Date; /** The UNIX time when the user was last updated. */ update_time?: Date; /** The Facebook Instant Game ID in the user's account. */ facebook_instant_game_id: string; /** The Apple Sign In ID in the user's account. */ apple_id: string; } /** A list of groups belonging to a user, along with the user's role in each group. */ export interface UserGroupList { /** Group-role pairs for a user. */ user_groups: UserGroupList_UserGroup[]; /** Cursor for the next page of results, if any. */ cursor: string; } /** A single group-role pair. */ export interface UserGroupList_UserGroup { /** Group. */ group?: Group; /** The user's relationship to the group. */ state?: number; } /** The group role status. */ export enum UserGroupList_UserGroup_State { /** SUPERADMIN - The user is a superadmin with full control of the group. */ SUPERADMIN = 0, /** ADMIN - The user is an admin with additional privileges. */ ADMIN = 1, /** MEMBER - The user is a regular member. */ MEMBER = 2, /** JOIN_REQUEST - The user has requested to join the group */ JOIN_REQUEST = 3, UNRECOGNIZED = -1, } export function userGroupList_UserGroup_StateFromJSON( object: any ): UserGroupList_UserGroup_State { switch (object) { case 0: case "SUPERADMIN": return UserGroupList_UserGroup_State.SUPERADMIN; case 1: case "ADMIN": return UserGroupList_UserGroup_State.ADMIN; case 2: case "MEMBER": return UserGroupList_UserGroup_State.MEMBER; case 3: case "JOIN_REQUEST": return UserGroupList_UserGroup_State.JOIN_REQUEST; case -1: case "UNRECOGNIZED": default: return UserGroupList_UserGroup_State.UNRECOGNIZED; } } export function userGroupList_UserGroup_StateToJSON( object: UserGroupList_UserGroup_State ): string { switch (object) { case UserGroupList_UserGroup_State.SUPERADMIN: return "SUPERADMIN"; case UserGroupList_UserGroup_State.ADMIN: return "ADMIN"; case UserGroupList_UserGroup_State.MEMBER: return "MEMBER"; case UserGroupList_UserGroup_State.JOIN_REQUEST: return "JOIN_REQUEST"; default: return "UNKNOWN"; } } /** A collection of zero or more users. */ export interface Users { /** The User objects. */ users: User[]; } /** Apple IAP Purchases validation request */ export interface ValidatePurchaseAppleRequest { /** Base64 encoded Apple receipt data payload. */ receipt: string; } /** Google IAP Purchase validation request */ export interface ValidatePurchaseGoogleRequest { /** JSON encoded Google purchase payload. */ purchase: string; } /** Huawei IAP Purchase validation request */ export interface ValidatePurchaseHuaweiRequest { /** JSON encoded Huawei InAppPurchaseData. */ purchase: string; /** InAppPurchaseData signature. */ signature: string; } /** Validated Purchase stored by Nakama. */ export interface ValidatedPurchase { /** Purchase Product ID. */ product_id: string; /** Purchase Transaction ID. */ transaction_id: string; /** Store identifier */ store: ValidatedPurchase_Store; /** UNIX Timestamp when the purchase was done. */ purchase_time?: Date; /** UNIX Timestamp when the receipt validation was stored in DB. */ create_time?: Date; /** UNIX Timestamp when the receipt validation was updated in DB. */ update_time?: Date; /** Raw provider validation response. */ provider_response: string; /** Whether the purchase was done in production or sandbox environment. */ environment: ValidatedPurchase_Environment; } /** Validation Provider */ export enum ValidatedPurchase_Store { /** APPLE_APP_STORE - Apple App Store */ APPLE_APP_STORE = 0, /** GOOGLE_PLAY_STORE - Google Play Store */ GOOGLE_PLAY_STORE = 1, /** HUAWEI_APP_GALLERY - Huawei App Gallery */ HUAWEI_APP_GALLERY = 2, UNRECOGNIZED = -1, } export function validatedPurchase_StoreFromJSON( object: any ): ValidatedPurchase_Store { switch (object) { case 0: case "APPLE_APP_STORE": return ValidatedPurchase_Store.APPLE_APP_STORE; case 1: case "GOOGLE_PLAY_STORE": return ValidatedPurchase_Store.GOOGLE_PLAY_STORE; case 2: case "HUAWEI_APP_GALLERY": return ValidatedPurchase_Store.HUAWEI_APP_GALLERY; case -1: case "UNRECOGNIZED": default: return ValidatedPurchase_Store.UNRECOGNIZED; } } export function validatedPurchase_StoreToJSON( object: ValidatedPurchase_Store ): string { switch (object) { case ValidatedPurchase_Store.APPLE_APP_STORE: return "APPLE_APP_STORE"; case ValidatedPurchase_Store.GOOGLE_PLAY_STORE: return "GOOGLE_PLAY_STORE"; case ValidatedPurchase_Store.HUAWEI_APP_GALLERY: return "HUAWEI_APP_GALLERY"; default: return "UNKNOWN"; } } /** Environment where the purchase took place */ export enum ValidatedPurchase_Environment { /** UNKNOWN - Unknown environment. */ UNKNOWN = 0, /** SANDBOX - Sandbox/test environment. */ SANDBOX = 1, /** PRODUCTION - Production environment. */ PRODUCTION = 2, UNRECOGNIZED = -1, } export function validatedPurchase_EnvironmentFromJSON( object: any ): ValidatedPurchase_Environment { switch (object) { case 0: case "UNKNOWN": return ValidatedPurchase_Environment.UNKNOWN; case 1: case "SANDBOX": return ValidatedPurchase_Environment.SANDBOX; case 2: case "PRODUCTION": return ValidatedPurchase_Environment.PRODUCTION; case -1: case "UNRECOGNIZED": default: return ValidatedPurchase_Environment.UNRECOGNIZED; } } export function validatedPurchase_EnvironmentToJSON( object: ValidatedPurchase_Environment ): string { switch (object) { case ValidatedPurchase_Environment.UNKNOWN: return "UNKNOWN"; case ValidatedPurchase_Environment.SANDBOX: return "SANDBOX"; case ValidatedPurchase_Environment.PRODUCTION: return "PRODUCTION"; default: return "UNKNOWN"; } } /** Validate IAP response */ export interface ValidatePurchaseResponse { /** Newly seen validated purchases. */ validated_purchases: ValidatedPurchase[]; } /** A list of validated purchases stored by Nakama. */ export interface PurchaseList { /** Stored validated purchases. */ validated_purchases: ValidatedPurchase[]; /** The cursor to send when retrieving the next page, if any. */ cursor: string; } /** A request to submit a score to a leaderboard. */ export interface WriteLeaderboardRecordRequest { /** The ID of the leaderboard to write to. */ leaderboard_id: string; /** Record input. */ record?: WriteLeaderboardRecordRequest_LeaderboardRecordWrite; } /** Record values to write. */ export interface WriteLeaderboardRecordRequest_LeaderboardRecordWrite { /** The score value to submit. */ score: number; /** An optional secondary value. */ subscore: number; /** Optional record metadata. */ metadata: string; /** Operator override. */ operator: OverrideOperator; } /** The object to store. */ export interface WriteStorageObject { /** The collection to store the object. */ collection: string; /** The key for the object within the collection. */ key: string; /** The value of the object. */ value: string; /** The version hash of the object to check. Possible values are: ["", "*", "#hash#"]. */ version: string; /** The read access permissions for the object. */ permission_read?: number; /** The write access permissions for the object. */ permission_write?: number; } /** Write objects to the storage engine. */ export interface WriteStorageObjectsRequest { /** The objects to store on the server. */ objects: WriteStorageObject[]; } /** A request to submit a score to a tournament. */ export interface WriteTournamentRecordRequest { /** The tournament ID to write the record for. */ tournament_id: string; /** Record input. */ record?: WriteTournamentRecordRequest_TournamentRecordWrite; } /** Record values to write. */ export interface WriteTournamentRecordRequest_TournamentRecordWrite { /** The score value to submit. */ score: number; /** An optional secondary value. */ subscore: number; /** A JSON object of additional properties (optional). */ metadata: string; /** Operator override. */ operator: OverrideOperator; } const baseAccount: object = { wallet: "", email: "", custom_id: "" }; export const Account = { encode( message: Account, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.user !== undefined) { User.encode(message.user, writer.uint32(10).fork()).ldelim(); } if (message.wallet !== "") { writer.uint32(18).string(message.wallet); } if (message.email !== "") { writer.uint32(26).string(message.email); } for (const v of message.devices) { AccountDevice.encode(v!, writer.uint32(34).fork()).ldelim(); } if (message.custom_id !== "") { writer.uint32(42).string(message.custom_id); } if (message.verify_time !== undefined) { Timestamp.encode( toTimestamp(message.verify_time), writer.uint32(50).fork() ).ldelim(); } if (message.disable_time !== undefined) { Timestamp.encode( toTimestamp(message.disable_time), writer.uint32(58).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Account { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccount } as Account; message.devices = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.user = User.decode(reader, reader.uint32()); break; case 2: message.wallet = reader.string(); break; case 3: message.email = reader.string(); break; case 4: message.devices.push(AccountDevice.decode(reader, reader.uint32())); break; case 5: message.custom_id = reader.string(); break; case 6: message.verify_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 7: message.disable_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Account { const message = { ...baseAccount } as Account; message.devices = []; if (object.user !== undefined && object.user !== null) { message.user = User.fromJSON(object.user); } if (object.wallet !== undefined && object.wallet !== null) { message.wallet = String(object.wallet); } if (object.email !== undefined && object.email !== null) { message.email = String(object.email); } if (object.devices !== undefined && object.devices !== null) { for (const e of object.devices) { message.devices.push(AccountDevice.fromJSON(e)); } } if (object.custom_id !== undefined && object.custom_id !== null) { message.custom_id = String(object.custom_id); } if (object.verify_time !== undefined && object.verify_time !== null) { message.verify_time = fromJsonTimestamp(object.verify_time); } if (object.disable_time !== undefined && object.disable_time !== null) { message.disable_time = fromJsonTimestamp(object.disable_time); } return message; }, toJSON(message: Account): unknown { const obj: any = {}; message.user !== undefined && (obj.user = message.user ? User.toJSON(message.user) : undefined); message.wallet !== undefined && (obj.wallet = message.wallet); message.email !== undefined && (obj.email = message.email); if (message.devices) { obj.devices = message.devices.map((e) => e ? AccountDevice.toJSON(e) : undefined ); } else { obj.devices = []; } message.custom_id !== undefined && (obj.custom_id = message.custom_id); message.verify_time !== undefined && (obj.verify_time = message.verify_time.toISOString()); message.disable_time !== undefined && (obj.disable_time = message.disable_time.toISOString()); return obj; }, fromPartial(object: DeepPartial<Account>): Account { const message = { ...baseAccount } as Account; message.devices = []; if (object.user !== undefined && object.user !== null) { message.user = User.fromPartial(object.user); } if (object.wallet !== undefined && object.wallet !== null) { message.wallet = object.wallet; } if (object.email !== undefined && object.email !== null) { message.email = object.email; } if (object.devices !== undefined && object.devices !== null) { for (const e of object.devices) { message.devices.push(AccountDevice.fromPartial(e)); } } if (object.custom_id !== undefined && object.custom_id !== null) { message.custom_id = object.custom_id; } if (object.verify_time !== undefined && object.verify_time !== null) { message.verify_time = object.verify_time; } if (object.disable_time !== undefined && object.disable_time !== null) { message.disable_time = object.disable_time; } return message; }, }; const baseAccountRefresh: object = { token: "" }; export const AccountRefresh = { encode( message: AccountRefresh, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.token !== "") { writer.uint32(10).string(message.token); } Object.entries(message.vars).forEach(([key, value]) => { AccountRefresh_VarsEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AccountRefresh { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountRefresh } as AccountRefresh; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.token = reader.string(); break; case 2: const entry2 = AccountRefresh_VarsEntry.decode( reader, reader.uint32() ); if (entry2.value !== undefined) { message.vars[entry2.key] = entry2.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountRefresh { const message = { ...baseAccountRefresh } as AccountRefresh; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = String(object.token); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountRefresh): unknown { const obj: any = {}; message.token !== undefined && (obj.token = message.token); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<AccountRefresh>): AccountRefresh { const message = { ...baseAccountRefresh } as AccountRefresh; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = object.token; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountRefresh_VarsEntry: object = { key: "", value: "" }; export const AccountRefresh_VarsEntry = { encode( message: AccountRefresh_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountRefresh_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountRefresh_VarsEntry, } as AccountRefresh_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountRefresh_VarsEntry { const message = { ...baseAccountRefresh_VarsEntry, } as AccountRefresh_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountRefresh_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountRefresh_VarsEntry> ): AccountRefresh_VarsEntry { const message = { ...baseAccountRefresh_VarsEntry, } as AccountRefresh_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAccountApple: object = { token: "" }; export const AccountApple = { encode( message: AccountApple, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.token !== "") { writer.uint32(10).string(message.token); } Object.entries(message.vars).forEach(([key, value]) => { AccountApple_VarsEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AccountApple { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountApple } as AccountApple; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.token = reader.string(); break; case 2: const entry2 = AccountApple_VarsEntry.decode(reader, reader.uint32()); if (entry2.value !== undefined) { message.vars[entry2.key] = entry2.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountApple { const message = { ...baseAccountApple } as AccountApple; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = String(object.token); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountApple): unknown { const obj: any = {}; message.token !== undefined && (obj.token = message.token); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<AccountApple>): AccountApple { const message = { ...baseAccountApple } as AccountApple; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = object.token; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountApple_VarsEntry: object = { key: "", value: "" }; export const AccountApple_VarsEntry = { encode( message: AccountApple_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountApple_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountApple_VarsEntry } as AccountApple_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountApple_VarsEntry { const message = { ...baseAccountApple_VarsEntry } as AccountApple_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountApple_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountApple_VarsEntry> ): AccountApple_VarsEntry { const message = { ...baseAccountApple_VarsEntry } as AccountApple_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAccountCustom: object = { id: "" }; export const AccountCustom = { encode( message: AccountCustom, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.id !== "") { writer.uint32(10).string(message.id); } Object.entries(message.vars).forEach(([key, value]) => { AccountCustom_VarsEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AccountCustom { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountCustom } as AccountCustom; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: const entry2 = AccountCustom_VarsEntry.decode( reader, reader.uint32() ); if (entry2.value !== undefined) { message.vars[entry2.key] = entry2.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountCustom { const message = { ...baseAccountCustom } as AccountCustom; message.vars = {}; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountCustom): unknown { const obj: any = {}; message.id !== undefined && (obj.id = message.id); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<AccountCustom>): AccountCustom { const message = { ...baseAccountCustom } as AccountCustom; message.vars = {}; if (object.id !== undefined && object.id !== null) { message.id = object.id; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountCustom_VarsEntry: object = { key: "", value: "" }; export const AccountCustom_VarsEntry = { encode( message: AccountCustom_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountCustom_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountCustom_VarsEntry, } as AccountCustom_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountCustom_VarsEntry { const message = { ...baseAccountCustom_VarsEntry, } as AccountCustom_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountCustom_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountCustom_VarsEntry> ): AccountCustom_VarsEntry { const message = { ...baseAccountCustom_VarsEntry, } as AccountCustom_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAccountDevice: object = { id: "" }; export const AccountDevice = { encode( message: AccountDevice, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.id !== "") { writer.uint32(10).string(message.id); } Object.entries(message.vars).forEach(([key, value]) => { AccountDevice_VarsEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AccountDevice { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountDevice } as AccountDevice; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: const entry2 = AccountDevice_VarsEntry.decode( reader, reader.uint32() ); if (entry2.value !== undefined) { message.vars[entry2.key] = entry2.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountDevice { const message = { ...baseAccountDevice } as AccountDevice; message.vars = {}; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountDevice): unknown { const obj: any = {}; message.id !== undefined && (obj.id = message.id); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<AccountDevice>): AccountDevice { const message = { ...baseAccountDevice } as AccountDevice; message.vars = {}; if (object.id !== undefined && object.id !== null) { message.id = object.id; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountDevice_VarsEntry: object = { key: "", value: "" }; export const AccountDevice_VarsEntry = { encode( message: AccountDevice_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountDevice_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountDevice_VarsEntry, } as AccountDevice_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountDevice_VarsEntry { const message = { ...baseAccountDevice_VarsEntry, } as AccountDevice_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountDevice_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountDevice_VarsEntry> ): AccountDevice_VarsEntry { const message = { ...baseAccountDevice_VarsEntry, } as AccountDevice_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAccountEmail: object = { email: "", password: "" }; export const AccountEmail = { encode( message: AccountEmail, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.email !== "") { writer.uint32(10).string(message.email); } if (message.password !== "") { writer.uint32(18).string(message.password); } Object.entries(message.vars).forEach(([key, value]) => { AccountEmail_VarsEntry.encode( { key: key as any, value }, writer.uint32(26).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AccountEmail { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountEmail } as AccountEmail; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.email = reader.string(); break; case 2: message.password = reader.string(); break; case 3: const entry3 = AccountEmail_VarsEntry.decode(reader, reader.uint32()); if (entry3.value !== undefined) { message.vars[entry3.key] = entry3.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountEmail { const message = { ...baseAccountEmail } as AccountEmail; message.vars = {}; if (object.email !== undefined && object.email !== null) { message.email = String(object.email); } if (object.password !== undefined && object.password !== null) { message.password = String(object.password); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountEmail): unknown { const obj: any = {}; message.email !== undefined && (obj.email = message.email); message.password !== undefined && (obj.password = message.password); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<AccountEmail>): AccountEmail { const message = { ...baseAccountEmail } as AccountEmail; message.vars = {}; if (object.email !== undefined && object.email !== null) { message.email = object.email; } if (object.password !== undefined && object.password !== null) { message.password = object.password; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountEmail_VarsEntry: object = { key: "", value: "" }; export const AccountEmail_VarsEntry = { encode( message: AccountEmail_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountEmail_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountEmail_VarsEntry } as AccountEmail_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountEmail_VarsEntry { const message = { ...baseAccountEmail_VarsEntry } as AccountEmail_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountEmail_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountEmail_VarsEntry> ): AccountEmail_VarsEntry { const message = { ...baseAccountEmail_VarsEntry } as AccountEmail_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAccountFacebook: object = { token: "" }; export const AccountFacebook = { encode( message: AccountFacebook, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.token !== "") { writer.uint32(10).string(message.token); } Object.entries(message.vars).forEach(([key, value]) => { AccountFacebook_VarsEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AccountFacebook { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountFacebook } as AccountFacebook; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.token = reader.string(); break; case 2: const entry2 = AccountFacebook_VarsEntry.decode( reader, reader.uint32() ); if (entry2.value !== undefined) { message.vars[entry2.key] = entry2.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountFacebook { const message = { ...baseAccountFacebook } as AccountFacebook; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = String(object.token); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountFacebook): unknown { const obj: any = {}; message.token !== undefined && (obj.token = message.token); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<AccountFacebook>): AccountFacebook { const message = { ...baseAccountFacebook } as AccountFacebook; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = object.token; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountFacebook_VarsEntry: object = { key: "", value: "" }; export const AccountFacebook_VarsEntry = { encode( message: AccountFacebook_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountFacebook_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountFacebook_VarsEntry, } as AccountFacebook_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountFacebook_VarsEntry { const message = { ...baseAccountFacebook_VarsEntry, } as AccountFacebook_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountFacebook_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountFacebook_VarsEntry> ): AccountFacebook_VarsEntry { const message = { ...baseAccountFacebook_VarsEntry, } as AccountFacebook_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAccountFacebookInstantGame: object = { signed_player_info: "" }; export const AccountFacebookInstantGame = { encode( message: AccountFacebookInstantGame, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.signed_player_info !== "") { writer.uint32(10).string(message.signed_player_info); } Object.entries(message.vars).forEach(([key, value]) => { AccountFacebookInstantGame_VarsEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountFacebookInstantGame { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountFacebookInstantGame, } as AccountFacebookInstantGame; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.signed_player_info = reader.string(); break; case 2: const entry2 = AccountFacebookInstantGame_VarsEntry.decode( reader, reader.uint32() ); if (entry2.value !== undefined) { message.vars[entry2.key] = entry2.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountFacebookInstantGame { const message = { ...baseAccountFacebookInstantGame, } as AccountFacebookInstantGame; message.vars = {}; if ( object.signed_player_info !== undefined && object.signed_player_info !== null ) { message.signed_player_info = String(object.signed_player_info); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountFacebookInstantGame): unknown { const obj: any = {}; message.signed_player_info !== undefined && (obj.signed_player_info = message.signed_player_info); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial( object: DeepPartial<AccountFacebookInstantGame> ): AccountFacebookInstantGame { const message = { ...baseAccountFacebookInstantGame, } as AccountFacebookInstantGame; message.vars = {}; if ( object.signed_player_info !== undefined && object.signed_player_info !== null ) { message.signed_player_info = object.signed_player_info; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountFacebookInstantGame_VarsEntry: object = { key: "", value: "" }; export const AccountFacebookInstantGame_VarsEntry = { encode( message: AccountFacebookInstantGame_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountFacebookInstantGame_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountFacebookInstantGame_VarsEntry, } as AccountFacebookInstantGame_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountFacebookInstantGame_VarsEntry { const message = { ...baseAccountFacebookInstantGame_VarsEntry, } as AccountFacebookInstantGame_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountFacebookInstantGame_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountFacebookInstantGame_VarsEntry> ): AccountFacebookInstantGame_VarsEntry { const message = { ...baseAccountFacebookInstantGame_VarsEntry, } as AccountFacebookInstantGame_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAccountGameCenter: object = { player_id: "", bundle_id: "", timestamp_seconds: 0, salt: "", signature: "", public_key_url: "", }; export const AccountGameCenter = { encode( message: AccountGameCenter, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.player_id !== "") { writer.uint32(10).string(message.player_id); } if (message.bundle_id !== "") { writer.uint32(18).string(message.bundle_id); } if (message.timestamp_seconds !== 0) { writer.uint32(24).int64(message.timestamp_seconds); } if (message.salt !== "") { writer.uint32(34).string(message.salt); } if (message.signature !== "") { writer.uint32(42).string(message.signature); } if (message.public_key_url !== "") { writer.uint32(50).string(message.public_key_url); } Object.entries(message.vars).forEach(([key, value]) => { AccountGameCenter_VarsEntry.encode( { key: key as any, value }, writer.uint32(58).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AccountGameCenter { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountGameCenter } as AccountGameCenter; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.player_id = reader.string(); break; case 2: message.bundle_id = reader.string(); break; case 3: message.timestamp_seconds = longToNumber(reader.int64() as Long); break; case 4: message.salt = reader.string(); break; case 5: message.signature = reader.string(); break; case 6: message.public_key_url = reader.string(); break; case 7: const entry7 = AccountGameCenter_VarsEntry.decode( reader, reader.uint32() ); if (entry7.value !== undefined) { message.vars[entry7.key] = entry7.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountGameCenter { const message = { ...baseAccountGameCenter } as AccountGameCenter; message.vars = {}; if (object.player_id !== undefined && object.player_id !== null) { message.player_id = String(object.player_id); } if (object.bundle_id !== undefined && object.bundle_id !== null) { message.bundle_id = String(object.bundle_id); } if ( object.timestamp_seconds !== undefined && object.timestamp_seconds !== null ) { message.timestamp_seconds = Number(object.timestamp_seconds); } if (object.salt !== undefined && object.salt !== null) { message.salt = String(object.salt); } if (object.signature !== undefined && object.signature !== null) { message.signature = String(object.signature); } if (object.public_key_url !== undefined && object.public_key_url !== null) { message.public_key_url = String(object.public_key_url); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountGameCenter): unknown { const obj: any = {}; message.player_id !== undefined && (obj.player_id = message.player_id); message.bundle_id !== undefined && (obj.bundle_id = message.bundle_id); message.timestamp_seconds !== undefined && (obj.timestamp_seconds = message.timestamp_seconds); message.salt !== undefined && (obj.salt = message.salt); message.signature !== undefined && (obj.signature = message.signature); message.public_key_url !== undefined && (obj.public_key_url = message.public_key_url); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<AccountGameCenter>): AccountGameCenter { const message = { ...baseAccountGameCenter } as AccountGameCenter; message.vars = {}; if (object.player_id !== undefined && object.player_id !== null) { message.player_id = object.player_id; } if (object.bundle_id !== undefined && object.bundle_id !== null) { message.bundle_id = object.bundle_id; } if ( object.timestamp_seconds !== undefined && object.timestamp_seconds !== null ) { message.timestamp_seconds = object.timestamp_seconds; } if (object.salt !== undefined && object.salt !== null) { message.salt = object.salt; } if (object.signature !== undefined && object.signature !== null) { message.signature = object.signature; } if (object.public_key_url !== undefined && object.public_key_url !== null) { message.public_key_url = object.public_key_url; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountGameCenter_VarsEntry: object = { key: "", value: "" }; export const AccountGameCenter_VarsEntry = { encode( message: AccountGameCenter_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountGameCenter_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountGameCenter_VarsEntry, } as AccountGameCenter_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountGameCenter_VarsEntry { const message = { ...baseAccountGameCenter_VarsEntry, } as AccountGameCenter_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountGameCenter_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountGameCenter_VarsEntry> ): AccountGameCenter_VarsEntry { const message = { ...baseAccountGameCenter_VarsEntry, } as AccountGameCenter_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAccountGoogle: object = { token: "" }; export const AccountGoogle = { encode( message: AccountGoogle, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.token !== "") { writer.uint32(10).string(message.token); } Object.entries(message.vars).forEach(([key, value]) => { AccountGoogle_VarsEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AccountGoogle { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountGoogle } as AccountGoogle; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.token = reader.string(); break; case 2: const entry2 = AccountGoogle_VarsEntry.decode( reader, reader.uint32() ); if (entry2.value !== undefined) { message.vars[entry2.key] = entry2.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountGoogle { const message = { ...baseAccountGoogle } as AccountGoogle; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = String(object.token); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountGoogle): unknown { const obj: any = {}; message.token !== undefined && (obj.token = message.token); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<AccountGoogle>): AccountGoogle { const message = { ...baseAccountGoogle } as AccountGoogle; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = object.token; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountGoogle_VarsEntry: object = { key: "", value: "" }; export const AccountGoogle_VarsEntry = { encode( message: AccountGoogle_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountGoogle_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountGoogle_VarsEntry, } as AccountGoogle_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountGoogle_VarsEntry { const message = { ...baseAccountGoogle_VarsEntry, } as AccountGoogle_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountGoogle_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountGoogle_VarsEntry> ): AccountGoogle_VarsEntry { const message = { ...baseAccountGoogle_VarsEntry, } as AccountGoogle_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAccountSteam: object = { token: "" }; export const AccountSteam = { encode( message: AccountSteam, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.token !== "") { writer.uint32(10).string(message.token); } Object.entries(message.vars).forEach(([key, value]) => { AccountSteam_VarsEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AccountSteam { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountSteam } as AccountSteam; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.token = reader.string(); break; case 2: const entry2 = AccountSteam_VarsEntry.decode(reader, reader.uint32()); if (entry2.value !== undefined) { message.vars[entry2.key] = entry2.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountSteam { const message = { ...baseAccountSteam } as AccountSteam; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = String(object.token); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: AccountSteam): unknown { const obj: any = {}; message.token !== undefined && (obj.token = message.token); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial(object: DeepPartial<AccountSteam>): AccountSteam { const message = { ...baseAccountSteam } as AccountSteam; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = object.token; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseAccountSteam_VarsEntry: object = { key: "", value: "" }; export const AccountSteam_VarsEntry = { encode( message: AccountSteam_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AccountSteam_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAccountSteam_VarsEntry } as AccountSteam_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AccountSteam_VarsEntry { const message = { ...baseAccountSteam_VarsEntry } as AccountSteam_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: AccountSteam_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<AccountSteam_VarsEntry> ): AccountSteam_VarsEntry { const message = { ...baseAccountSteam_VarsEntry } as AccountSteam_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseAddFriendsRequest: object = { ids: "", usernames: "" }; export const AddFriendsRequest = { encode( message: AddFriendsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.ids) { writer.uint32(10).string(v!); } for (const v of message.usernames) { writer.uint32(18).string(v!); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): AddFriendsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAddFriendsRequest } as AddFriendsRequest; message.ids = []; message.usernames = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.ids.push(reader.string()); break; case 2: message.usernames.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AddFriendsRequest { const message = { ...baseAddFriendsRequest } as AddFriendsRequest; message.ids = []; message.usernames = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(String(e)); } } if (object.usernames !== undefined && object.usernames !== null) { for (const e of object.usernames) { message.usernames.push(String(e)); } } return message; }, toJSON(message: AddFriendsRequest): unknown { const obj: any = {}; if (message.ids) { obj.ids = message.ids.map((e) => e); } else { obj.ids = []; } if (message.usernames) { obj.usernames = message.usernames.map((e) => e); } else { obj.usernames = []; } return obj; }, fromPartial(object: DeepPartial<AddFriendsRequest>): AddFriendsRequest { const message = { ...baseAddFriendsRequest } as AddFriendsRequest; message.ids = []; message.usernames = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(e); } } if (object.usernames !== undefined && object.usernames !== null) { for (const e of object.usernames) { message.usernames.push(e); } } return message; }, }; const baseAddGroupUsersRequest: object = { group_id: "", user_ids: "" }; export const AddGroupUsersRequest = { encode( message: AddGroupUsersRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } for (const v of message.user_ids) { writer.uint32(18).string(v!); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AddGroupUsersRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAddGroupUsersRequest } as AddGroupUsersRequest; message.user_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; case 2: message.user_ids.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AddGroupUsersRequest { const message = { ...baseAddGroupUsersRequest } as AddGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(String(e)); } } return message; }, toJSON(message: AddGroupUsersRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); if (message.user_ids) { obj.user_ids = message.user_ids.map((e) => e); } else { obj.user_ids = []; } return obj; }, fromPartial(object: DeepPartial<AddGroupUsersRequest>): AddGroupUsersRequest { const message = { ...baseAddGroupUsersRequest } as AddGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(e); } } return message; }, }; const baseSessionRefreshRequest: object = { token: "" }; export const SessionRefreshRequest = { encode( message: SessionRefreshRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.token !== "") { writer.uint32(10).string(message.token); } Object.entries(message.vars).forEach(([key, value]) => { SessionRefreshRequest_VarsEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): SessionRefreshRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSessionRefreshRequest } as SessionRefreshRequest; message.vars = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.token = reader.string(); break; case 2: const entry2 = SessionRefreshRequest_VarsEntry.decode( reader, reader.uint32() ); if (entry2.value !== undefined) { message.vars[entry2.key] = entry2.value; } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SessionRefreshRequest { const message = { ...baseSessionRefreshRequest } as SessionRefreshRequest; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = String(object.token); } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { message.vars[key] = String(value); }); } return message; }, toJSON(message: SessionRefreshRequest): unknown { const obj: any = {}; message.token !== undefined && (obj.token = message.token); obj.vars = {}; if (message.vars) { Object.entries(message.vars).forEach(([k, v]) => { obj.vars[k] = v; }); } return obj; }, fromPartial( object: DeepPartial<SessionRefreshRequest> ): SessionRefreshRequest { const message = { ...baseSessionRefreshRequest } as SessionRefreshRequest; message.vars = {}; if (object.token !== undefined && object.token !== null) { message.token = object.token; } if (object.vars !== undefined && object.vars !== null) { Object.entries(object.vars).forEach(([key, value]) => { if (value !== undefined) { message.vars[key] = String(value); } }); } return message; }, }; const baseSessionRefreshRequest_VarsEntry: object = { key: "", value: "" }; export const SessionRefreshRequest_VarsEntry = { encode( message: SessionRefreshRequest_VarsEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): SessionRefreshRequest_VarsEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSessionRefreshRequest_VarsEntry, } as SessionRefreshRequest_VarsEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SessionRefreshRequest_VarsEntry { const message = { ...baseSessionRefreshRequest_VarsEntry, } as SessionRefreshRequest_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: SessionRefreshRequest_VarsEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<SessionRefreshRequest_VarsEntry> ): SessionRefreshRequest_VarsEntry { const message = { ...baseSessionRefreshRequest_VarsEntry, } as SessionRefreshRequest_VarsEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseSessionLogoutRequest: object = { token: "", refresh_token: "" }; export const SessionLogoutRequest = { encode( message: SessionLogoutRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.token !== "") { writer.uint32(10).string(message.token); } if (message.refresh_token !== "") { writer.uint32(18).string(message.refresh_token); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): SessionLogoutRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSessionLogoutRequest } as SessionLogoutRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.token = reader.string(); break; case 2: message.refresh_token = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): SessionLogoutRequest { const message = { ...baseSessionLogoutRequest } as SessionLogoutRequest; if (object.token !== undefined && object.token !== null) { message.token = String(object.token); } if (object.refresh_token !== undefined && object.refresh_token !== null) { message.refresh_token = String(object.refresh_token); } return message; }, toJSON(message: SessionLogoutRequest): unknown { const obj: any = {}; message.token !== undefined && (obj.token = message.token); message.refresh_token !== undefined && (obj.refresh_token = message.refresh_token); return obj; }, fromPartial(object: DeepPartial<SessionLogoutRequest>): SessionLogoutRequest { const message = { ...baseSessionLogoutRequest } as SessionLogoutRequest; if (object.token !== undefined && object.token !== null) { message.token = object.token; } if (object.refresh_token !== undefined && object.refresh_token !== null) { message.refresh_token = object.refresh_token; } return message; }, }; const baseAuthenticateAppleRequest: object = { username: "" }; export const AuthenticateAppleRequest = { encode( message: AuthenticateAppleRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountApple.encode(message.account, writer.uint32(10).fork()).ldelim(); } if (message.create !== undefined) { BoolValue.encode( { value: message.create! }, writer.uint32(18).fork() ).ldelim(); } if (message.username !== "") { writer.uint32(26).string(message.username); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AuthenticateAppleRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAuthenticateAppleRequest, } as AuthenticateAppleRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountApple.decode(reader, reader.uint32()); break; case 2: message.create = BoolValue.decode(reader, reader.uint32()).value; break; case 3: message.username = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AuthenticateAppleRequest { const message = { ...baseAuthenticateAppleRequest, } as AuthenticateAppleRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountApple.fromJSON(object.account); } if (object.create !== undefined && object.create !== null) { message.create = Boolean(object.create); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } return message; }, toJSON(message: AuthenticateAppleRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountApple.toJSON(message.account) : undefined); message.create !== undefined && (obj.create = message.create); message.username !== undefined && (obj.username = message.username); return obj; }, fromPartial( object: DeepPartial<AuthenticateAppleRequest> ): AuthenticateAppleRequest { const message = { ...baseAuthenticateAppleRequest, } as AuthenticateAppleRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountApple.fromPartial(object.account); } if (object.create !== undefined && object.create !== null) { message.create = object.create; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } return message; }, }; const baseAuthenticateCustomRequest: object = { username: "" }; export const AuthenticateCustomRequest = { encode( message: AuthenticateCustomRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountCustom.encode(message.account, writer.uint32(10).fork()).ldelim(); } if (message.create !== undefined) { BoolValue.encode( { value: message.create! }, writer.uint32(18).fork() ).ldelim(); } if (message.username !== "") { writer.uint32(26).string(message.username); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AuthenticateCustomRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAuthenticateCustomRequest, } as AuthenticateCustomRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountCustom.decode(reader, reader.uint32()); break; case 2: message.create = BoolValue.decode(reader, reader.uint32()).value; break; case 3: message.username = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AuthenticateCustomRequest { const message = { ...baseAuthenticateCustomRequest, } as AuthenticateCustomRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountCustom.fromJSON(object.account); } if (object.create !== undefined && object.create !== null) { message.create = Boolean(object.create); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } return message; }, toJSON(message: AuthenticateCustomRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountCustom.toJSON(message.account) : undefined); message.create !== undefined && (obj.create = message.create); message.username !== undefined && (obj.username = message.username); return obj; }, fromPartial( object: DeepPartial<AuthenticateCustomRequest> ): AuthenticateCustomRequest { const message = { ...baseAuthenticateCustomRequest, } as AuthenticateCustomRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountCustom.fromPartial(object.account); } if (object.create !== undefined && object.create !== null) { message.create = object.create; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } return message; }, }; const baseAuthenticateDeviceRequest: object = { username: "" }; export const AuthenticateDeviceRequest = { encode( message: AuthenticateDeviceRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountDevice.encode(message.account, writer.uint32(10).fork()).ldelim(); } if (message.create !== undefined) { BoolValue.encode( { value: message.create! }, writer.uint32(18).fork() ).ldelim(); } if (message.username !== "") { writer.uint32(26).string(message.username); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AuthenticateDeviceRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAuthenticateDeviceRequest, } as AuthenticateDeviceRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountDevice.decode(reader, reader.uint32()); break; case 2: message.create = BoolValue.decode(reader, reader.uint32()).value; break; case 3: message.username = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AuthenticateDeviceRequest { const message = { ...baseAuthenticateDeviceRequest, } as AuthenticateDeviceRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountDevice.fromJSON(object.account); } if (object.create !== undefined && object.create !== null) { message.create = Boolean(object.create); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } return message; }, toJSON(message: AuthenticateDeviceRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountDevice.toJSON(message.account) : undefined); message.create !== undefined && (obj.create = message.create); message.username !== undefined && (obj.username = message.username); return obj; }, fromPartial( object: DeepPartial<AuthenticateDeviceRequest> ): AuthenticateDeviceRequest { const message = { ...baseAuthenticateDeviceRequest, } as AuthenticateDeviceRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountDevice.fromPartial(object.account); } if (object.create !== undefined && object.create !== null) { message.create = object.create; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } return message; }, }; const baseAuthenticateEmailRequest: object = { username: "" }; export const AuthenticateEmailRequest = { encode( message: AuthenticateEmailRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountEmail.encode(message.account, writer.uint32(10).fork()).ldelim(); } if (message.create !== undefined) { BoolValue.encode( { value: message.create! }, writer.uint32(18).fork() ).ldelim(); } if (message.username !== "") { writer.uint32(26).string(message.username); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AuthenticateEmailRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAuthenticateEmailRequest, } as AuthenticateEmailRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountEmail.decode(reader, reader.uint32()); break; case 2: message.create = BoolValue.decode(reader, reader.uint32()).value; break; case 3: message.username = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AuthenticateEmailRequest { const message = { ...baseAuthenticateEmailRequest, } as AuthenticateEmailRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountEmail.fromJSON(object.account); } if (object.create !== undefined && object.create !== null) { message.create = Boolean(object.create); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } return message; }, toJSON(message: AuthenticateEmailRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountEmail.toJSON(message.account) : undefined); message.create !== undefined && (obj.create = message.create); message.username !== undefined && (obj.username = message.username); return obj; }, fromPartial( object: DeepPartial<AuthenticateEmailRequest> ): AuthenticateEmailRequest { const message = { ...baseAuthenticateEmailRequest, } as AuthenticateEmailRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountEmail.fromPartial(object.account); } if (object.create !== undefined && object.create !== null) { message.create = object.create; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } return message; }, }; const baseAuthenticateFacebookRequest: object = { username: "" }; export const AuthenticateFacebookRequest = { encode( message: AuthenticateFacebookRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountFacebook.encode( message.account, writer.uint32(10).fork() ).ldelim(); } if (message.create !== undefined) { BoolValue.encode( { value: message.create! }, writer.uint32(18).fork() ).ldelim(); } if (message.username !== "") { writer.uint32(26).string(message.username); } if (message.sync !== undefined) { BoolValue.encode( { value: message.sync! }, writer.uint32(34).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AuthenticateFacebookRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAuthenticateFacebookRequest, } as AuthenticateFacebookRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountFacebook.decode(reader, reader.uint32()); break; case 2: message.create = BoolValue.decode(reader, reader.uint32()).value; break; case 3: message.username = reader.string(); break; case 4: message.sync = BoolValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AuthenticateFacebookRequest { const message = { ...baseAuthenticateFacebookRequest, } as AuthenticateFacebookRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountFacebook.fromJSON(object.account); } if (object.create !== undefined && object.create !== null) { message.create = Boolean(object.create); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } if (object.sync !== undefined && object.sync !== null) { message.sync = Boolean(object.sync); } return message; }, toJSON(message: AuthenticateFacebookRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountFacebook.toJSON(message.account) : undefined); message.create !== undefined && (obj.create = message.create); message.username !== undefined && (obj.username = message.username); message.sync !== undefined && (obj.sync = message.sync); return obj; }, fromPartial( object: DeepPartial<AuthenticateFacebookRequest> ): AuthenticateFacebookRequest { const message = { ...baseAuthenticateFacebookRequest, } as AuthenticateFacebookRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountFacebook.fromPartial(object.account); } if (object.create !== undefined && object.create !== null) { message.create = object.create; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } if (object.sync !== undefined && object.sync !== null) { message.sync = object.sync; } return message; }, }; const baseAuthenticateFacebookInstantGameRequest: object = { username: "" }; export const AuthenticateFacebookInstantGameRequest = { encode( message: AuthenticateFacebookInstantGameRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountFacebookInstantGame.encode( message.account, writer.uint32(10).fork() ).ldelim(); } if (message.create !== undefined) { BoolValue.encode( { value: message.create! }, writer.uint32(18).fork() ).ldelim(); } if (message.username !== "") { writer.uint32(26).string(message.username); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AuthenticateFacebookInstantGameRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAuthenticateFacebookInstantGameRequest, } as AuthenticateFacebookInstantGameRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountFacebookInstantGame.decode( reader, reader.uint32() ); break; case 2: message.create = BoolValue.decode(reader, reader.uint32()).value; break; case 3: message.username = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AuthenticateFacebookInstantGameRequest { const message = { ...baseAuthenticateFacebookInstantGameRequest, } as AuthenticateFacebookInstantGameRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountFacebookInstantGame.fromJSON(object.account); } if (object.create !== undefined && object.create !== null) { message.create = Boolean(object.create); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } return message; }, toJSON(message: AuthenticateFacebookInstantGameRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountFacebookInstantGame.toJSON(message.account) : undefined); message.create !== undefined && (obj.create = message.create); message.username !== undefined && (obj.username = message.username); return obj; }, fromPartial( object: DeepPartial<AuthenticateFacebookInstantGameRequest> ): AuthenticateFacebookInstantGameRequest { const message = { ...baseAuthenticateFacebookInstantGameRequest, } as AuthenticateFacebookInstantGameRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountFacebookInstantGame.fromPartial(object.account); } if (object.create !== undefined && object.create !== null) { message.create = object.create; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } return message; }, }; const baseAuthenticateGameCenterRequest: object = { username: "" }; export const AuthenticateGameCenterRequest = { encode( message: AuthenticateGameCenterRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountGameCenter.encode( message.account, writer.uint32(10).fork() ).ldelim(); } if (message.create !== undefined) { BoolValue.encode( { value: message.create! }, writer.uint32(18).fork() ).ldelim(); } if (message.username !== "") { writer.uint32(26).string(message.username); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AuthenticateGameCenterRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAuthenticateGameCenterRequest, } as AuthenticateGameCenterRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountGameCenter.decode(reader, reader.uint32()); break; case 2: message.create = BoolValue.decode(reader, reader.uint32()).value; break; case 3: message.username = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AuthenticateGameCenterRequest { const message = { ...baseAuthenticateGameCenterRequest, } as AuthenticateGameCenterRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountGameCenter.fromJSON(object.account); } if (object.create !== undefined && object.create !== null) { message.create = Boolean(object.create); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } return message; }, toJSON(message: AuthenticateGameCenterRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountGameCenter.toJSON(message.account) : undefined); message.create !== undefined && (obj.create = message.create); message.username !== undefined && (obj.username = message.username); return obj; }, fromPartial( object: DeepPartial<AuthenticateGameCenterRequest> ): AuthenticateGameCenterRequest { const message = { ...baseAuthenticateGameCenterRequest, } as AuthenticateGameCenterRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountGameCenter.fromPartial(object.account); } if (object.create !== undefined && object.create !== null) { message.create = object.create; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } return message; }, }; const baseAuthenticateGoogleRequest: object = { username: "" }; export const AuthenticateGoogleRequest = { encode( message: AuthenticateGoogleRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountGoogle.encode(message.account, writer.uint32(10).fork()).ldelim(); } if (message.create !== undefined) { BoolValue.encode( { value: message.create! }, writer.uint32(18).fork() ).ldelim(); } if (message.username !== "") { writer.uint32(26).string(message.username); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AuthenticateGoogleRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAuthenticateGoogleRequest, } as AuthenticateGoogleRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountGoogle.decode(reader, reader.uint32()); break; case 2: message.create = BoolValue.decode(reader, reader.uint32()).value; break; case 3: message.username = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AuthenticateGoogleRequest { const message = { ...baseAuthenticateGoogleRequest, } as AuthenticateGoogleRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountGoogle.fromJSON(object.account); } if (object.create !== undefined && object.create !== null) { message.create = Boolean(object.create); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } return message; }, toJSON(message: AuthenticateGoogleRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountGoogle.toJSON(message.account) : undefined); message.create !== undefined && (obj.create = message.create); message.username !== undefined && (obj.username = message.username); return obj; }, fromPartial( object: DeepPartial<AuthenticateGoogleRequest> ): AuthenticateGoogleRequest { const message = { ...baseAuthenticateGoogleRequest, } as AuthenticateGoogleRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountGoogle.fromPartial(object.account); } if (object.create !== undefined && object.create !== null) { message.create = object.create; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } return message; }, }; const baseAuthenticateSteamRequest: object = { username: "" }; export const AuthenticateSteamRequest = { encode( message: AuthenticateSteamRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountSteam.encode(message.account, writer.uint32(10).fork()).ldelim(); } if (message.create !== undefined) { BoolValue.encode( { value: message.create! }, writer.uint32(18).fork() ).ldelim(); } if (message.username !== "") { writer.uint32(26).string(message.username); } if (message.sync !== undefined) { BoolValue.encode( { value: message.sync! }, writer.uint32(34).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): AuthenticateSteamRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseAuthenticateSteamRequest, } as AuthenticateSteamRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountSteam.decode(reader, reader.uint32()); break; case 2: message.create = BoolValue.decode(reader, reader.uint32()).value; break; case 3: message.username = reader.string(); break; case 4: message.sync = BoolValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): AuthenticateSteamRequest { const message = { ...baseAuthenticateSteamRequest, } as AuthenticateSteamRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountSteam.fromJSON(object.account); } if (object.create !== undefined && object.create !== null) { message.create = Boolean(object.create); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } if (object.sync !== undefined && object.sync !== null) { message.sync = Boolean(object.sync); } return message; }, toJSON(message: AuthenticateSteamRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountSteam.toJSON(message.account) : undefined); message.create !== undefined && (obj.create = message.create); message.username !== undefined && (obj.username = message.username); message.sync !== undefined && (obj.sync = message.sync); return obj; }, fromPartial( object: DeepPartial<AuthenticateSteamRequest> ): AuthenticateSteamRequest { const message = { ...baseAuthenticateSteamRequest, } as AuthenticateSteamRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountSteam.fromPartial(object.account); } if (object.create !== undefined && object.create !== null) { message.create = object.create; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } if (object.sync !== undefined && object.sync !== null) { message.sync = object.sync; } return message; }, }; const baseBanGroupUsersRequest: object = { group_id: "", user_ids: "" }; export const BanGroupUsersRequest = { encode( message: BanGroupUsersRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } for (const v of message.user_ids) { writer.uint32(18).string(v!); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): BanGroupUsersRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseBanGroupUsersRequest } as BanGroupUsersRequest; message.user_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; case 2: message.user_ids.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): BanGroupUsersRequest { const message = { ...baseBanGroupUsersRequest } as BanGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(String(e)); } } return message; }, toJSON(message: BanGroupUsersRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); if (message.user_ids) { obj.user_ids = message.user_ids.map((e) => e); } else { obj.user_ids = []; } return obj; }, fromPartial(object: DeepPartial<BanGroupUsersRequest>): BanGroupUsersRequest { const message = { ...baseBanGroupUsersRequest } as BanGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(e); } } return message; }, }; const baseBlockFriendsRequest: object = { ids: "", usernames: "" }; export const BlockFriendsRequest = { encode( message: BlockFriendsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.ids) { writer.uint32(10).string(v!); } for (const v of message.usernames) { writer.uint32(18).string(v!); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): BlockFriendsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseBlockFriendsRequest } as BlockFriendsRequest; message.ids = []; message.usernames = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.ids.push(reader.string()); break; case 2: message.usernames.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): BlockFriendsRequest { const message = { ...baseBlockFriendsRequest } as BlockFriendsRequest; message.ids = []; message.usernames = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(String(e)); } } if (object.usernames !== undefined && object.usernames !== null) { for (const e of object.usernames) { message.usernames.push(String(e)); } } return message; }, toJSON(message: BlockFriendsRequest): unknown { const obj: any = {}; if (message.ids) { obj.ids = message.ids.map((e) => e); } else { obj.ids = []; } if (message.usernames) { obj.usernames = message.usernames.map((e) => e); } else { obj.usernames = []; } return obj; }, fromPartial(object: DeepPartial<BlockFriendsRequest>): BlockFriendsRequest { const message = { ...baseBlockFriendsRequest } as BlockFriendsRequest; message.ids = []; message.usernames = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(e); } } if (object.usernames !== undefined && object.usernames !== null) { for (const e of object.usernames) { message.usernames.push(e); } } return message; }, }; const baseChannelMessage: object = { channel_id: "", message_id: "", sender_id: "", username: "", content: "", room_name: "", group_id: "", user_id_one: "", user_id_two: "", }; export const ChannelMessage = { encode( message: ChannelMessage, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.channel_id !== "") { writer.uint32(10).string(message.channel_id); } if (message.message_id !== "") { writer.uint32(18).string(message.message_id); } if (message.code !== undefined) { Int32Value.encode( { value: message.code! }, writer.uint32(26).fork() ).ldelim(); } if (message.sender_id !== "") { writer.uint32(34).string(message.sender_id); } if (message.username !== "") { writer.uint32(42).string(message.username); } if (message.content !== "") { writer.uint32(50).string(message.content); } if (message.create_time !== undefined) { Timestamp.encode( toTimestamp(message.create_time), writer.uint32(58).fork() ).ldelim(); } if (message.update_time !== undefined) { Timestamp.encode( toTimestamp(message.update_time), writer.uint32(66).fork() ).ldelim(); } if (message.persistent !== undefined) { BoolValue.encode( { value: message.persistent! }, writer.uint32(74).fork() ).ldelim(); } if (message.room_name !== "") { writer.uint32(82).string(message.room_name); } if (message.group_id !== "") { writer.uint32(90).string(message.group_id); } if (message.user_id_one !== "") { writer.uint32(98).string(message.user_id_one); } if (message.user_id_two !== "") { writer.uint32(106).string(message.user_id_two); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ChannelMessage { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannelMessage } as ChannelMessage; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.channel_id = reader.string(); break; case 2: message.message_id = reader.string(); break; case 3: message.code = Int32Value.decode(reader, reader.uint32()).value; break; case 4: message.sender_id = reader.string(); break; case 5: message.username = reader.string(); break; case 6: message.content = reader.string(); break; case 7: message.create_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 8: message.update_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 9: message.persistent = BoolValue.decode(reader, reader.uint32()).value; break; case 10: message.room_name = reader.string(); break; case 11: message.group_id = reader.string(); break; case 12: message.user_id_one = reader.string(); break; case 13: message.user_id_two = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChannelMessage { const message = { ...baseChannelMessage } as ChannelMessage; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = String(object.channel_id); } if (object.message_id !== undefined && object.message_id !== null) { message.message_id = String(object.message_id); } if (object.code !== undefined && object.code !== null) { message.code = Number(object.code); } if (object.sender_id !== undefined && object.sender_id !== null) { message.sender_id = String(object.sender_id); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } if (object.content !== undefined && object.content !== null) { message.content = String(object.content); } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = fromJsonTimestamp(object.create_time); } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = fromJsonTimestamp(object.update_time); } if (object.persistent !== undefined && object.persistent !== null) { message.persistent = Boolean(object.persistent); } if (object.room_name !== undefined && object.room_name !== null) { message.room_name = String(object.room_name); } if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } if (object.user_id_one !== undefined && object.user_id_one !== null) { message.user_id_one = String(object.user_id_one); } if (object.user_id_two !== undefined && object.user_id_two !== null) { message.user_id_two = String(object.user_id_two); } return message; }, toJSON(message: ChannelMessage): unknown { const obj: any = {}; message.channel_id !== undefined && (obj.channel_id = message.channel_id); message.message_id !== undefined && (obj.message_id = message.message_id); message.code !== undefined && (obj.code = message.code); message.sender_id !== undefined && (obj.sender_id = message.sender_id); message.username !== undefined && (obj.username = message.username); message.content !== undefined && (obj.content = message.content); message.create_time !== undefined && (obj.create_time = message.create_time.toISOString()); message.update_time !== undefined && (obj.update_time = message.update_time.toISOString()); message.persistent !== undefined && (obj.persistent = message.persistent); message.room_name !== undefined && (obj.room_name = message.room_name); message.group_id !== undefined && (obj.group_id = message.group_id); message.user_id_one !== undefined && (obj.user_id_one = message.user_id_one); message.user_id_two !== undefined && (obj.user_id_two = message.user_id_two); return obj; }, fromPartial(object: DeepPartial<ChannelMessage>): ChannelMessage { const message = { ...baseChannelMessage } as ChannelMessage; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = object.channel_id; } if (object.message_id !== undefined && object.message_id !== null) { message.message_id = object.message_id; } if (object.code !== undefined && object.code !== null) { message.code = object.code; } if (object.sender_id !== undefined && object.sender_id !== null) { message.sender_id = object.sender_id; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } if (object.content !== undefined && object.content !== null) { message.content = object.content; } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = object.create_time; } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = object.update_time; } if (object.persistent !== undefined && object.persistent !== null) { message.persistent = object.persistent; } if (object.room_name !== undefined && object.room_name !== null) { message.room_name = object.room_name; } if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } if (object.user_id_one !== undefined && object.user_id_one !== null) { message.user_id_one = object.user_id_one; } if (object.user_id_two !== undefined && object.user_id_two !== null) { message.user_id_two = object.user_id_two; } return message; }, }; const baseChannelMessageList: object = { next_cursor: "", prev_cursor: "", cacheable_cursor: "", }; export const ChannelMessageList = { encode( message: ChannelMessageList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.messages) { ChannelMessage.encode(v!, writer.uint32(10).fork()).ldelim(); } if (message.next_cursor !== "") { writer.uint32(18).string(message.next_cursor); } if (message.prev_cursor !== "") { writer.uint32(26).string(message.prev_cursor); } if (message.cacheable_cursor !== "") { writer.uint32(34).string(message.cacheable_cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ChannelMessageList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseChannelMessageList } as ChannelMessageList; message.messages = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.messages.push(ChannelMessage.decode(reader, reader.uint32())); break; case 2: message.next_cursor = reader.string(); break; case 3: message.prev_cursor = reader.string(); break; case 4: message.cacheable_cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ChannelMessageList { const message = { ...baseChannelMessageList } as ChannelMessageList; message.messages = []; if (object.messages !== undefined && object.messages !== null) { for (const e of object.messages) { message.messages.push(ChannelMessage.fromJSON(e)); } } if (object.next_cursor !== undefined && object.next_cursor !== null) { message.next_cursor = String(object.next_cursor); } if (object.prev_cursor !== undefined && object.prev_cursor !== null) { message.prev_cursor = String(object.prev_cursor); } if ( object.cacheable_cursor !== undefined && object.cacheable_cursor !== null ) { message.cacheable_cursor = String(object.cacheable_cursor); } return message; }, toJSON(message: ChannelMessageList): unknown { const obj: any = {}; if (message.messages) { obj.messages = message.messages.map((e) => e ? ChannelMessage.toJSON(e) : undefined ); } else { obj.messages = []; } message.next_cursor !== undefined && (obj.next_cursor = message.next_cursor); message.prev_cursor !== undefined && (obj.prev_cursor = message.prev_cursor); message.cacheable_cursor !== undefined && (obj.cacheable_cursor = message.cacheable_cursor); return obj; }, fromPartial(object: DeepPartial<ChannelMessageList>): ChannelMessageList { const message = { ...baseChannelMessageList } as ChannelMessageList; message.messages = []; if (object.messages !== undefined && object.messages !== null) { for (const e of object.messages) { message.messages.push(ChannelMessage.fromPartial(e)); } } if (object.next_cursor !== undefined && object.next_cursor !== null) { message.next_cursor = object.next_cursor; } if (object.prev_cursor !== undefined && object.prev_cursor !== null) { message.prev_cursor = object.prev_cursor; } if ( object.cacheable_cursor !== undefined && object.cacheable_cursor !== null ) { message.cacheable_cursor = object.cacheable_cursor; } return message; }, }; const baseCreateGroupRequest: object = { name: "", description: "", lang_tag: "", avatar_url: "", open: false, max_count: 0, }; export const CreateGroupRequest = { encode( message: CreateGroupRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.name !== "") { writer.uint32(10).string(message.name); } if (message.description !== "") { writer.uint32(18).string(message.description); } if (message.lang_tag !== "") { writer.uint32(26).string(message.lang_tag); } if (message.avatar_url !== "") { writer.uint32(34).string(message.avatar_url); } if (message.open === true) { writer.uint32(40).bool(message.open); } if (message.max_count !== 0) { writer.uint32(48).int32(message.max_count); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): CreateGroupRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseCreateGroupRequest } as CreateGroupRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.description = reader.string(); break; case 3: message.lang_tag = reader.string(); break; case 4: message.avatar_url = reader.string(); break; case 5: message.open = reader.bool(); break; case 6: message.max_count = reader.int32(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): CreateGroupRequest { const message = { ...baseCreateGroupRequest } as CreateGroupRequest; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } if (object.description !== undefined && object.description !== null) { message.description = String(object.description); } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = String(object.lang_tag); } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = String(object.avatar_url); } if (object.open !== undefined && object.open !== null) { message.open = Boolean(object.open); } if (object.max_count !== undefined && object.max_count !== null) { message.max_count = Number(object.max_count); } return message; }, toJSON(message: CreateGroupRequest): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); message.description !== undefined && (obj.description = message.description); message.lang_tag !== undefined && (obj.lang_tag = message.lang_tag); message.avatar_url !== undefined && (obj.avatar_url = message.avatar_url); message.open !== undefined && (obj.open = message.open); message.max_count !== undefined && (obj.max_count = message.max_count); return obj; }, fromPartial(object: DeepPartial<CreateGroupRequest>): CreateGroupRequest { const message = { ...baseCreateGroupRequest } as CreateGroupRequest; if (object.name !== undefined && object.name !== null) { message.name = object.name; } if (object.description !== undefined && object.description !== null) { message.description = object.description; } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = object.lang_tag; } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = object.avatar_url; } if (object.open !== undefined && object.open !== null) { message.open = object.open; } if (object.max_count !== undefined && object.max_count !== null) { message.max_count = object.max_count; } return message; }, }; const baseDeleteFriendsRequest: object = { ids: "", usernames: "" }; export const DeleteFriendsRequest = { encode( message: DeleteFriendsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.ids) { writer.uint32(10).string(v!); } for (const v of message.usernames) { writer.uint32(18).string(v!); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): DeleteFriendsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseDeleteFriendsRequest } as DeleteFriendsRequest; message.ids = []; message.usernames = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.ids.push(reader.string()); break; case 2: message.usernames.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteFriendsRequest { const message = { ...baseDeleteFriendsRequest } as DeleteFriendsRequest; message.ids = []; message.usernames = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(String(e)); } } if (object.usernames !== undefined && object.usernames !== null) { for (const e of object.usernames) { message.usernames.push(String(e)); } } return message; }, toJSON(message: DeleteFriendsRequest): unknown { const obj: any = {}; if (message.ids) { obj.ids = message.ids.map((e) => e); } else { obj.ids = []; } if (message.usernames) { obj.usernames = message.usernames.map((e) => e); } else { obj.usernames = []; } return obj; }, fromPartial(object: DeepPartial<DeleteFriendsRequest>): DeleteFriendsRequest { const message = { ...baseDeleteFriendsRequest } as DeleteFriendsRequest; message.ids = []; message.usernames = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(e); } } if (object.usernames !== undefined && object.usernames !== null) { for (const e of object.usernames) { message.usernames.push(e); } } return message; }, }; const baseDeleteGroupRequest: object = { group_id: "" }; export const DeleteGroupRequest = { encode( message: DeleteGroupRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): DeleteGroupRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseDeleteGroupRequest } as DeleteGroupRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteGroupRequest { const message = { ...baseDeleteGroupRequest } as DeleteGroupRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } return message; }, toJSON(message: DeleteGroupRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); return obj; }, fromPartial(object: DeepPartial<DeleteGroupRequest>): DeleteGroupRequest { const message = { ...baseDeleteGroupRequest } as DeleteGroupRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } return message; }, }; const baseDeleteLeaderboardRecordRequest: object = { leaderboard_id: "" }; export const DeleteLeaderboardRecordRequest = { encode( message: DeleteLeaderboardRecordRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.leaderboard_id !== "") { writer.uint32(10).string(message.leaderboard_id); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): DeleteLeaderboardRecordRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseDeleteLeaderboardRecordRequest, } as DeleteLeaderboardRecordRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.leaderboard_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteLeaderboardRecordRequest { const message = { ...baseDeleteLeaderboardRecordRequest, } as DeleteLeaderboardRecordRequest; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = String(object.leaderboard_id); } return message; }, toJSON(message: DeleteLeaderboardRecordRequest): unknown { const obj: any = {}; message.leaderboard_id !== undefined && (obj.leaderboard_id = message.leaderboard_id); return obj; }, fromPartial( object: DeepPartial<DeleteLeaderboardRecordRequest> ): DeleteLeaderboardRecordRequest { const message = { ...baseDeleteLeaderboardRecordRequest, } as DeleteLeaderboardRecordRequest; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = object.leaderboard_id; } return message; }, }; const baseDeleteNotificationsRequest: object = { ids: "" }; export const DeleteNotificationsRequest = { encode( message: DeleteNotificationsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.ids) { writer.uint32(10).string(v!); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): DeleteNotificationsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseDeleteNotificationsRequest, } as DeleteNotificationsRequest; message.ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.ids.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteNotificationsRequest { const message = { ...baseDeleteNotificationsRequest, } as DeleteNotificationsRequest; message.ids = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(String(e)); } } return message; }, toJSON(message: DeleteNotificationsRequest): unknown { const obj: any = {}; if (message.ids) { obj.ids = message.ids.map((e) => e); } else { obj.ids = []; } return obj; }, fromPartial( object: DeepPartial<DeleteNotificationsRequest> ): DeleteNotificationsRequest { const message = { ...baseDeleteNotificationsRequest, } as DeleteNotificationsRequest; message.ids = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(e); } } return message; }, }; const baseDeleteStorageObjectId: object = { collection: "", key: "", version: "", }; export const DeleteStorageObjectId = { encode( message: DeleteStorageObjectId, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.collection !== "") { writer.uint32(10).string(message.collection); } if (message.key !== "") { writer.uint32(18).string(message.key); } if (message.version !== "") { writer.uint32(26).string(message.version); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): DeleteStorageObjectId { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseDeleteStorageObjectId } as DeleteStorageObjectId; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.collection = reader.string(); break; case 2: message.key = reader.string(); break; case 3: message.version = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteStorageObjectId { const message = { ...baseDeleteStorageObjectId } as DeleteStorageObjectId; if (object.collection !== undefined && object.collection !== null) { message.collection = String(object.collection); } if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.version !== undefined && object.version !== null) { message.version = String(object.version); } return message; }, toJSON(message: DeleteStorageObjectId): unknown { const obj: any = {}; message.collection !== undefined && (obj.collection = message.collection); message.key !== undefined && (obj.key = message.key); message.version !== undefined && (obj.version = message.version); return obj; }, fromPartial( object: DeepPartial<DeleteStorageObjectId> ): DeleteStorageObjectId { const message = { ...baseDeleteStorageObjectId } as DeleteStorageObjectId; if (object.collection !== undefined && object.collection !== null) { message.collection = object.collection; } if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.version !== undefined && object.version !== null) { message.version = object.version; } return message; }, }; const baseDeleteStorageObjectsRequest: object = {}; export const DeleteStorageObjectsRequest = { encode( message: DeleteStorageObjectsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.object_ids) { DeleteStorageObjectId.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): DeleteStorageObjectsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseDeleteStorageObjectsRequest, } as DeleteStorageObjectsRequest; message.object_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.object_ids.push( DeleteStorageObjectId.decode(reader, reader.uint32()) ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DeleteStorageObjectsRequest { const message = { ...baseDeleteStorageObjectsRequest, } as DeleteStorageObjectsRequest; message.object_ids = []; if (object.object_ids !== undefined && object.object_ids !== null) { for (const e of object.object_ids) { message.object_ids.push(DeleteStorageObjectId.fromJSON(e)); } } return message; }, toJSON(message: DeleteStorageObjectsRequest): unknown { const obj: any = {}; if (message.object_ids) { obj.object_ids = message.object_ids.map((e) => e ? DeleteStorageObjectId.toJSON(e) : undefined ); } else { obj.object_ids = []; } return obj; }, fromPartial( object: DeepPartial<DeleteStorageObjectsRequest> ): DeleteStorageObjectsRequest { const message = { ...baseDeleteStorageObjectsRequest, } as DeleteStorageObjectsRequest; message.object_ids = []; if (object.object_ids !== undefined && object.object_ids !== null) { for (const e of object.object_ids) { message.object_ids.push(DeleteStorageObjectId.fromPartial(e)); } } return message; }, }; const baseEvent: object = { name: "", external: false }; export const Event = { encode(message: Event, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.name !== "") { writer.uint32(10).string(message.name); } Object.entries(message.properties).forEach(([key, value]) => { Event_PropertiesEntry.encode( { key: key as any, value }, writer.uint32(18).fork() ).ldelim(); }); if (message.timestamp !== undefined) { Timestamp.encode( toTimestamp(message.timestamp), writer.uint32(26).fork() ).ldelim(); } if (message.external === true) { writer.uint32(32).bool(message.external); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Event { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseEvent } as Event; message.properties = {}; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: const entry2 = Event_PropertiesEntry.decode(reader, reader.uint32()); if (entry2.value !== undefined) { message.properties[entry2.key] = entry2.value; } break; case 3: message.timestamp = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 4: message.external = reader.bool(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Event { const message = { ...baseEvent } as Event; message.properties = {}; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } if (object.properties !== undefined && object.properties !== null) { Object.entries(object.properties).forEach(([key, value]) => { message.properties[key] = String(value); }); } if (object.timestamp !== undefined && object.timestamp !== null) { message.timestamp = fromJsonTimestamp(object.timestamp); } if (object.external !== undefined && object.external !== null) { message.external = Boolean(object.external); } return message; }, toJSON(message: Event): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); obj.properties = {}; if (message.properties) { Object.entries(message.properties).forEach(([k, v]) => { obj.properties[k] = v; }); } message.timestamp !== undefined && (obj.timestamp = message.timestamp.toISOString()); message.external !== undefined && (obj.external = message.external); return obj; }, fromPartial(object: DeepPartial<Event>): Event { const message = { ...baseEvent } as Event; message.properties = {}; if (object.name !== undefined && object.name !== null) { message.name = object.name; } if (object.properties !== undefined && object.properties !== null) { Object.entries(object.properties).forEach(([key, value]) => { if (value !== undefined) { message.properties[key] = String(value); } }); } if (object.timestamp !== undefined && object.timestamp !== null) { message.timestamp = object.timestamp; } if (object.external !== undefined && object.external !== null) { message.external = object.external; } return message; }, }; const baseEvent_PropertiesEntry: object = { key: "", value: "" }; export const Event_PropertiesEntry = { encode( message: Event_PropertiesEntry, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.key !== "") { writer.uint32(10).string(message.key); } if (message.value !== "") { writer.uint32(18).string(message.value); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): Event_PropertiesEntry { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseEvent_PropertiesEntry } as Event_PropertiesEntry; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.key = reader.string(); break; case 2: message.value = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Event_PropertiesEntry { const message = { ...baseEvent_PropertiesEntry } as Event_PropertiesEntry; if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } return message; }, toJSON(message: Event_PropertiesEntry): unknown { const obj: any = {}; message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); return obj; }, fromPartial( object: DeepPartial<Event_PropertiesEntry> ): Event_PropertiesEntry { const message = { ...baseEvent_PropertiesEntry } as Event_PropertiesEntry; if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } return message; }, }; const baseFriend: object = {}; export const Friend = { encode( message: Friend, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.user !== undefined) { User.encode(message.user, writer.uint32(10).fork()).ldelim(); } if (message.state !== undefined) { Int32Value.encode( { value: message.state! }, writer.uint32(18).fork() ).ldelim(); } if (message.update_time !== undefined) { Timestamp.encode( toTimestamp(message.update_time), writer.uint32(26).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Friend { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseFriend } as Friend; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.user = User.decode(reader, reader.uint32()); break; case 2: message.state = Int32Value.decode(reader, reader.uint32()).value; break; case 3: message.update_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Friend { const message = { ...baseFriend } as Friend; if (object.user !== undefined && object.user !== null) { message.user = User.fromJSON(object.user); } if (object.state !== undefined && object.state !== null) { message.state = Number(object.state); } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = fromJsonTimestamp(object.update_time); } return message; }, toJSON(message: Friend): unknown { const obj: any = {}; message.user !== undefined && (obj.user = message.user ? User.toJSON(message.user) : undefined); message.state !== undefined && (obj.state = message.state); message.update_time !== undefined && (obj.update_time = message.update_time.toISOString()); return obj; }, fromPartial(object: DeepPartial<Friend>): Friend { const message = { ...baseFriend } as Friend; if (object.user !== undefined && object.user !== null) { message.user = User.fromPartial(object.user); } if (object.state !== undefined && object.state !== null) { message.state = object.state; } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = object.update_time; } return message; }, }; const baseFriendList: object = { cursor: "" }; export const FriendList = { encode( message: FriendList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.friends) { Friend.encode(v!, writer.uint32(10).fork()).ldelim(); } if (message.cursor !== "") { writer.uint32(18).string(message.cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): FriendList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseFriendList } as FriendList; message.friends = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.friends.push(Friend.decode(reader, reader.uint32())); break; case 2: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): FriendList { const message = { ...baseFriendList } as FriendList; message.friends = []; if (object.friends !== undefined && object.friends !== null) { for (const e of object.friends) { message.friends.push(Friend.fromJSON(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: FriendList): unknown { const obj: any = {}; if (message.friends) { obj.friends = message.friends.map((e) => e ? Friend.toJSON(e) : undefined ); } else { obj.friends = []; } message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial(object: DeepPartial<FriendList>): FriendList { const message = { ...baseFriendList } as FriendList; message.friends = []; if (object.friends !== undefined && object.friends !== null) { for (const e of object.friends) { message.friends.push(Friend.fromPartial(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseGetUsersRequest: object = { ids: "", usernames: "", facebook_ids: "", }; export const GetUsersRequest = { encode( message: GetUsersRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.ids) { writer.uint32(10).string(v!); } for (const v of message.usernames) { writer.uint32(18).string(v!); } for (const v of message.facebook_ids) { writer.uint32(26).string(v!); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): GetUsersRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseGetUsersRequest } as GetUsersRequest; message.ids = []; message.usernames = []; message.facebook_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.ids.push(reader.string()); break; case 2: message.usernames.push(reader.string()); break; case 3: message.facebook_ids.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): GetUsersRequest { const message = { ...baseGetUsersRequest } as GetUsersRequest; message.ids = []; message.usernames = []; message.facebook_ids = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(String(e)); } } if (object.usernames !== undefined && object.usernames !== null) { for (const e of object.usernames) { message.usernames.push(String(e)); } } if (object.facebook_ids !== undefined && object.facebook_ids !== null) { for (const e of object.facebook_ids) { message.facebook_ids.push(String(e)); } } return message; }, toJSON(message: GetUsersRequest): unknown { const obj: any = {}; if (message.ids) { obj.ids = message.ids.map((e) => e); } else { obj.ids = []; } if (message.usernames) { obj.usernames = message.usernames.map((e) => e); } else { obj.usernames = []; } if (message.facebook_ids) { obj.facebook_ids = message.facebook_ids.map((e) => e); } else { obj.facebook_ids = []; } return obj; }, fromPartial(object: DeepPartial<GetUsersRequest>): GetUsersRequest { const message = { ...baseGetUsersRequest } as GetUsersRequest; message.ids = []; message.usernames = []; message.facebook_ids = []; if (object.ids !== undefined && object.ids !== null) { for (const e of object.ids) { message.ids.push(e); } } if (object.usernames !== undefined && object.usernames !== null) { for (const e of object.usernames) { message.usernames.push(e); } } if (object.facebook_ids !== undefined && object.facebook_ids !== null) { for (const e of object.facebook_ids) { message.facebook_ids.push(e); } } return message; }, }; const baseGroup: object = { id: "", creator_id: "", name: "", description: "", lang_tag: "", metadata: "", avatar_url: "", edge_count: 0, max_count: 0, }; export const Group = { encode(message: Group, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.id !== "") { writer.uint32(10).string(message.id); } if (message.creator_id !== "") { writer.uint32(18).string(message.creator_id); } if (message.name !== "") { writer.uint32(26).string(message.name); } if (message.description !== "") { writer.uint32(34).string(message.description); } if (message.lang_tag !== "") { writer.uint32(42).string(message.lang_tag); } if (message.metadata !== "") { writer.uint32(50).string(message.metadata); } if (message.avatar_url !== "") { writer.uint32(58).string(message.avatar_url); } if (message.open !== undefined) { BoolValue.encode( { value: message.open! }, writer.uint32(66).fork() ).ldelim(); } if (message.edge_count !== 0) { writer.uint32(72).int32(message.edge_count); } if (message.max_count !== 0) { writer.uint32(80).int32(message.max_count); } if (message.create_time !== undefined) { Timestamp.encode( toTimestamp(message.create_time), writer.uint32(90).fork() ).ldelim(); } if (message.update_time !== undefined) { Timestamp.encode( toTimestamp(message.update_time), writer.uint32(98).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Group { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseGroup } as Group; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.creator_id = reader.string(); break; case 3: message.name = reader.string(); break; case 4: message.description = reader.string(); break; case 5: message.lang_tag = reader.string(); break; case 6: message.metadata = reader.string(); break; case 7: message.avatar_url = reader.string(); break; case 8: message.open = BoolValue.decode(reader, reader.uint32()).value; break; case 9: message.edge_count = reader.int32(); break; case 10: message.max_count = reader.int32(); break; case 11: message.create_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 12: message.update_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Group { const message = { ...baseGroup } as Group; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } if (object.creator_id !== undefined && object.creator_id !== null) { message.creator_id = String(object.creator_id); } if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } if (object.description !== undefined && object.description !== null) { message.description = String(object.description); } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = String(object.lang_tag); } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = String(object.metadata); } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = String(object.avatar_url); } if (object.open !== undefined && object.open !== null) { message.open = Boolean(object.open); } if (object.edge_count !== undefined && object.edge_count !== null) { message.edge_count = Number(object.edge_count); } if (object.max_count !== undefined && object.max_count !== null) { message.max_count = Number(object.max_count); } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = fromJsonTimestamp(object.create_time); } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = fromJsonTimestamp(object.update_time); } return message; }, toJSON(message: Group): unknown { const obj: any = {}; message.id !== undefined && (obj.id = message.id); message.creator_id !== undefined && (obj.creator_id = message.creator_id); message.name !== undefined && (obj.name = message.name); message.description !== undefined && (obj.description = message.description); message.lang_tag !== undefined && (obj.lang_tag = message.lang_tag); message.metadata !== undefined && (obj.metadata = message.metadata); message.avatar_url !== undefined && (obj.avatar_url = message.avatar_url); message.open !== undefined && (obj.open = message.open); message.edge_count !== undefined && (obj.edge_count = message.edge_count); message.max_count !== undefined && (obj.max_count = message.max_count); message.create_time !== undefined && (obj.create_time = message.create_time.toISOString()); message.update_time !== undefined && (obj.update_time = message.update_time.toISOString()); return obj; }, fromPartial(object: DeepPartial<Group>): Group { const message = { ...baseGroup } as Group; if (object.id !== undefined && object.id !== null) { message.id = object.id; } if (object.creator_id !== undefined && object.creator_id !== null) { message.creator_id = object.creator_id; } if (object.name !== undefined && object.name !== null) { message.name = object.name; } if (object.description !== undefined && object.description !== null) { message.description = object.description; } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = object.lang_tag; } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = object.metadata; } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = object.avatar_url; } if (object.open !== undefined && object.open !== null) { message.open = object.open; } if (object.edge_count !== undefined && object.edge_count !== null) { message.edge_count = object.edge_count; } if (object.max_count !== undefined && object.max_count !== null) { message.max_count = object.max_count; } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = object.create_time; } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = object.update_time; } return message; }, }; const baseGroupList: object = { cursor: "" }; export const GroupList = { encode( message: GroupList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.groups) { Group.encode(v!, writer.uint32(10).fork()).ldelim(); } if (message.cursor !== "") { writer.uint32(18).string(message.cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): GroupList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseGroupList } as GroupList; message.groups = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.groups.push(Group.decode(reader, reader.uint32())); break; case 2: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): GroupList { const message = { ...baseGroupList } as GroupList; message.groups = []; if (object.groups !== undefined && object.groups !== null) { for (const e of object.groups) { message.groups.push(Group.fromJSON(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: GroupList): unknown { const obj: any = {}; if (message.groups) { obj.groups = message.groups.map((e) => (e ? Group.toJSON(e) : undefined)); } else { obj.groups = []; } message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial(object: DeepPartial<GroupList>): GroupList { const message = { ...baseGroupList } as GroupList; message.groups = []; if (object.groups !== undefined && object.groups !== null) { for (const e of object.groups) { message.groups.push(Group.fromPartial(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseGroupUserList: object = { cursor: "" }; export const GroupUserList = { encode( message: GroupUserList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.group_users) { GroupUserList_GroupUser.encode(v!, writer.uint32(10).fork()).ldelim(); } if (message.cursor !== "") { writer.uint32(18).string(message.cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): GroupUserList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseGroupUserList } as GroupUserList; message.group_users = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_users.push( GroupUserList_GroupUser.decode(reader, reader.uint32()) ); break; case 2: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): GroupUserList { const message = { ...baseGroupUserList } as GroupUserList; message.group_users = []; if (object.group_users !== undefined && object.group_users !== null) { for (const e of object.group_users) { message.group_users.push(GroupUserList_GroupUser.fromJSON(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: GroupUserList): unknown { const obj: any = {}; if (message.group_users) { obj.group_users = message.group_users.map((e) => e ? GroupUserList_GroupUser.toJSON(e) : undefined ); } else { obj.group_users = []; } message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial(object: DeepPartial<GroupUserList>): GroupUserList { const message = { ...baseGroupUserList } as GroupUserList; message.group_users = []; if (object.group_users !== undefined && object.group_users !== null) { for (const e of object.group_users) { message.group_users.push(GroupUserList_GroupUser.fromPartial(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseGroupUserList_GroupUser: object = {}; export const GroupUserList_GroupUser = { encode( message: GroupUserList_GroupUser, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.user !== undefined) { User.encode(message.user, writer.uint32(10).fork()).ldelim(); } if (message.state !== undefined) { Int32Value.encode( { value: message.state! }, writer.uint32(18).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): GroupUserList_GroupUser { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseGroupUserList_GroupUser, } as GroupUserList_GroupUser; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.user = User.decode(reader, reader.uint32()); break; case 2: message.state = Int32Value.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): GroupUserList_GroupUser { const message = { ...baseGroupUserList_GroupUser, } as GroupUserList_GroupUser; if (object.user !== undefined && object.user !== null) { message.user = User.fromJSON(object.user); } if (object.state !== undefined && object.state !== null) { message.state = Number(object.state); } return message; }, toJSON(message: GroupUserList_GroupUser): unknown { const obj: any = {}; message.user !== undefined && (obj.user = message.user ? User.toJSON(message.user) : undefined); message.state !== undefined && (obj.state = message.state); return obj; }, fromPartial( object: DeepPartial<GroupUserList_GroupUser> ): GroupUserList_GroupUser { const message = { ...baseGroupUserList_GroupUser, } as GroupUserList_GroupUser; if (object.user !== undefined && object.user !== null) { message.user = User.fromPartial(object.user); } if (object.state !== undefined && object.state !== null) { message.state = object.state; } return message; }, }; const baseImportFacebookFriendsRequest: object = {}; export const ImportFacebookFriendsRequest = { encode( message: ImportFacebookFriendsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountFacebook.encode( message.account, writer.uint32(10).fork() ).ldelim(); } if (message.reset !== undefined) { BoolValue.encode( { value: message.reset! }, writer.uint32(18).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ImportFacebookFriendsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseImportFacebookFriendsRequest, } as ImportFacebookFriendsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountFacebook.decode(reader, reader.uint32()); break; case 2: message.reset = BoolValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ImportFacebookFriendsRequest { const message = { ...baseImportFacebookFriendsRequest, } as ImportFacebookFriendsRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountFacebook.fromJSON(object.account); } if (object.reset !== undefined && object.reset !== null) { message.reset = Boolean(object.reset); } return message; }, toJSON(message: ImportFacebookFriendsRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountFacebook.toJSON(message.account) : undefined); message.reset !== undefined && (obj.reset = message.reset); return obj; }, fromPartial( object: DeepPartial<ImportFacebookFriendsRequest> ): ImportFacebookFriendsRequest { const message = { ...baseImportFacebookFriendsRequest, } as ImportFacebookFriendsRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountFacebook.fromPartial(object.account); } if (object.reset !== undefined && object.reset !== null) { message.reset = object.reset; } return message; }, }; const baseImportSteamFriendsRequest: object = {}; export const ImportSteamFriendsRequest = { encode( message: ImportSteamFriendsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountSteam.encode(message.account, writer.uint32(10).fork()).ldelim(); } if (message.reset !== undefined) { BoolValue.encode( { value: message.reset! }, writer.uint32(18).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ImportSteamFriendsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseImportSteamFriendsRequest, } as ImportSteamFriendsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountSteam.decode(reader, reader.uint32()); break; case 2: message.reset = BoolValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ImportSteamFriendsRequest { const message = { ...baseImportSteamFriendsRequest, } as ImportSteamFriendsRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountSteam.fromJSON(object.account); } if (object.reset !== undefined && object.reset !== null) { message.reset = Boolean(object.reset); } return message; }, toJSON(message: ImportSteamFriendsRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountSteam.toJSON(message.account) : undefined); message.reset !== undefined && (obj.reset = message.reset); return obj; }, fromPartial( object: DeepPartial<ImportSteamFriendsRequest> ): ImportSteamFriendsRequest { const message = { ...baseImportSteamFriendsRequest, } as ImportSteamFriendsRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountSteam.fromPartial(object.account); } if (object.reset !== undefined && object.reset !== null) { message.reset = object.reset; } return message; }, }; const baseJoinGroupRequest: object = { group_id: "" }; export const JoinGroupRequest = { encode( message: JoinGroupRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): JoinGroupRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseJoinGroupRequest } as JoinGroupRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): JoinGroupRequest { const message = { ...baseJoinGroupRequest } as JoinGroupRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } return message; }, toJSON(message: JoinGroupRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); return obj; }, fromPartial(object: DeepPartial<JoinGroupRequest>): JoinGroupRequest { const message = { ...baseJoinGroupRequest } as JoinGroupRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } return message; }, }; const baseJoinTournamentRequest: object = { tournament_id: "" }; export const JoinTournamentRequest = { encode( message: JoinTournamentRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.tournament_id !== "") { writer.uint32(10).string(message.tournament_id); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): JoinTournamentRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseJoinTournamentRequest } as JoinTournamentRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.tournament_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): JoinTournamentRequest { const message = { ...baseJoinTournamentRequest } as JoinTournamentRequest; if (object.tournament_id !== undefined && object.tournament_id !== null) { message.tournament_id = String(object.tournament_id); } return message; }, toJSON(message: JoinTournamentRequest): unknown { const obj: any = {}; message.tournament_id !== undefined && (obj.tournament_id = message.tournament_id); return obj; }, fromPartial( object: DeepPartial<JoinTournamentRequest> ): JoinTournamentRequest { const message = { ...baseJoinTournamentRequest } as JoinTournamentRequest; if (object.tournament_id !== undefined && object.tournament_id !== null) { message.tournament_id = object.tournament_id; } return message; }, }; const baseKickGroupUsersRequest: object = { group_id: "", user_ids: "" }; export const KickGroupUsersRequest = { encode( message: KickGroupUsersRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } for (const v of message.user_ids) { writer.uint32(18).string(v!); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): KickGroupUsersRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseKickGroupUsersRequest } as KickGroupUsersRequest; message.user_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; case 2: message.user_ids.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): KickGroupUsersRequest { const message = { ...baseKickGroupUsersRequest } as KickGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(String(e)); } } return message; }, toJSON(message: KickGroupUsersRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); if (message.user_ids) { obj.user_ids = message.user_ids.map((e) => e); } else { obj.user_ids = []; } return obj; }, fromPartial( object: DeepPartial<KickGroupUsersRequest> ): KickGroupUsersRequest { const message = { ...baseKickGroupUsersRequest } as KickGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(e); } } return message; }, }; const baseLeaderboardRecord: object = { leaderboard_id: "", owner_id: "", score: 0, subscore: 0, num_score: 0, metadata: "", rank: 0, max_num_score: 0, }; export const LeaderboardRecord = { encode( message: LeaderboardRecord, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.leaderboard_id !== "") { writer.uint32(10).string(message.leaderboard_id); } if (message.owner_id !== "") { writer.uint32(18).string(message.owner_id); } if (message.username !== undefined) { StringValue.encode( { value: message.username! }, writer.uint32(26).fork() ).ldelim(); } if (message.score !== 0) { writer.uint32(32).int64(message.score); } if (message.subscore !== 0) { writer.uint32(40).int64(message.subscore); } if (message.num_score !== 0) { writer.uint32(48).int32(message.num_score); } if (message.metadata !== "") { writer.uint32(58).string(message.metadata); } if (message.create_time !== undefined) { Timestamp.encode( toTimestamp(message.create_time), writer.uint32(66).fork() ).ldelim(); } if (message.update_time !== undefined) { Timestamp.encode( toTimestamp(message.update_time), writer.uint32(74).fork() ).ldelim(); } if (message.expiry_time !== undefined) { Timestamp.encode( toTimestamp(message.expiry_time), writer.uint32(82).fork() ).ldelim(); } if (message.rank !== 0) { writer.uint32(88).int64(message.rank); } if (message.max_num_score !== 0) { writer.uint32(96).uint32(message.max_num_score); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): LeaderboardRecord { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseLeaderboardRecord } as LeaderboardRecord; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.leaderboard_id = reader.string(); break; case 2: message.owner_id = reader.string(); break; case 3: message.username = StringValue.decode(reader, reader.uint32()).value; break; case 4: message.score = longToNumber(reader.int64() as Long); break; case 5: message.subscore = longToNumber(reader.int64() as Long); break; case 6: message.num_score = reader.int32(); break; case 7: message.metadata = reader.string(); break; case 8: message.create_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 9: message.update_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 10: message.expiry_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 11: message.rank = longToNumber(reader.int64() as Long); break; case 12: message.max_num_score = reader.uint32(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): LeaderboardRecord { const message = { ...baseLeaderboardRecord } as LeaderboardRecord; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = String(object.leaderboard_id); } if (object.owner_id !== undefined && object.owner_id !== null) { message.owner_id = String(object.owner_id); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } if (object.score !== undefined && object.score !== null) { message.score = Number(object.score); } if (object.subscore !== undefined && object.subscore !== null) { message.subscore = Number(object.subscore); } if (object.num_score !== undefined && object.num_score !== null) { message.num_score = Number(object.num_score); } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = String(object.metadata); } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = fromJsonTimestamp(object.create_time); } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = fromJsonTimestamp(object.update_time); } if (object.expiry_time !== undefined && object.expiry_time !== null) { message.expiry_time = fromJsonTimestamp(object.expiry_time); } if (object.rank !== undefined && object.rank !== null) { message.rank = Number(object.rank); } if (object.max_num_score !== undefined && object.max_num_score !== null) { message.max_num_score = Number(object.max_num_score); } return message; }, toJSON(message: LeaderboardRecord): unknown { const obj: any = {}; message.leaderboard_id !== undefined && (obj.leaderboard_id = message.leaderboard_id); message.owner_id !== undefined && (obj.owner_id = message.owner_id); message.username !== undefined && (obj.username = message.username); message.score !== undefined && (obj.score = message.score); message.subscore !== undefined && (obj.subscore = message.subscore); message.num_score !== undefined && (obj.num_score = message.num_score); message.metadata !== undefined && (obj.metadata = message.metadata); message.create_time !== undefined && (obj.create_time = message.create_time.toISOString()); message.update_time !== undefined && (obj.update_time = message.update_time.toISOString()); message.expiry_time !== undefined && (obj.expiry_time = message.expiry_time.toISOString()); message.rank !== undefined && (obj.rank = message.rank); message.max_num_score !== undefined && (obj.max_num_score = message.max_num_score); return obj; }, fromPartial(object: DeepPartial<LeaderboardRecord>): LeaderboardRecord { const message = { ...baseLeaderboardRecord } as LeaderboardRecord; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = object.leaderboard_id; } if (object.owner_id !== undefined && object.owner_id !== null) { message.owner_id = object.owner_id; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } if (object.score !== undefined && object.score !== null) { message.score = object.score; } if (object.subscore !== undefined && object.subscore !== null) { message.subscore = object.subscore; } if (object.num_score !== undefined && object.num_score !== null) { message.num_score = object.num_score; } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = object.metadata; } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = object.create_time; } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = object.update_time; } if (object.expiry_time !== undefined && object.expiry_time !== null) { message.expiry_time = object.expiry_time; } if (object.rank !== undefined && object.rank !== null) { message.rank = object.rank; } if (object.max_num_score !== undefined && object.max_num_score !== null) { message.max_num_score = object.max_num_score; } return message; }, }; const baseLeaderboardRecordList: object = { next_cursor: "", prev_cursor: "" }; export const LeaderboardRecordList = { encode( message: LeaderboardRecordList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.records) { LeaderboardRecord.encode(v!, writer.uint32(10).fork()).ldelim(); } for (const v of message.owner_records) { LeaderboardRecord.encode(v!, writer.uint32(18).fork()).ldelim(); } if (message.next_cursor !== "") { writer.uint32(26).string(message.next_cursor); } if (message.prev_cursor !== "") { writer.uint32(34).string(message.prev_cursor); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): LeaderboardRecordList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseLeaderboardRecordList } as LeaderboardRecordList; message.records = []; message.owner_records = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.records.push( LeaderboardRecord.decode(reader, reader.uint32()) ); break; case 2: message.owner_records.push( LeaderboardRecord.decode(reader, reader.uint32()) ); break; case 3: message.next_cursor = reader.string(); break; case 4: message.prev_cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): LeaderboardRecordList { const message = { ...baseLeaderboardRecordList } as LeaderboardRecordList; message.records = []; message.owner_records = []; if (object.records !== undefined && object.records !== null) { for (const e of object.records) { message.records.push(LeaderboardRecord.fromJSON(e)); } } if (object.owner_records !== undefined && object.owner_records !== null) { for (const e of object.owner_records) { message.owner_records.push(LeaderboardRecord.fromJSON(e)); } } if (object.next_cursor !== undefined && object.next_cursor !== null) { message.next_cursor = String(object.next_cursor); } if (object.prev_cursor !== undefined && object.prev_cursor !== null) { message.prev_cursor = String(object.prev_cursor); } return message; }, toJSON(message: LeaderboardRecordList): unknown { const obj: any = {}; if (message.records) { obj.records = message.records.map((e) => e ? LeaderboardRecord.toJSON(e) : undefined ); } else { obj.records = []; } if (message.owner_records) { obj.owner_records = message.owner_records.map((e) => e ? LeaderboardRecord.toJSON(e) : undefined ); } else { obj.owner_records = []; } message.next_cursor !== undefined && (obj.next_cursor = message.next_cursor); message.prev_cursor !== undefined && (obj.prev_cursor = message.prev_cursor); return obj; }, fromPartial( object: DeepPartial<LeaderboardRecordList> ): LeaderboardRecordList { const message = { ...baseLeaderboardRecordList } as LeaderboardRecordList; message.records = []; message.owner_records = []; if (object.records !== undefined && object.records !== null) { for (const e of object.records) { message.records.push(LeaderboardRecord.fromPartial(e)); } } if (object.owner_records !== undefined && object.owner_records !== null) { for (const e of object.owner_records) { message.owner_records.push(LeaderboardRecord.fromPartial(e)); } } if (object.next_cursor !== undefined && object.next_cursor !== null) { message.next_cursor = object.next_cursor; } if (object.prev_cursor !== undefined && object.prev_cursor !== null) { message.prev_cursor = object.prev_cursor; } return message; }, }; const baseLeaveGroupRequest: object = { group_id: "" }; export const LeaveGroupRequest = { encode( message: LeaveGroupRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): LeaveGroupRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseLeaveGroupRequest } as LeaveGroupRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): LeaveGroupRequest { const message = { ...baseLeaveGroupRequest } as LeaveGroupRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } return message; }, toJSON(message: LeaveGroupRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); return obj; }, fromPartial(object: DeepPartial<LeaveGroupRequest>): LeaveGroupRequest { const message = { ...baseLeaveGroupRequest } as LeaveGroupRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } return message; }, }; const baseLinkFacebookRequest: object = {}; export const LinkFacebookRequest = { encode( message: LinkFacebookRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountFacebook.encode( message.account, writer.uint32(10).fork() ).ldelim(); } if (message.sync !== undefined) { BoolValue.encode( { value: message.sync! }, writer.uint32(18).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): LinkFacebookRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseLinkFacebookRequest } as LinkFacebookRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountFacebook.decode(reader, reader.uint32()); break; case 2: message.sync = BoolValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): LinkFacebookRequest { const message = { ...baseLinkFacebookRequest } as LinkFacebookRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountFacebook.fromJSON(object.account); } if (object.sync !== undefined && object.sync !== null) { message.sync = Boolean(object.sync); } return message; }, toJSON(message: LinkFacebookRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountFacebook.toJSON(message.account) : undefined); message.sync !== undefined && (obj.sync = message.sync); return obj; }, fromPartial(object: DeepPartial<LinkFacebookRequest>): LinkFacebookRequest { const message = { ...baseLinkFacebookRequest } as LinkFacebookRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountFacebook.fromPartial(object.account); } if (object.sync !== undefined && object.sync !== null) { message.sync = object.sync; } return message; }, }; const baseLinkSteamRequest: object = {}; export const LinkSteamRequest = { encode( message: LinkSteamRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.account !== undefined) { AccountSteam.encode(message.account, writer.uint32(10).fork()).ldelim(); } if (message.sync !== undefined) { BoolValue.encode( { value: message.sync! }, writer.uint32(18).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): LinkSteamRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseLinkSteamRequest } as LinkSteamRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.account = AccountSteam.decode(reader, reader.uint32()); break; case 2: message.sync = BoolValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): LinkSteamRequest { const message = { ...baseLinkSteamRequest } as LinkSteamRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountSteam.fromJSON(object.account); } if (object.sync !== undefined && object.sync !== null) { message.sync = Boolean(object.sync); } return message; }, toJSON(message: LinkSteamRequest): unknown { const obj: any = {}; message.account !== undefined && (obj.account = message.account ? AccountSteam.toJSON(message.account) : undefined); message.sync !== undefined && (obj.sync = message.sync); return obj; }, fromPartial(object: DeepPartial<LinkSteamRequest>): LinkSteamRequest { const message = { ...baseLinkSteamRequest } as LinkSteamRequest; if (object.account !== undefined && object.account !== null) { message.account = AccountSteam.fromPartial(object.account); } if (object.sync !== undefined && object.sync !== null) { message.sync = object.sync; } return message; }, }; const baseListChannelMessagesRequest: object = { channel_id: "", cursor: "" }; export const ListChannelMessagesRequest = { encode( message: ListChannelMessagesRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.channel_id !== "") { writer.uint32(10).string(message.channel_id); } if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(18).fork() ).ldelim(); } if (message.forward !== undefined) { BoolValue.encode( { value: message.forward! }, writer.uint32(26).fork() ).ldelim(); } if (message.cursor !== "") { writer.uint32(34).string(message.cursor); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListChannelMessagesRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListChannelMessagesRequest, } as ListChannelMessagesRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.channel_id = reader.string(); break; case 2: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 3: message.forward = BoolValue.decode(reader, reader.uint32()).value; break; case 4: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListChannelMessagesRequest { const message = { ...baseListChannelMessagesRequest, } as ListChannelMessagesRequest; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = String(object.channel_id); } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.forward !== undefined && object.forward !== null) { message.forward = Boolean(object.forward); } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: ListChannelMessagesRequest): unknown { const obj: any = {}; message.channel_id !== undefined && (obj.channel_id = message.channel_id); message.limit !== undefined && (obj.limit = message.limit); message.forward !== undefined && (obj.forward = message.forward); message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial( object: DeepPartial<ListChannelMessagesRequest> ): ListChannelMessagesRequest { const message = { ...baseListChannelMessagesRequest, } as ListChannelMessagesRequest; if (object.channel_id !== undefined && object.channel_id !== null) { message.channel_id = object.channel_id; } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.forward !== undefined && object.forward !== null) { message.forward = object.forward; } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseListFriendsRequest: object = { cursor: "" }; export const ListFriendsRequest = { encode( message: ListFriendsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(10).fork() ).ldelim(); } if (message.state !== undefined) { Int32Value.encode( { value: message.state! }, writer.uint32(18).fork() ).ldelim(); } if (message.cursor !== "") { writer.uint32(26).string(message.cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ListFriendsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListFriendsRequest } as ListFriendsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 2: message.state = Int32Value.decode(reader, reader.uint32()).value; break; case 3: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListFriendsRequest { const message = { ...baseListFriendsRequest } as ListFriendsRequest; if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.state !== undefined && object.state !== null) { message.state = Number(object.state); } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: ListFriendsRequest): unknown { const obj: any = {}; message.limit !== undefined && (obj.limit = message.limit); message.state !== undefined && (obj.state = message.state); message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial(object: DeepPartial<ListFriendsRequest>): ListFriendsRequest { const message = { ...baseListFriendsRequest } as ListFriendsRequest; if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.state !== undefined && object.state !== null) { message.state = object.state; } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseListGroupsRequest: object = { name: "", cursor: "" }; export const ListGroupsRequest = { encode( message: ListGroupsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.name !== "") { writer.uint32(10).string(message.name); } if (message.cursor !== "") { writer.uint32(18).string(message.cursor); } if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(26).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ListGroupsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListGroupsRequest } as ListGroupsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.name = reader.string(); break; case 2: message.cursor = reader.string(); break; case 3: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListGroupsRequest { const message = { ...baseListGroupsRequest } as ListGroupsRequest; if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } return message; }, toJSON(message: ListGroupsRequest): unknown { const obj: any = {}; message.name !== undefined && (obj.name = message.name); message.cursor !== undefined && (obj.cursor = message.cursor); message.limit !== undefined && (obj.limit = message.limit); return obj; }, fromPartial(object: DeepPartial<ListGroupsRequest>): ListGroupsRequest { const message = { ...baseListGroupsRequest } as ListGroupsRequest; if (object.name !== undefined && object.name !== null) { message.name = object.name; } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } return message; }, }; const baseListGroupUsersRequest: object = { group_id: "", cursor: "" }; export const ListGroupUsersRequest = { encode( message: ListGroupUsersRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(18).fork() ).ldelim(); } if (message.state !== undefined) { Int32Value.encode( { value: message.state! }, writer.uint32(26).fork() ).ldelim(); } if (message.cursor !== "") { writer.uint32(34).string(message.cursor); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListGroupUsersRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListGroupUsersRequest } as ListGroupUsersRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; case 2: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 3: message.state = Int32Value.decode(reader, reader.uint32()).value; break; case 4: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListGroupUsersRequest { const message = { ...baseListGroupUsersRequest } as ListGroupUsersRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.state !== undefined && object.state !== null) { message.state = Number(object.state); } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: ListGroupUsersRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); message.limit !== undefined && (obj.limit = message.limit); message.state !== undefined && (obj.state = message.state); message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial( object: DeepPartial<ListGroupUsersRequest> ): ListGroupUsersRequest { const message = { ...baseListGroupUsersRequest } as ListGroupUsersRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.state !== undefined && object.state !== null) { message.state = object.state; } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseListLeaderboardRecordsAroundOwnerRequest: object = { leaderboard_id: "", owner_id: "", }; export const ListLeaderboardRecordsAroundOwnerRequest = { encode( message: ListLeaderboardRecordsAroundOwnerRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.leaderboard_id !== "") { writer.uint32(10).string(message.leaderboard_id); } if (message.limit !== undefined) { UInt32Value.encode( { value: message.limit! }, writer.uint32(18).fork() ).ldelim(); } if (message.owner_id !== "") { writer.uint32(26).string(message.owner_id); } if (message.expiry !== undefined) { Int64Value.encode( { value: message.expiry! }, writer.uint32(34).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListLeaderboardRecordsAroundOwnerRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListLeaderboardRecordsAroundOwnerRequest, } as ListLeaderboardRecordsAroundOwnerRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.leaderboard_id = reader.string(); break; case 2: message.limit = UInt32Value.decode(reader, reader.uint32()).value; break; case 3: message.owner_id = reader.string(); break; case 4: message.expiry = Int64Value.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListLeaderboardRecordsAroundOwnerRequest { const message = { ...baseListLeaderboardRecordsAroundOwnerRequest, } as ListLeaderboardRecordsAroundOwnerRequest; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = String(object.leaderboard_id); } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.owner_id !== undefined && object.owner_id !== null) { message.owner_id = String(object.owner_id); } if (object.expiry !== undefined && object.expiry !== null) { message.expiry = Number(object.expiry); } return message; }, toJSON(message: ListLeaderboardRecordsAroundOwnerRequest): unknown { const obj: any = {}; message.leaderboard_id !== undefined && (obj.leaderboard_id = message.leaderboard_id); message.limit !== undefined && (obj.limit = message.limit); message.owner_id !== undefined && (obj.owner_id = message.owner_id); message.expiry !== undefined && (obj.expiry = message.expiry); return obj; }, fromPartial( object: DeepPartial<ListLeaderboardRecordsAroundOwnerRequest> ): ListLeaderboardRecordsAroundOwnerRequest { const message = { ...baseListLeaderboardRecordsAroundOwnerRequest, } as ListLeaderboardRecordsAroundOwnerRequest; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = object.leaderboard_id; } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.owner_id !== undefined && object.owner_id !== null) { message.owner_id = object.owner_id; } if (object.expiry !== undefined && object.expiry !== null) { message.expiry = object.expiry; } return message; }, }; const baseListLeaderboardRecordsRequest: object = { leaderboard_id: "", owner_ids: "", cursor: "", }; export const ListLeaderboardRecordsRequest = { encode( message: ListLeaderboardRecordsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.leaderboard_id !== "") { writer.uint32(10).string(message.leaderboard_id); } for (const v of message.owner_ids) { writer.uint32(18).string(v!); } if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(26).fork() ).ldelim(); } if (message.cursor !== "") { writer.uint32(34).string(message.cursor); } if (message.expiry !== undefined) { Int64Value.encode( { value: message.expiry! }, writer.uint32(42).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListLeaderboardRecordsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListLeaderboardRecordsRequest, } as ListLeaderboardRecordsRequest; message.owner_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.leaderboard_id = reader.string(); break; case 2: message.owner_ids.push(reader.string()); break; case 3: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 4: message.cursor = reader.string(); break; case 5: message.expiry = Int64Value.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListLeaderboardRecordsRequest { const message = { ...baseListLeaderboardRecordsRequest, } as ListLeaderboardRecordsRequest; message.owner_ids = []; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = String(object.leaderboard_id); } if (object.owner_ids !== undefined && object.owner_ids !== null) { for (const e of object.owner_ids) { message.owner_ids.push(String(e)); } } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } if (object.expiry !== undefined && object.expiry !== null) { message.expiry = Number(object.expiry); } return message; }, toJSON(message: ListLeaderboardRecordsRequest): unknown { const obj: any = {}; message.leaderboard_id !== undefined && (obj.leaderboard_id = message.leaderboard_id); if (message.owner_ids) { obj.owner_ids = message.owner_ids.map((e) => e); } else { obj.owner_ids = []; } message.limit !== undefined && (obj.limit = message.limit); message.cursor !== undefined && (obj.cursor = message.cursor); message.expiry !== undefined && (obj.expiry = message.expiry); return obj; }, fromPartial( object: DeepPartial<ListLeaderboardRecordsRequest> ): ListLeaderboardRecordsRequest { const message = { ...baseListLeaderboardRecordsRequest, } as ListLeaderboardRecordsRequest; message.owner_ids = []; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = object.leaderboard_id; } if (object.owner_ids !== undefined && object.owner_ids !== null) { for (const e of object.owner_ids) { message.owner_ids.push(e); } } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } if (object.expiry !== undefined && object.expiry !== null) { message.expiry = object.expiry; } return message; }, }; const baseListMatchesRequest: object = {}; export const ListMatchesRequest = { encode( message: ListMatchesRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(10).fork() ).ldelim(); } if (message.authoritative !== undefined) { BoolValue.encode( { value: message.authoritative! }, writer.uint32(18).fork() ).ldelim(); } if (message.label !== undefined) { StringValue.encode( { value: message.label! }, writer.uint32(26).fork() ).ldelim(); } if (message.min_size !== undefined) { Int32Value.encode( { value: message.min_size! }, writer.uint32(34).fork() ).ldelim(); } if (message.max_size !== undefined) { Int32Value.encode( { value: message.max_size! }, writer.uint32(42).fork() ).ldelim(); } if (message.query !== undefined) { StringValue.encode( { value: message.query! }, writer.uint32(50).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ListMatchesRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListMatchesRequest } as ListMatchesRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 2: message.authoritative = BoolValue.decode( reader, reader.uint32() ).value; break; case 3: message.label = StringValue.decode(reader, reader.uint32()).value; break; case 4: message.min_size = Int32Value.decode(reader, reader.uint32()).value; break; case 5: message.max_size = Int32Value.decode(reader, reader.uint32()).value; break; case 6: message.query = StringValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListMatchesRequest { const message = { ...baseListMatchesRequest } as ListMatchesRequest; if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.authoritative !== undefined && object.authoritative !== null) { message.authoritative = Boolean(object.authoritative); } if (object.label !== undefined && object.label !== null) { message.label = String(object.label); } if (object.min_size !== undefined && object.min_size !== null) { message.min_size = Number(object.min_size); } if (object.max_size !== undefined && object.max_size !== null) { message.max_size = Number(object.max_size); } if (object.query !== undefined && object.query !== null) { message.query = String(object.query); } return message; }, toJSON(message: ListMatchesRequest): unknown { const obj: any = {}; message.limit !== undefined && (obj.limit = message.limit); message.authoritative !== undefined && (obj.authoritative = message.authoritative); message.label !== undefined && (obj.label = message.label); message.min_size !== undefined && (obj.min_size = message.min_size); message.max_size !== undefined && (obj.max_size = message.max_size); message.query !== undefined && (obj.query = message.query); return obj; }, fromPartial(object: DeepPartial<ListMatchesRequest>): ListMatchesRequest { const message = { ...baseListMatchesRequest } as ListMatchesRequest; if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.authoritative !== undefined && object.authoritative !== null) { message.authoritative = object.authoritative; } if (object.label !== undefined && object.label !== null) { message.label = object.label; } if (object.min_size !== undefined && object.min_size !== null) { message.min_size = object.min_size; } if (object.max_size !== undefined && object.max_size !== null) { message.max_size = object.max_size; } if (object.query !== undefined && object.query !== null) { message.query = object.query; } return message; }, }; const baseListNotificationsRequest: object = { cacheable_cursor: "" }; export const ListNotificationsRequest = { encode( message: ListNotificationsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(10).fork() ).ldelim(); } if (message.cacheable_cursor !== "") { writer.uint32(18).string(message.cacheable_cursor); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListNotificationsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListNotificationsRequest, } as ListNotificationsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 2: message.cacheable_cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListNotificationsRequest { const message = { ...baseListNotificationsRequest, } as ListNotificationsRequest; if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if ( object.cacheable_cursor !== undefined && object.cacheable_cursor !== null ) { message.cacheable_cursor = String(object.cacheable_cursor); } return message; }, toJSON(message: ListNotificationsRequest): unknown { const obj: any = {}; message.limit !== undefined && (obj.limit = message.limit); message.cacheable_cursor !== undefined && (obj.cacheable_cursor = message.cacheable_cursor); return obj; }, fromPartial( object: DeepPartial<ListNotificationsRequest> ): ListNotificationsRequest { const message = { ...baseListNotificationsRequest, } as ListNotificationsRequest; if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if ( object.cacheable_cursor !== undefined && object.cacheable_cursor !== null ) { message.cacheable_cursor = object.cacheable_cursor; } return message; }, }; const baseListStorageObjectsRequest: object = { user_id: "", collection: "", cursor: "", }; export const ListStorageObjectsRequest = { encode( message: ListStorageObjectsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.user_id !== "") { writer.uint32(10).string(message.user_id); } if (message.collection !== "") { writer.uint32(18).string(message.collection); } if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(26).fork() ).ldelim(); } if (message.cursor !== "") { writer.uint32(34).string(message.cursor); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListStorageObjectsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListStorageObjectsRequest, } as ListStorageObjectsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.user_id = reader.string(); break; case 2: message.collection = reader.string(); break; case 3: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 4: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListStorageObjectsRequest { const message = { ...baseListStorageObjectsRequest, } as ListStorageObjectsRequest; if (object.user_id !== undefined && object.user_id !== null) { message.user_id = String(object.user_id); } if (object.collection !== undefined && object.collection !== null) { message.collection = String(object.collection); } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: ListStorageObjectsRequest): unknown { const obj: any = {}; message.user_id !== undefined && (obj.user_id = message.user_id); message.collection !== undefined && (obj.collection = message.collection); message.limit !== undefined && (obj.limit = message.limit); message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial( object: DeepPartial<ListStorageObjectsRequest> ): ListStorageObjectsRequest { const message = { ...baseListStorageObjectsRequest, } as ListStorageObjectsRequest; if (object.user_id !== undefined && object.user_id !== null) { message.user_id = object.user_id; } if (object.collection !== undefined && object.collection !== null) { message.collection = object.collection; } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseListTournamentRecordsAroundOwnerRequest: object = { tournament_id: "", owner_id: "", }; export const ListTournamentRecordsAroundOwnerRequest = { encode( message: ListTournamentRecordsAroundOwnerRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.tournament_id !== "") { writer.uint32(10).string(message.tournament_id); } if (message.limit !== undefined) { UInt32Value.encode( { value: message.limit! }, writer.uint32(18).fork() ).ldelim(); } if (message.owner_id !== "") { writer.uint32(26).string(message.owner_id); } if (message.expiry !== undefined) { Int64Value.encode( { value: message.expiry! }, writer.uint32(34).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListTournamentRecordsAroundOwnerRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListTournamentRecordsAroundOwnerRequest, } as ListTournamentRecordsAroundOwnerRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.tournament_id = reader.string(); break; case 2: message.limit = UInt32Value.decode(reader, reader.uint32()).value; break; case 3: message.owner_id = reader.string(); break; case 4: message.expiry = Int64Value.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListTournamentRecordsAroundOwnerRequest { const message = { ...baseListTournamentRecordsAroundOwnerRequest, } as ListTournamentRecordsAroundOwnerRequest; if (object.tournament_id !== undefined && object.tournament_id !== null) { message.tournament_id = String(object.tournament_id); } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.owner_id !== undefined && object.owner_id !== null) { message.owner_id = String(object.owner_id); } if (object.expiry !== undefined && object.expiry !== null) { message.expiry = Number(object.expiry); } return message; }, toJSON(message: ListTournamentRecordsAroundOwnerRequest): unknown { const obj: any = {}; message.tournament_id !== undefined && (obj.tournament_id = message.tournament_id); message.limit !== undefined && (obj.limit = message.limit); message.owner_id !== undefined && (obj.owner_id = message.owner_id); message.expiry !== undefined && (obj.expiry = message.expiry); return obj; }, fromPartial( object: DeepPartial<ListTournamentRecordsAroundOwnerRequest> ): ListTournamentRecordsAroundOwnerRequest { const message = { ...baseListTournamentRecordsAroundOwnerRequest, } as ListTournamentRecordsAroundOwnerRequest; if (object.tournament_id !== undefined && object.tournament_id !== null) { message.tournament_id = object.tournament_id; } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.owner_id !== undefined && object.owner_id !== null) { message.owner_id = object.owner_id; } if (object.expiry !== undefined && object.expiry !== null) { message.expiry = object.expiry; } return message; }, }; const baseListTournamentRecordsRequest: object = { tournament_id: "", owner_ids: "", cursor: "", }; export const ListTournamentRecordsRequest = { encode( message: ListTournamentRecordsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.tournament_id !== "") { writer.uint32(10).string(message.tournament_id); } for (const v of message.owner_ids) { writer.uint32(18).string(v!); } if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(26).fork() ).ldelim(); } if (message.cursor !== "") { writer.uint32(34).string(message.cursor); } if (message.expiry !== undefined) { Int64Value.encode( { value: message.expiry! }, writer.uint32(42).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListTournamentRecordsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListTournamentRecordsRequest, } as ListTournamentRecordsRequest; message.owner_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.tournament_id = reader.string(); break; case 2: message.owner_ids.push(reader.string()); break; case 3: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 4: message.cursor = reader.string(); break; case 5: message.expiry = Int64Value.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListTournamentRecordsRequest { const message = { ...baseListTournamentRecordsRequest, } as ListTournamentRecordsRequest; message.owner_ids = []; if (object.tournament_id !== undefined && object.tournament_id !== null) { message.tournament_id = String(object.tournament_id); } if (object.owner_ids !== undefined && object.owner_ids !== null) { for (const e of object.owner_ids) { message.owner_ids.push(String(e)); } } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } if (object.expiry !== undefined && object.expiry !== null) { message.expiry = Number(object.expiry); } return message; }, toJSON(message: ListTournamentRecordsRequest): unknown { const obj: any = {}; message.tournament_id !== undefined && (obj.tournament_id = message.tournament_id); if (message.owner_ids) { obj.owner_ids = message.owner_ids.map((e) => e); } else { obj.owner_ids = []; } message.limit !== undefined && (obj.limit = message.limit); message.cursor !== undefined && (obj.cursor = message.cursor); message.expiry !== undefined && (obj.expiry = message.expiry); return obj; }, fromPartial( object: DeepPartial<ListTournamentRecordsRequest> ): ListTournamentRecordsRequest { const message = { ...baseListTournamentRecordsRequest, } as ListTournamentRecordsRequest; message.owner_ids = []; if (object.tournament_id !== undefined && object.tournament_id !== null) { message.tournament_id = object.tournament_id; } if (object.owner_ids !== undefined && object.owner_ids !== null) { for (const e of object.owner_ids) { message.owner_ids.push(e); } } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } if (object.expiry !== undefined && object.expiry !== null) { message.expiry = object.expiry; } return message; }, }; const baseListTournamentsRequest: object = { cursor: "" }; export const ListTournamentsRequest = { encode( message: ListTournamentsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.category_start !== undefined) { UInt32Value.encode( { value: message.category_start! }, writer.uint32(10).fork() ).ldelim(); } if (message.category_end !== undefined) { UInt32Value.encode( { value: message.category_end! }, writer.uint32(18).fork() ).ldelim(); } if (message.start_time !== undefined) { UInt32Value.encode( { value: message.start_time! }, writer.uint32(26).fork() ).ldelim(); } if (message.end_time !== undefined) { UInt32Value.encode( { value: message.end_time! }, writer.uint32(34).fork() ).ldelim(); } if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(50).fork() ).ldelim(); } if (message.cursor !== "") { writer.uint32(66).string(message.cursor); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListTournamentsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListTournamentsRequest } as ListTournamentsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.category_start = UInt32Value.decode( reader, reader.uint32() ).value; break; case 2: message.category_end = UInt32Value.decode( reader, reader.uint32() ).value; break; case 3: message.start_time = UInt32Value.decode( reader, reader.uint32() ).value; break; case 4: message.end_time = UInt32Value.decode(reader, reader.uint32()).value; break; case 6: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 8: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListTournamentsRequest { const message = { ...baseListTournamentsRequest } as ListTournamentsRequest; if (object.category_start !== undefined && object.category_start !== null) { message.category_start = Number(object.category_start); } if (object.category_end !== undefined && object.category_end !== null) { message.category_end = Number(object.category_end); } if (object.start_time !== undefined && object.start_time !== null) { message.start_time = Number(object.start_time); } if (object.end_time !== undefined && object.end_time !== null) { message.end_time = Number(object.end_time); } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: ListTournamentsRequest): unknown { const obj: any = {}; message.category_start !== undefined && (obj.category_start = message.category_start); message.category_end !== undefined && (obj.category_end = message.category_end); message.start_time !== undefined && (obj.start_time = message.start_time); message.end_time !== undefined && (obj.end_time = message.end_time); message.limit !== undefined && (obj.limit = message.limit); message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial( object: DeepPartial<ListTournamentsRequest> ): ListTournamentsRequest { const message = { ...baseListTournamentsRequest } as ListTournamentsRequest; if (object.category_start !== undefined && object.category_start !== null) { message.category_start = object.category_start; } if (object.category_end !== undefined && object.category_end !== null) { message.category_end = object.category_end; } if (object.start_time !== undefined && object.start_time !== null) { message.start_time = object.start_time; } if (object.end_time !== undefined && object.end_time !== null) { message.end_time = object.end_time; } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseListUserGroupsRequest: object = { user_id: "", cursor: "" }; export const ListUserGroupsRequest = { encode( message: ListUserGroupsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.user_id !== "") { writer.uint32(10).string(message.user_id); } if (message.limit !== undefined) { Int32Value.encode( { value: message.limit! }, writer.uint32(18).fork() ).ldelim(); } if (message.state !== undefined) { Int32Value.encode( { value: message.state! }, writer.uint32(26).fork() ).ldelim(); } if (message.cursor !== "") { writer.uint32(34).string(message.cursor); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ListUserGroupsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseListUserGroupsRequest } as ListUserGroupsRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.user_id = reader.string(); break; case 2: message.limit = Int32Value.decode(reader, reader.uint32()).value; break; case 3: message.state = Int32Value.decode(reader, reader.uint32()).value; break; case 4: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ListUserGroupsRequest { const message = { ...baseListUserGroupsRequest } as ListUserGroupsRequest; if (object.user_id !== undefined && object.user_id !== null) { message.user_id = String(object.user_id); } if (object.limit !== undefined && object.limit !== null) { message.limit = Number(object.limit); } if (object.state !== undefined && object.state !== null) { message.state = Number(object.state); } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: ListUserGroupsRequest): unknown { const obj: any = {}; message.user_id !== undefined && (obj.user_id = message.user_id); message.limit !== undefined && (obj.limit = message.limit); message.state !== undefined && (obj.state = message.state); message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial( object: DeepPartial<ListUserGroupsRequest> ): ListUserGroupsRequest { const message = { ...baseListUserGroupsRequest } as ListUserGroupsRequest; if (object.user_id !== undefined && object.user_id !== null) { message.user_id = object.user_id; } if (object.limit !== undefined && object.limit !== null) { message.limit = object.limit; } if (object.state !== undefined && object.state !== null) { message.state = object.state; } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseMatch: object = { match_id: "", authoritative: false, size: 0, tick_rate: 0, handler_name: "", }; export const Match = { encode(message: Match, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.match_id !== "") { writer.uint32(10).string(message.match_id); } if (message.authoritative === true) { writer.uint32(16).bool(message.authoritative); } if (message.label !== undefined) { StringValue.encode( { value: message.label! }, writer.uint32(26).fork() ).ldelim(); } if (message.size !== 0) { writer.uint32(32).int32(message.size); } if (message.tick_rate !== 0) { writer.uint32(40).int32(message.tick_rate); } if (message.handler_name !== "") { writer.uint32(50).string(message.handler_name); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Match { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatch } as Match; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.match_id = reader.string(); break; case 2: message.authoritative = reader.bool(); break; case 3: message.label = StringValue.decode(reader, reader.uint32()).value; break; case 4: message.size = reader.int32(); break; case 5: message.tick_rate = reader.int32(); break; case 6: message.handler_name = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Match { const message = { ...baseMatch } as Match; if (object.match_id !== undefined && object.match_id !== null) { message.match_id = String(object.match_id); } if (object.authoritative !== undefined && object.authoritative !== null) { message.authoritative = Boolean(object.authoritative); } if (object.label !== undefined && object.label !== null) { message.label = String(object.label); } if (object.size !== undefined && object.size !== null) { message.size = Number(object.size); } if (object.tick_rate !== undefined && object.tick_rate !== null) { message.tick_rate = Number(object.tick_rate); } if (object.handler_name !== undefined && object.handler_name !== null) { message.handler_name = String(object.handler_name); } return message; }, toJSON(message: Match): unknown { const obj: any = {}; message.match_id !== undefined && (obj.match_id = message.match_id); message.authoritative !== undefined && (obj.authoritative = message.authoritative); message.label !== undefined && (obj.label = message.label); message.size !== undefined && (obj.size = message.size); message.tick_rate !== undefined && (obj.tick_rate = message.tick_rate); message.handler_name !== undefined && (obj.handler_name = message.handler_name); return obj; }, fromPartial(object: DeepPartial<Match>): Match { const message = { ...baseMatch } as Match; if (object.match_id !== undefined && object.match_id !== null) { message.match_id = object.match_id; } if (object.authoritative !== undefined && object.authoritative !== null) { message.authoritative = object.authoritative; } if (object.label !== undefined && object.label !== null) { message.label = object.label; } if (object.size !== undefined && object.size !== null) { message.size = object.size; } if (object.tick_rate !== undefined && object.tick_rate !== null) { message.tick_rate = object.tick_rate; } if (object.handler_name !== undefined && object.handler_name !== null) { message.handler_name = object.handler_name; } return message; }, }; const baseMatchList: object = {}; export const MatchList = { encode( message: MatchList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.matches) { Match.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): MatchList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseMatchList } as MatchList; message.matches = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.matches.push(Match.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): MatchList { const message = { ...baseMatchList } as MatchList; message.matches = []; if (object.matches !== undefined && object.matches !== null) { for (const e of object.matches) { message.matches.push(Match.fromJSON(e)); } } return message; }, toJSON(message: MatchList): unknown { const obj: any = {}; if (message.matches) { obj.matches = message.matches.map((e) => e ? Match.toJSON(e) : undefined ); } else { obj.matches = []; } return obj; }, fromPartial(object: DeepPartial<MatchList>): MatchList { const message = { ...baseMatchList } as MatchList; message.matches = []; if (object.matches !== undefined && object.matches !== null) { for (const e of object.matches) { message.matches.push(Match.fromPartial(e)); } } return message; }, }; const baseNotification: object = { id: "", subject: "", content: "", code: 0, sender_id: "", persistent: false, }; export const Notification = { encode( message: Notification, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.id !== "") { writer.uint32(10).string(message.id); } if (message.subject !== "") { writer.uint32(18).string(message.subject); } if (message.content !== "") { writer.uint32(26).string(message.content); } if (message.code !== 0) { writer.uint32(32).int32(message.code); } if (message.sender_id !== "") { writer.uint32(42).string(message.sender_id); } if (message.create_time !== undefined) { Timestamp.encode( toTimestamp(message.create_time), writer.uint32(50).fork() ).ldelim(); } if (message.persistent === true) { writer.uint32(56).bool(message.persistent); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Notification { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseNotification } as Notification; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.subject = reader.string(); break; case 3: message.content = reader.string(); break; case 4: message.code = reader.int32(); break; case 5: message.sender_id = reader.string(); break; case 6: message.create_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 7: message.persistent = reader.bool(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Notification { const message = { ...baseNotification } as Notification; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } if (object.subject !== undefined && object.subject !== null) { message.subject = String(object.subject); } if (object.content !== undefined && object.content !== null) { message.content = String(object.content); } if (object.code !== undefined && object.code !== null) { message.code = Number(object.code); } if (object.sender_id !== undefined && object.sender_id !== null) { message.sender_id = String(object.sender_id); } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = fromJsonTimestamp(object.create_time); } if (object.persistent !== undefined && object.persistent !== null) { message.persistent = Boolean(object.persistent); } return message; }, toJSON(message: Notification): unknown { const obj: any = {}; message.id !== undefined && (obj.id = message.id); message.subject !== undefined && (obj.subject = message.subject); message.content !== undefined && (obj.content = message.content); message.code !== undefined && (obj.code = message.code); message.sender_id !== undefined && (obj.sender_id = message.sender_id); message.create_time !== undefined && (obj.create_time = message.create_time.toISOString()); message.persistent !== undefined && (obj.persistent = message.persistent); return obj; }, fromPartial(object: DeepPartial<Notification>): Notification { const message = { ...baseNotification } as Notification; if (object.id !== undefined && object.id !== null) { message.id = object.id; } if (object.subject !== undefined && object.subject !== null) { message.subject = object.subject; } if (object.content !== undefined && object.content !== null) { message.content = object.content; } if (object.code !== undefined && object.code !== null) { message.code = object.code; } if (object.sender_id !== undefined && object.sender_id !== null) { message.sender_id = object.sender_id; } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = object.create_time; } if (object.persistent !== undefined && object.persistent !== null) { message.persistent = object.persistent; } return message; }, }; const baseNotificationList: object = { cacheable_cursor: "" }; export const NotificationList = { encode( message: NotificationList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.notifications) { Notification.encode(v!, writer.uint32(10).fork()).ldelim(); } if (message.cacheable_cursor !== "") { writer.uint32(18).string(message.cacheable_cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): NotificationList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseNotificationList } as NotificationList; message.notifications = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.notifications.push( Notification.decode(reader, reader.uint32()) ); break; case 2: message.cacheable_cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): NotificationList { const message = { ...baseNotificationList } as NotificationList; message.notifications = []; if (object.notifications !== undefined && object.notifications !== null) { for (const e of object.notifications) { message.notifications.push(Notification.fromJSON(e)); } } if ( object.cacheable_cursor !== undefined && object.cacheable_cursor !== null ) { message.cacheable_cursor = String(object.cacheable_cursor); } return message; }, toJSON(message: NotificationList): unknown { const obj: any = {}; if (message.notifications) { obj.notifications = message.notifications.map((e) => e ? Notification.toJSON(e) : undefined ); } else { obj.notifications = []; } message.cacheable_cursor !== undefined && (obj.cacheable_cursor = message.cacheable_cursor); return obj; }, fromPartial(object: DeepPartial<NotificationList>): NotificationList { const message = { ...baseNotificationList } as NotificationList; message.notifications = []; if (object.notifications !== undefined && object.notifications !== null) { for (const e of object.notifications) { message.notifications.push(Notification.fromPartial(e)); } } if ( object.cacheable_cursor !== undefined && object.cacheable_cursor !== null ) { message.cacheable_cursor = object.cacheable_cursor; } return message; }, }; const basePromoteGroupUsersRequest: object = { group_id: "", user_ids: "" }; export const PromoteGroupUsersRequest = { encode( message: PromoteGroupUsersRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } for (const v of message.user_ids) { writer.uint32(18).string(v!); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): PromoteGroupUsersRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePromoteGroupUsersRequest, } as PromoteGroupUsersRequest; message.user_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; case 2: message.user_ids.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PromoteGroupUsersRequest { const message = { ...basePromoteGroupUsersRequest, } as PromoteGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(String(e)); } } return message; }, toJSON(message: PromoteGroupUsersRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); if (message.user_ids) { obj.user_ids = message.user_ids.map((e) => e); } else { obj.user_ids = []; } return obj; }, fromPartial( object: DeepPartial<PromoteGroupUsersRequest> ): PromoteGroupUsersRequest { const message = { ...basePromoteGroupUsersRequest, } as PromoteGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(e); } } return message; }, }; const baseDemoteGroupUsersRequest: object = { group_id: "", user_ids: "" }; export const DemoteGroupUsersRequest = { encode( message: DemoteGroupUsersRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } for (const v of message.user_ids) { writer.uint32(18).string(v!); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): DemoteGroupUsersRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseDemoteGroupUsersRequest, } as DemoteGroupUsersRequest; message.user_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; case 2: message.user_ids.push(reader.string()); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): DemoteGroupUsersRequest { const message = { ...baseDemoteGroupUsersRequest, } as DemoteGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(String(e)); } } return message; }, toJSON(message: DemoteGroupUsersRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); if (message.user_ids) { obj.user_ids = message.user_ids.map((e) => e); } else { obj.user_ids = []; } return obj; }, fromPartial( object: DeepPartial<DemoteGroupUsersRequest> ): DemoteGroupUsersRequest { const message = { ...baseDemoteGroupUsersRequest, } as DemoteGroupUsersRequest; message.user_ids = []; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } if (object.user_ids !== undefined && object.user_ids !== null) { for (const e of object.user_ids) { message.user_ids.push(e); } } return message; }, }; const baseReadStorageObjectId: object = { collection: "", key: "", user_id: "", }; export const ReadStorageObjectId = { encode( message: ReadStorageObjectId, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.collection !== "") { writer.uint32(10).string(message.collection); } if (message.key !== "") { writer.uint32(18).string(message.key); } if (message.user_id !== "") { writer.uint32(26).string(message.user_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ReadStorageObjectId { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseReadStorageObjectId } as ReadStorageObjectId; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.collection = reader.string(); break; case 2: message.key = reader.string(); break; case 3: message.user_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadStorageObjectId { const message = { ...baseReadStorageObjectId } as ReadStorageObjectId; if (object.collection !== undefined && object.collection !== null) { message.collection = String(object.collection); } if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.user_id !== undefined && object.user_id !== null) { message.user_id = String(object.user_id); } return message; }, toJSON(message: ReadStorageObjectId): unknown { const obj: any = {}; message.collection !== undefined && (obj.collection = message.collection); message.key !== undefined && (obj.key = message.key); message.user_id !== undefined && (obj.user_id = message.user_id); return obj; }, fromPartial(object: DeepPartial<ReadStorageObjectId>): ReadStorageObjectId { const message = { ...baseReadStorageObjectId } as ReadStorageObjectId; if (object.collection !== undefined && object.collection !== null) { message.collection = object.collection; } if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.user_id !== undefined && object.user_id !== null) { message.user_id = object.user_id; } return message; }, }; const baseReadStorageObjectsRequest: object = {}; export const ReadStorageObjectsRequest = { encode( message: ReadStorageObjectsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.object_ids) { ReadStorageObjectId.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ReadStorageObjectsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseReadStorageObjectsRequest, } as ReadStorageObjectsRequest; message.object_ids = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.object_ids.push( ReadStorageObjectId.decode(reader, reader.uint32()) ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ReadStorageObjectsRequest { const message = { ...baseReadStorageObjectsRequest, } as ReadStorageObjectsRequest; message.object_ids = []; if (object.object_ids !== undefined && object.object_ids !== null) { for (const e of object.object_ids) { message.object_ids.push(ReadStorageObjectId.fromJSON(e)); } } return message; }, toJSON(message: ReadStorageObjectsRequest): unknown { const obj: any = {}; if (message.object_ids) { obj.object_ids = message.object_ids.map((e) => e ? ReadStorageObjectId.toJSON(e) : undefined ); } else { obj.object_ids = []; } return obj; }, fromPartial( object: DeepPartial<ReadStorageObjectsRequest> ): ReadStorageObjectsRequest { const message = { ...baseReadStorageObjectsRequest, } as ReadStorageObjectsRequest; message.object_ids = []; if (object.object_ids !== undefined && object.object_ids !== null) { for (const e of object.object_ids) { message.object_ids.push(ReadStorageObjectId.fromPartial(e)); } } return message; }, }; const baseRpc: object = { id: "", payload: "", http_key: "" }; export const Rpc = { encode(message: Rpc, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.id !== "") { writer.uint32(10).string(message.id); } if (message.payload !== "") { writer.uint32(18).string(message.payload); } if (message.http_key !== "") { writer.uint32(26).string(message.http_key); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Rpc { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseRpc } as Rpc; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.payload = reader.string(); break; case 3: message.http_key = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Rpc { const message = { ...baseRpc } as Rpc; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } if (object.payload !== undefined && object.payload !== null) { message.payload = String(object.payload); } if (object.http_key !== undefined && object.http_key !== null) { message.http_key = String(object.http_key); } return message; }, toJSON(message: Rpc): unknown { const obj: any = {}; message.id !== undefined && (obj.id = message.id); message.payload !== undefined && (obj.payload = message.payload); message.http_key !== undefined && (obj.http_key = message.http_key); return obj; }, fromPartial(object: DeepPartial<Rpc>): Rpc { const message = { ...baseRpc } as Rpc; if (object.id !== undefined && object.id !== null) { message.id = object.id; } if (object.payload !== undefined && object.payload !== null) { message.payload = object.payload; } if (object.http_key !== undefined && object.http_key !== null) { message.http_key = object.http_key; } return message; }, }; const baseSession: object = { created: false, token: "", refresh_token: "" }; export const Session = { encode( message: Session, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.created === true) { writer.uint32(8).bool(message.created); } if (message.token !== "") { writer.uint32(18).string(message.token); } if (message.refresh_token !== "") { writer.uint32(26).string(message.refresh_token); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Session { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseSession } as Session; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.created = reader.bool(); break; case 2: message.token = reader.string(); break; case 3: message.refresh_token = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Session { const message = { ...baseSession } as Session; if (object.created !== undefined && object.created !== null) { message.created = Boolean(object.created); } if (object.token !== undefined && object.token !== null) { message.token = String(object.token); } if (object.refresh_token !== undefined && object.refresh_token !== null) { message.refresh_token = String(object.refresh_token); } return message; }, toJSON(message: Session): unknown { const obj: any = {}; message.created !== undefined && (obj.created = message.created); message.token !== undefined && (obj.token = message.token); message.refresh_token !== undefined && (obj.refresh_token = message.refresh_token); return obj; }, fromPartial(object: DeepPartial<Session>): Session { const message = { ...baseSession } as Session; if (object.created !== undefined && object.created !== null) { message.created = object.created; } if (object.token !== undefined && object.token !== null) { message.token = object.token; } if (object.refresh_token !== undefined && object.refresh_token !== null) { message.refresh_token = object.refresh_token; } return message; }, }; const baseStorageObject: object = { collection: "", key: "", user_id: "", value: "", version: "", permission_read: 0, permission_write: 0, }; export const StorageObject = { encode( message: StorageObject, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.collection !== "") { writer.uint32(10).string(message.collection); } if (message.key !== "") { writer.uint32(18).string(message.key); } if (message.user_id !== "") { writer.uint32(26).string(message.user_id); } if (message.value !== "") { writer.uint32(34).string(message.value); } if (message.version !== "") { writer.uint32(42).string(message.version); } if (message.permission_read !== 0) { writer.uint32(48).int32(message.permission_read); } if (message.permission_write !== 0) { writer.uint32(56).int32(message.permission_write); } if (message.create_time !== undefined) { Timestamp.encode( toTimestamp(message.create_time), writer.uint32(66).fork() ).ldelim(); } if (message.update_time !== undefined) { Timestamp.encode( toTimestamp(message.update_time), writer.uint32(74).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StorageObject { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStorageObject } as StorageObject; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.collection = reader.string(); break; case 2: message.key = reader.string(); break; case 3: message.user_id = reader.string(); break; case 4: message.value = reader.string(); break; case 5: message.version = reader.string(); break; case 6: message.permission_read = reader.int32(); break; case 7: message.permission_write = reader.int32(); break; case 8: message.create_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 9: message.update_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StorageObject { const message = { ...baseStorageObject } as StorageObject; if (object.collection !== undefined && object.collection !== null) { message.collection = String(object.collection); } if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.user_id !== undefined && object.user_id !== null) { message.user_id = String(object.user_id); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } if (object.version !== undefined && object.version !== null) { message.version = String(object.version); } if ( object.permission_read !== undefined && object.permission_read !== null ) { message.permission_read = Number(object.permission_read); } if ( object.permission_write !== undefined && object.permission_write !== null ) { message.permission_write = Number(object.permission_write); } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = fromJsonTimestamp(object.create_time); } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = fromJsonTimestamp(object.update_time); } return message; }, toJSON(message: StorageObject): unknown { const obj: any = {}; message.collection !== undefined && (obj.collection = message.collection); message.key !== undefined && (obj.key = message.key); message.user_id !== undefined && (obj.user_id = message.user_id); message.value !== undefined && (obj.value = message.value); message.version !== undefined && (obj.version = message.version); message.permission_read !== undefined && (obj.permission_read = message.permission_read); message.permission_write !== undefined && (obj.permission_write = message.permission_write); message.create_time !== undefined && (obj.create_time = message.create_time.toISOString()); message.update_time !== undefined && (obj.update_time = message.update_time.toISOString()); return obj; }, fromPartial(object: DeepPartial<StorageObject>): StorageObject { const message = { ...baseStorageObject } as StorageObject; if (object.collection !== undefined && object.collection !== null) { message.collection = object.collection; } if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.user_id !== undefined && object.user_id !== null) { message.user_id = object.user_id; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } if (object.version !== undefined && object.version !== null) { message.version = object.version; } if ( object.permission_read !== undefined && object.permission_read !== null ) { message.permission_read = object.permission_read; } if ( object.permission_write !== undefined && object.permission_write !== null ) { message.permission_write = object.permission_write; } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = object.create_time; } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = object.update_time; } return message; }, }; const baseStorageObjectAck: object = { collection: "", key: "", version: "", user_id: "", }; export const StorageObjectAck = { encode( message: StorageObjectAck, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.collection !== "") { writer.uint32(10).string(message.collection); } if (message.key !== "") { writer.uint32(18).string(message.key); } if (message.version !== "") { writer.uint32(26).string(message.version); } if (message.user_id !== "") { writer.uint32(34).string(message.user_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StorageObjectAck { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStorageObjectAck } as StorageObjectAck; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.collection = reader.string(); break; case 2: message.key = reader.string(); break; case 3: message.version = reader.string(); break; case 4: message.user_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StorageObjectAck { const message = { ...baseStorageObjectAck } as StorageObjectAck; if (object.collection !== undefined && object.collection !== null) { message.collection = String(object.collection); } if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.version !== undefined && object.version !== null) { message.version = String(object.version); } if (object.user_id !== undefined && object.user_id !== null) { message.user_id = String(object.user_id); } return message; }, toJSON(message: StorageObjectAck): unknown { const obj: any = {}; message.collection !== undefined && (obj.collection = message.collection); message.key !== undefined && (obj.key = message.key); message.version !== undefined && (obj.version = message.version); message.user_id !== undefined && (obj.user_id = message.user_id); return obj; }, fromPartial(object: DeepPartial<StorageObjectAck>): StorageObjectAck { const message = { ...baseStorageObjectAck } as StorageObjectAck; if (object.collection !== undefined && object.collection !== null) { message.collection = object.collection; } if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.version !== undefined && object.version !== null) { message.version = object.version; } if (object.user_id !== undefined && object.user_id !== null) { message.user_id = object.user_id; } return message; }, }; const baseStorageObjectAcks: object = {}; export const StorageObjectAcks = { encode( message: StorageObjectAcks, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.acks) { StorageObjectAck.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StorageObjectAcks { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStorageObjectAcks } as StorageObjectAcks; message.acks = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.acks.push(StorageObjectAck.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StorageObjectAcks { const message = { ...baseStorageObjectAcks } as StorageObjectAcks; message.acks = []; if (object.acks !== undefined && object.acks !== null) { for (const e of object.acks) { message.acks.push(StorageObjectAck.fromJSON(e)); } } return message; }, toJSON(message: StorageObjectAcks): unknown { const obj: any = {}; if (message.acks) { obj.acks = message.acks.map((e) => e ? StorageObjectAck.toJSON(e) : undefined ); } else { obj.acks = []; } return obj; }, fromPartial(object: DeepPartial<StorageObjectAcks>): StorageObjectAcks { const message = { ...baseStorageObjectAcks } as StorageObjectAcks; message.acks = []; if (object.acks !== undefined && object.acks !== null) { for (const e of object.acks) { message.acks.push(StorageObjectAck.fromPartial(e)); } } return message; }, }; const baseStorageObjects: object = {}; export const StorageObjects = { encode( message: StorageObjects, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.objects) { StorageObject.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StorageObjects { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStorageObjects } as StorageObjects; message.objects = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.objects.push(StorageObject.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StorageObjects { const message = { ...baseStorageObjects } as StorageObjects; message.objects = []; if (object.objects !== undefined && object.objects !== null) { for (const e of object.objects) { message.objects.push(StorageObject.fromJSON(e)); } } return message; }, toJSON(message: StorageObjects): unknown { const obj: any = {}; if (message.objects) { obj.objects = message.objects.map((e) => e ? StorageObject.toJSON(e) : undefined ); } else { obj.objects = []; } return obj; }, fromPartial(object: DeepPartial<StorageObjects>): StorageObjects { const message = { ...baseStorageObjects } as StorageObjects; message.objects = []; if (object.objects !== undefined && object.objects !== null) { for (const e of object.objects) { message.objects.push(StorageObject.fromPartial(e)); } } return message; }, }; const baseStorageObjectList: object = { cursor: "" }; export const StorageObjectList = { encode( message: StorageObjectList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.objects) { StorageObject.encode(v!, writer.uint32(10).fork()).ldelim(); } if (message.cursor !== "") { writer.uint32(18).string(message.cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): StorageObjectList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseStorageObjectList } as StorageObjectList; message.objects = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.objects.push(StorageObject.decode(reader, reader.uint32())); break; case 2: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): StorageObjectList { const message = { ...baseStorageObjectList } as StorageObjectList; message.objects = []; if (object.objects !== undefined && object.objects !== null) { for (const e of object.objects) { message.objects.push(StorageObject.fromJSON(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: StorageObjectList): unknown { const obj: any = {}; if (message.objects) { obj.objects = message.objects.map((e) => e ? StorageObject.toJSON(e) : undefined ); } else { obj.objects = []; } message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial(object: DeepPartial<StorageObjectList>): StorageObjectList { const message = { ...baseStorageObjectList } as StorageObjectList; message.objects = []; if (object.objects !== undefined && object.objects !== null) { for (const e of object.objects) { message.objects.push(StorageObject.fromPartial(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseTournament: object = { id: "", title: "", description: "", category: 0, sort_order: 0, size: 0, max_size: 0, max_num_score: 0, can_enter: false, end_active: 0, next_reset: 0, metadata: "", duration: 0, start_active: 0, }; export const Tournament = { encode( message: Tournament, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.id !== "") { writer.uint32(10).string(message.id); } if (message.title !== "") { writer.uint32(18).string(message.title); } if (message.description !== "") { writer.uint32(26).string(message.description); } if (message.category !== 0) { writer.uint32(32).uint32(message.category); } if (message.sort_order !== 0) { writer.uint32(40).uint32(message.sort_order); } if (message.size !== 0) { writer.uint32(48).uint32(message.size); } if (message.max_size !== 0) { writer.uint32(56).uint32(message.max_size); } if (message.max_num_score !== 0) { writer.uint32(64).uint32(message.max_num_score); } if (message.can_enter === true) { writer.uint32(72).bool(message.can_enter); } if (message.end_active !== 0) { writer.uint32(80).uint32(message.end_active); } if (message.next_reset !== 0) { writer.uint32(88).uint32(message.next_reset); } if (message.metadata !== "") { writer.uint32(98).string(message.metadata); } if (message.create_time !== undefined) { Timestamp.encode( toTimestamp(message.create_time), writer.uint32(106).fork() ).ldelim(); } if (message.start_time !== undefined) { Timestamp.encode( toTimestamp(message.start_time), writer.uint32(114).fork() ).ldelim(); } if (message.end_time !== undefined) { Timestamp.encode( toTimestamp(message.end_time), writer.uint32(122).fork() ).ldelim(); } if (message.duration !== 0) { writer.uint32(128).uint32(message.duration); } if (message.start_active !== 0) { writer.uint32(136).uint32(message.start_active); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Tournament { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseTournament } as Tournament; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.title = reader.string(); break; case 3: message.description = reader.string(); break; case 4: message.category = reader.uint32(); break; case 5: message.sort_order = reader.uint32(); break; case 6: message.size = reader.uint32(); break; case 7: message.max_size = reader.uint32(); break; case 8: message.max_num_score = reader.uint32(); break; case 9: message.can_enter = reader.bool(); break; case 10: message.end_active = reader.uint32(); break; case 11: message.next_reset = reader.uint32(); break; case 12: message.metadata = reader.string(); break; case 13: message.create_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 14: message.start_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 15: message.end_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 16: message.duration = reader.uint32(); break; case 17: message.start_active = reader.uint32(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Tournament { const message = { ...baseTournament } as Tournament; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } if (object.title !== undefined && object.title !== null) { message.title = String(object.title); } if (object.description !== undefined && object.description !== null) { message.description = String(object.description); } if (object.category !== undefined && object.category !== null) { message.category = Number(object.category); } if (object.sort_order !== undefined && object.sort_order !== null) { message.sort_order = Number(object.sort_order); } if (object.size !== undefined && object.size !== null) { message.size = Number(object.size); } if (object.max_size !== undefined && object.max_size !== null) { message.max_size = Number(object.max_size); } if (object.max_num_score !== undefined && object.max_num_score !== null) { message.max_num_score = Number(object.max_num_score); } if (object.can_enter !== undefined && object.can_enter !== null) { message.can_enter = Boolean(object.can_enter); } if (object.end_active !== undefined && object.end_active !== null) { message.end_active = Number(object.end_active); } if (object.next_reset !== undefined && object.next_reset !== null) { message.next_reset = Number(object.next_reset); } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = String(object.metadata); } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = fromJsonTimestamp(object.create_time); } if (object.start_time !== undefined && object.start_time !== null) { message.start_time = fromJsonTimestamp(object.start_time); } if (object.end_time !== undefined && object.end_time !== null) { message.end_time = fromJsonTimestamp(object.end_time); } if (object.duration !== undefined && object.duration !== null) { message.duration = Number(object.duration); } if (object.start_active !== undefined && object.start_active !== null) { message.start_active = Number(object.start_active); } return message; }, toJSON(message: Tournament): unknown { const obj: any = {}; message.id !== undefined && (obj.id = message.id); message.title !== undefined && (obj.title = message.title); message.description !== undefined && (obj.description = message.description); message.category !== undefined && (obj.category = message.category); message.sort_order !== undefined && (obj.sort_order = message.sort_order); message.size !== undefined && (obj.size = message.size); message.max_size !== undefined && (obj.max_size = message.max_size); message.max_num_score !== undefined && (obj.max_num_score = message.max_num_score); message.can_enter !== undefined && (obj.can_enter = message.can_enter); message.end_active !== undefined && (obj.end_active = message.end_active); message.next_reset !== undefined && (obj.next_reset = message.next_reset); message.metadata !== undefined && (obj.metadata = message.metadata); message.create_time !== undefined && (obj.create_time = message.create_time.toISOString()); message.start_time !== undefined && (obj.start_time = message.start_time.toISOString()); message.end_time !== undefined && (obj.end_time = message.end_time.toISOString()); message.duration !== undefined && (obj.duration = message.duration); message.start_active !== undefined && (obj.start_active = message.start_active); return obj; }, fromPartial(object: DeepPartial<Tournament>): Tournament { const message = { ...baseTournament } as Tournament; if (object.id !== undefined && object.id !== null) { message.id = object.id; } if (object.title !== undefined && object.title !== null) { message.title = object.title; } if (object.description !== undefined && object.description !== null) { message.description = object.description; } if (object.category !== undefined && object.category !== null) { message.category = object.category; } if (object.sort_order !== undefined && object.sort_order !== null) { message.sort_order = object.sort_order; } if (object.size !== undefined && object.size !== null) { message.size = object.size; } if (object.max_size !== undefined && object.max_size !== null) { message.max_size = object.max_size; } if (object.max_num_score !== undefined && object.max_num_score !== null) { message.max_num_score = object.max_num_score; } if (object.can_enter !== undefined && object.can_enter !== null) { message.can_enter = object.can_enter; } if (object.end_active !== undefined && object.end_active !== null) { message.end_active = object.end_active; } if (object.next_reset !== undefined && object.next_reset !== null) { message.next_reset = object.next_reset; } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = object.metadata; } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = object.create_time; } if (object.start_time !== undefined && object.start_time !== null) { message.start_time = object.start_time; } if (object.end_time !== undefined && object.end_time !== null) { message.end_time = object.end_time; } if (object.duration !== undefined && object.duration !== null) { message.duration = object.duration; } if (object.start_active !== undefined && object.start_active !== null) { message.start_active = object.start_active; } return message; }, }; const baseTournamentList: object = { cursor: "" }; export const TournamentList = { encode( message: TournamentList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.tournaments) { Tournament.encode(v!, writer.uint32(10).fork()).ldelim(); } if (message.cursor !== "") { writer.uint32(18).string(message.cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): TournamentList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseTournamentList } as TournamentList; message.tournaments = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.tournaments.push(Tournament.decode(reader, reader.uint32())); break; case 2: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): TournamentList { const message = { ...baseTournamentList } as TournamentList; message.tournaments = []; if (object.tournaments !== undefined && object.tournaments !== null) { for (const e of object.tournaments) { message.tournaments.push(Tournament.fromJSON(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: TournamentList): unknown { const obj: any = {}; if (message.tournaments) { obj.tournaments = message.tournaments.map((e) => e ? Tournament.toJSON(e) : undefined ); } else { obj.tournaments = []; } message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial(object: DeepPartial<TournamentList>): TournamentList { const message = { ...baseTournamentList } as TournamentList; message.tournaments = []; if (object.tournaments !== undefined && object.tournaments !== null) { for (const e of object.tournaments) { message.tournaments.push(Tournament.fromPartial(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseTournamentRecordList: object = { next_cursor: "", prev_cursor: "" }; export const TournamentRecordList = { encode( message: TournamentRecordList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.records) { LeaderboardRecord.encode(v!, writer.uint32(10).fork()).ldelim(); } for (const v of message.owner_records) { LeaderboardRecord.encode(v!, writer.uint32(18).fork()).ldelim(); } if (message.next_cursor !== "") { writer.uint32(26).string(message.next_cursor); } if (message.prev_cursor !== "") { writer.uint32(34).string(message.prev_cursor); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): TournamentRecordList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseTournamentRecordList } as TournamentRecordList; message.records = []; message.owner_records = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.records.push( LeaderboardRecord.decode(reader, reader.uint32()) ); break; case 2: message.owner_records.push( LeaderboardRecord.decode(reader, reader.uint32()) ); break; case 3: message.next_cursor = reader.string(); break; case 4: message.prev_cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): TournamentRecordList { const message = { ...baseTournamentRecordList } as TournamentRecordList; message.records = []; message.owner_records = []; if (object.records !== undefined && object.records !== null) { for (const e of object.records) { message.records.push(LeaderboardRecord.fromJSON(e)); } } if (object.owner_records !== undefined && object.owner_records !== null) { for (const e of object.owner_records) { message.owner_records.push(LeaderboardRecord.fromJSON(e)); } } if (object.next_cursor !== undefined && object.next_cursor !== null) { message.next_cursor = String(object.next_cursor); } if (object.prev_cursor !== undefined && object.prev_cursor !== null) { message.prev_cursor = String(object.prev_cursor); } return message; }, toJSON(message: TournamentRecordList): unknown { const obj: any = {}; if (message.records) { obj.records = message.records.map((e) => e ? LeaderboardRecord.toJSON(e) : undefined ); } else { obj.records = []; } if (message.owner_records) { obj.owner_records = message.owner_records.map((e) => e ? LeaderboardRecord.toJSON(e) : undefined ); } else { obj.owner_records = []; } message.next_cursor !== undefined && (obj.next_cursor = message.next_cursor); message.prev_cursor !== undefined && (obj.prev_cursor = message.prev_cursor); return obj; }, fromPartial(object: DeepPartial<TournamentRecordList>): TournamentRecordList { const message = { ...baseTournamentRecordList } as TournamentRecordList; message.records = []; message.owner_records = []; if (object.records !== undefined && object.records !== null) { for (const e of object.records) { message.records.push(LeaderboardRecord.fromPartial(e)); } } if (object.owner_records !== undefined && object.owner_records !== null) { for (const e of object.owner_records) { message.owner_records.push(LeaderboardRecord.fromPartial(e)); } } if (object.next_cursor !== undefined && object.next_cursor !== null) { message.next_cursor = object.next_cursor; } if (object.prev_cursor !== undefined && object.prev_cursor !== null) { message.prev_cursor = object.prev_cursor; } return message; }, }; const baseUpdateAccountRequest: object = {}; export const UpdateAccountRequest = { encode( message: UpdateAccountRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.username !== undefined) { StringValue.encode( { value: message.username! }, writer.uint32(10).fork() ).ldelim(); } if (message.display_name !== undefined) { StringValue.encode( { value: message.display_name! }, writer.uint32(18).fork() ).ldelim(); } if (message.avatar_url !== undefined) { StringValue.encode( { value: message.avatar_url! }, writer.uint32(26).fork() ).ldelim(); } if (message.lang_tag !== undefined) { StringValue.encode( { value: message.lang_tag! }, writer.uint32(34).fork() ).ldelim(); } if (message.location !== undefined) { StringValue.encode( { value: message.location! }, writer.uint32(42).fork() ).ldelim(); } if (message.timezone !== undefined) { StringValue.encode( { value: message.timezone! }, writer.uint32(50).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): UpdateAccountRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseUpdateAccountRequest } as UpdateAccountRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.username = StringValue.decode(reader, reader.uint32()).value; break; case 2: message.display_name = StringValue.decode( reader, reader.uint32() ).value; break; case 3: message.avatar_url = StringValue.decode( reader, reader.uint32() ).value; break; case 4: message.lang_tag = StringValue.decode(reader, reader.uint32()).value; break; case 5: message.location = StringValue.decode(reader, reader.uint32()).value; break; case 6: message.timezone = StringValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): UpdateAccountRequest { const message = { ...baseUpdateAccountRequest } as UpdateAccountRequest; if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } if (object.display_name !== undefined && object.display_name !== null) { message.display_name = String(object.display_name); } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = String(object.avatar_url); } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = String(object.lang_tag); } if (object.location !== undefined && object.location !== null) { message.location = String(object.location); } if (object.timezone !== undefined && object.timezone !== null) { message.timezone = String(object.timezone); } return message; }, toJSON(message: UpdateAccountRequest): unknown { const obj: any = {}; message.username !== undefined && (obj.username = message.username); message.display_name !== undefined && (obj.display_name = message.display_name); message.avatar_url !== undefined && (obj.avatar_url = message.avatar_url); message.lang_tag !== undefined && (obj.lang_tag = message.lang_tag); message.location !== undefined && (obj.location = message.location); message.timezone !== undefined && (obj.timezone = message.timezone); return obj; }, fromPartial(object: DeepPartial<UpdateAccountRequest>): UpdateAccountRequest { const message = { ...baseUpdateAccountRequest } as UpdateAccountRequest; if (object.username !== undefined && object.username !== null) { message.username = object.username; } if (object.display_name !== undefined && object.display_name !== null) { message.display_name = object.display_name; } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = object.avatar_url; } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = object.lang_tag; } if (object.location !== undefined && object.location !== null) { message.location = object.location; } if (object.timezone !== undefined && object.timezone !== null) { message.timezone = object.timezone; } return message; }, }; const baseUpdateGroupRequest: object = { group_id: "" }; export const UpdateGroupRequest = { encode( message: UpdateGroupRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group_id !== "") { writer.uint32(10).string(message.group_id); } if (message.name !== undefined) { StringValue.encode( { value: message.name! }, writer.uint32(18).fork() ).ldelim(); } if (message.description !== undefined) { StringValue.encode( { value: message.description! }, writer.uint32(26).fork() ).ldelim(); } if (message.lang_tag !== undefined) { StringValue.encode( { value: message.lang_tag! }, writer.uint32(34).fork() ).ldelim(); } if (message.avatar_url !== undefined) { StringValue.encode( { value: message.avatar_url! }, writer.uint32(42).fork() ).ldelim(); } if (message.open !== undefined) { BoolValue.encode( { value: message.open! }, writer.uint32(50).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): UpdateGroupRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseUpdateGroupRequest } as UpdateGroupRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group_id = reader.string(); break; case 2: message.name = StringValue.decode(reader, reader.uint32()).value; break; case 3: message.description = StringValue.decode( reader, reader.uint32() ).value; break; case 4: message.lang_tag = StringValue.decode(reader, reader.uint32()).value; break; case 5: message.avatar_url = StringValue.decode( reader, reader.uint32() ).value; break; case 6: message.open = BoolValue.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): UpdateGroupRequest { const message = { ...baseUpdateGroupRequest } as UpdateGroupRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = String(object.group_id); } if (object.name !== undefined && object.name !== null) { message.name = String(object.name); } if (object.description !== undefined && object.description !== null) { message.description = String(object.description); } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = String(object.lang_tag); } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = String(object.avatar_url); } if (object.open !== undefined && object.open !== null) { message.open = Boolean(object.open); } return message; }, toJSON(message: UpdateGroupRequest): unknown { const obj: any = {}; message.group_id !== undefined && (obj.group_id = message.group_id); message.name !== undefined && (obj.name = message.name); message.description !== undefined && (obj.description = message.description); message.lang_tag !== undefined && (obj.lang_tag = message.lang_tag); message.avatar_url !== undefined && (obj.avatar_url = message.avatar_url); message.open !== undefined && (obj.open = message.open); return obj; }, fromPartial(object: DeepPartial<UpdateGroupRequest>): UpdateGroupRequest { const message = { ...baseUpdateGroupRequest } as UpdateGroupRequest; if (object.group_id !== undefined && object.group_id !== null) { message.group_id = object.group_id; } if (object.name !== undefined && object.name !== null) { message.name = object.name; } if (object.description !== undefined && object.description !== null) { message.description = object.description; } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = object.lang_tag; } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = object.avatar_url; } if (object.open !== undefined && object.open !== null) { message.open = object.open; } return message; }, }; const baseUser: object = { id: "", username: "", display_name: "", avatar_url: "", lang_tag: "", location: "", timezone: "", metadata: "", facebook_id: "", google_id: "", gamecenter_id: "", steam_id: "", online: false, edge_count: 0, facebook_instant_game_id: "", apple_id: "", }; export const User = { encode(message: User, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.id !== "") { writer.uint32(10).string(message.id); } if (message.username !== "") { writer.uint32(18).string(message.username); } if (message.display_name !== "") { writer.uint32(26).string(message.display_name); } if (message.avatar_url !== "") { writer.uint32(34).string(message.avatar_url); } if (message.lang_tag !== "") { writer.uint32(42).string(message.lang_tag); } if (message.location !== "") { writer.uint32(50).string(message.location); } if (message.timezone !== "") { writer.uint32(58).string(message.timezone); } if (message.metadata !== "") { writer.uint32(66).string(message.metadata); } if (message.facebook_id !== "") { writer.uint32(74).string(message.facebook_id); } if (message.google_id !== "") { writer.uint32(82).string(message.google_id); } if (message.gamecenter_id !== "") { writer.uint32(90).string(message.gamecenter_id); } if (message.steam_id !== "") { writer.uint32(98).string(message.steam_id); } if (message.online === true) { writer.uint32(104).bool(message.online); } if (message.edge_count !== 0) { writer.uint32(112).int32(message.edge_count); } if (message.create_time !== undefined) { Timestamp.encode( toTimestamp(message.create_time), writer.uint32(122).fork() ).ldelim(); } if (message.update_time !== undefined) { Timestamp.encode( toTimestamp(message.update_time), writer.uint32(130).fork() ).ldelim(); } if (message.facebook_instant_game_id !== "") { writer.uint32(138).string(message.facebook_instant_game_id); } if (message.apple_id !== "") { writer.uint32(146).string(message.apple_id); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): User { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseUser } as User; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = reader.string(); break; case 2: message.username = reader.string(); break; case 3: message.display_name = reader.string(); break; case 4: message.avatar_url = reader.string(); break; case 5: message.lang_tag = reader.string(); break; case 6: message.location = reader.string(); break; case 7: message.timezone = reader.string(); break; case 8: message.metadata = reader.string(); break; case 9: message.facebook_id = reader.string(); break; case 10: message.google_id = reader.string(); break; case 11: message.gamecenter_id = reader.string(); break; case 12: message.steam_id = reader.string(); break; case 13: message.online = reader.bool(); break; case 14: message.edge_count = reader.int32(); break; case 15: message.create_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 16: message.update_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 17: message.facebook_instant_game_id = reader.string(); break; case 18: message.apple_id = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): User { const message = { ...baseUser } as User; if (object.id !== undefined && object.id !== null) { message.id = String(object.id); } if (object.username !== undefined && object.username !== null) { message.username = String(object.username); } if (object.display_name !== undefined && object.display_name !== null) { message.display_name = String(object.display_name); } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = String(object.avatar_url); } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = String(object.lang_tag); } if (object.location !== undefined && object.location !== null) { message.location = String(object.location); } if (object.timezone !== undefined && object.timezone !== null) { message.timezone = String(object.timezone); } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = String(object.metadata); } if (object.facebook_id !== undefined && object.facebook_id !== null) { message.facebook_id = String(object.facebook_id); } if (object.google_id !== undefined && object.google_id !== null) { message.google_id = String(object.google_id); } if (object.gamecenter_id !== undefined && object.gamecenter_id !== null) { message.gamecenter_id = String(object.gamecenter_id); } if (object.steam_id !== undefined && object.steam_id !== null) { message.steam_id = String(object.steam_id); } if (object.online !== undefined && object.online !== null) { message.online = Boolean(object.online); } if (object.edge_count !== undefined && object.edge_count !== null) { message.edge_count = Number(object.edge_count); } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = fromJsonTimestamp(object.create_time); } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = fromJsonTimestamp(object.update_time); } if ( object.facebook_instant_game_id !== undefined && object.facebook_instant_game_id !== null ) { message.facebook_instant_game_id = String( object.facebook_instant_game_id ); } if (object.apple_id !== undefined && object.apple_id !== null) { message.apple_id = String(object.apple_id); } return message; }, toJSON(message: User): unknown { const obj: any = {}; message.id !== undefined && (obj.id = message.id); message.username !== undefined && (obj.username = message.username); message.display_name !== undefined && (obj.display_name = message.display_name); message.avatar_url !== undefined && (obj.avatar_url = message.avatar_url); message.lang_tag !== undefined && (obj.lang_tag = message.lang_tag); message.location !== undefined && (obj.location = message.location); message.timezone !== undefined && (obj.timezone = message.timezone); message.metadata !== undefined && (obj.metadata = message.metadata); message.facebook_id !== undefined && (obj.facebook_id = message.facebook_id); message.google_id !== undefined && (obj.google_id = message.google_id); message.gamecenter_id !== undefined && (obj.gamecenter_id = message.gamecenter_id); message.steam_id !== undefined && (obj.steam_id = message.steam_id); message.online !== undefined && (obj.online = message.online); message.edge_count !== undefined && (obj.edge_count = message.edge_count); message.create_time !== undefined && (obj.create_time = message.create_time.toISOString()); message.update_time !== undefined && (obj.update_time = message.update_time.toISOString()); message.facebook_instant_game_id !== undefined && (obj.facebook_instant_game_id = message.facebook_instant_game_id); message.apple_id !== undefined && (obj.apple_id = message.apple_id); return obj; }, fromPartial(object: DeepPartial<User>): User { const message = { ...baseUser } as User; if (object.id !== undefined && object.id !== null) { message.id = object.id; } if (object.username !== undefined && object.username !== null) { message.username = object.username; } if (object.display_name !== undefined && object.display_name !== null) { message.display_name = object.display_name; } if (object.avatar_url !== undefined && object.avatar_url !== null) { message.avatar_url = object.avatar_url; } if (object.lang_tag !== undefined && object.lang_tag !== null) { message.lang_tag = object.lang_tag; } if (object.location !== undefined && object.location !== null) { message.location = object.location; } if (object.timezone !== undefined && object.timezone !== null) { message.timezone = object.timezone; } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = object.metadata; } if (object.facebook_id !== undefined && object.facebook_id !== null) { message.facebook_id = object.facebook_id; } if (object.google_id !== undefined && object.google_id !== null) { message.google_id = object.google_id; } if (object.gamecenter_id !== undefined && object.gamecenter_id !== null) { message.gamecenter_id = object.gamecenter_id; } if (object.steam_id !== undefined && object.steam_id !== null) { message.steam_id = object.steam_id; } if (object.online !== undefined && object.online !== null) { message.online = object.online; } if (object.edge_count !== undefined && object.edge_count !== null) { message.edge_count = object.edge_count; } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = object.create_time; } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = object.update_time; } if ( object.facebook_instant_game_id !== undefined && object.facebook_instant_game_id !== null ) { message.facebook_instant_game_id = object.facebook_instant_game_id; } if (object.apple_id !== undefined && object.apple_id !== null) { message.apple_id = object.apple_id; } return message; }, }; const baseUserGroupList: object = { cursor: "" }; export const UserGroupList = { encode( message: UserGroupList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.user_groups) { UserGroupList_UserGroup.encode(v!, writer.uint32(10).fork()).ldelim(); } if (message.cursor !== "") { writer.uint32(18).string(message.cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): UserGroupList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseUserGroupList } as UserGroupList; message.user_groups = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.user_groups.push( UserGroupList_UserGroup.decode(reader, reader.uint32()) ); break; case 2: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): UserGroupList { const message = { ...baseUserGroupList } as UserGroupList; message.user_groups = []; if (object.user_groups !== undefined && object.user_groups !== null) { for (const e of object.user_groups) { message.user_groups.push(UserGroupList_UserGroup.fromJSON(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: UserGroupList): unknown { const obj: any = {}; if (message.user_groups) { obj.user_groups = message.user_groups.map((e) => e ? UserGroupList_UserGroup.toJSON(e) : undefined ); } else { obj.user_groups = []; } message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial(object: DeepPartial<UserGroupList>): UserGroupList { const message = { ...baseUserGroupList } as UserGroupList; message.user_groups = []; if (object.user_groups !== undefined && object.user_groups !== null) { for (const e of object.user_groups) { message.user_groups.push(UserGroupList_UserGroup.fromPartial(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseUserGroupList_UserGroup: object = {}; export const UserGroupList_UserGroup = { encode( message: UserGroupList_UserGroup, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.group !== undefined) { Group.encode(message.group, writer.uint32(10).fork()).ldelim(); } if (message.state !== undefined) { Int32Value.encode( { value: message.state! }, writer.uint32(18).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): UserGroupList_UserGroup { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseUserGroupList_UserGroup, } as UserGroupList_UserGroup; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.group = Group.decode(reader, reader.uint32()); break; case 2: message.state = Int32Value.decode(reader, reader.uint32()).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): UserGroupList_UserGroup { const message = { ...baseUserGroupList_UserGroup, } as UserGroupList_UserGroup; if (object.group !== undefined && object.group !== null) { message.group = Group.fromJSON(object.group); } if (object.state !== undefined && object.state !== null) { message.state = Number(object.state); } return message; }, toJSON(message: UserGroupList_UserGroup): unknown { const obj: any = {}; message.group !== undefined && (obj.group = message.group ? Group.toJSON(message.group) : undefined); message.state !== undefined && (obj.state = message.state); return obj; }, fromPartial( object: DeepPartial<UserGroupList_UserGroup> ): UserGroupList_UserGroup { const message = { ...baseUserGroupList_UserGroup, } as UserGroupList_UserGroup; if (object.group !== undefined && object.group !== null) { message.group = Group.fromPartial(object.group); } if (object.state !== undefined && object.state !== null) { message.state = object.state; } return message; }, }; const baseUsers: object = {}; export const Users = { encode(message: Users, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { for (const v of message.users) { User.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Users { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseUsers } as Users; message.users = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.users.push(User.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Users { const message = { ...baseUsers } as Users; message.users = []; if (object.users !== undefined && object.users !== null) { for (const e of object.users) { message.users.push(User.fromJSON(e)); } } return message; }, toJSON(message: Users): unknown { const obj: any = {}; if (message.users) { obj.users = message.users.map((e) => (e ? User.toJSON(e) : undefined)); } else { obj.users = []; } return obj; }, fromPartial(object: DeepPartial<Users>): Users { const message = { ...baseUsers } as Users; message.users = []; if (object.users !== undefined && object.users !== null) { for (const e of object.users) { message.users.push(User.fromPartial(e)); } } return message; }, }; const baseValidatePurchaseAppleRequest: object = { receipt: "" }; export const ValidatePurchaseAppleRequest = { encode( message: ValidatePurchaseAppleRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.receipt !== "") { writer.uint32(10).string(message.receipt); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ValidatePurchaseAppleRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseValidatePurchaseAppleRequest, } as ValidatePurchaseAppleRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.receipt = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ValidatePurchaseAppleRequest { const message = { ...baseValidatePurchaseAppleRequest, } as ValidatePurchaseAppleRequest; if (object.receipt !== undefined && object.receipt !== null) { message.receipt = String(object.receipt); } return message; }, toJSON(message: ValidatePurchaseAppleRequest): unknown { const obj: any = {}; message.receipt !== undefined && (obj.receipt = message.receipt); return obj; }, fromPartial( object: DeepPartial<ValidatePurchaseAppleRequest> ): ValidatePurchaseAppleRequest { const message = { ...baseValidatePurchaseAppleRequest, } as ValidatePurchaseAppleRequest; if (object.receipt !== undefined && object.receipt !== null) { message.receipt = object.receipt; } return message; }, }; const baseValidatePurchaseGoogleRequest: object = { purchase: "" }; export const ValidatePurchaseGoogleRequest = { encode( message: ValidatePurchaseGoogleRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.purchase !== "") { writer.uint32(10).string(message.purchase); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ValidatePurchaseGoogleRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseValidatePurchaseGoogleRequest, } as ValidatePurchaseGoogleRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.purchase = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ValidatePurchaseGoogleRequest { const message = { ...baseValidatePurchaseGoogleRequest, } as ValidatePurchaseGoogleRequest; if (object.purchase !== undefined && object.purchase !== null) { message.purchase = String(object.purchase); } return message; }, toJSON(message: ValidatePurchaseGoogleRequest): unknown { const obj: any = {}; message.purchase !== undefined && (obj.purchase = message.purchase); return obj; }, fromPartial( object: DeepPartial<ValidatePurchaseGoogleRequest> ): ValidatePurchaseGoogleRequest { const message = { ...baseValidatePurchaseGoogleRequest, } as ValidatePurchaseGoogleRequest; if (object.purchase !== undefined && object.purchase !== null) { message.purchase = object.purchase; } return message; }, }; const baseValidatePurchaseHuaweiRequest: object = { purchase: "", signature: "", }; export const ValidatePurchaseHuaweiRequest = { encode( message: ValidatePurchaseHuaweiRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.purchase !== "") { writer.uint32(10).string(message.purchase); } if (message.signature !== "") { writer.uint32(18).string(message.signature); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ValidatePurchaseHuaweiRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseValidatePurchaseHuaweiRequest, } as ValidatePurchaseHuaweiRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.purchase = reader.string(); break; case 2: message.signature = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ValidatePurchaseHuaweiRequest { const message = { ...baseValidatePurchaseHuaweiRequest, } as ValidatePurchaseHuaweiRequest; if (object.purchase !== undefined && object.purchase !== null) { message.purchase = String(object.purchase); } if (object.signature !== undefined && object.signature !== null) { message.signature = String(object.signature); } return message; }, toJSON(message: ValidatePurchaseHuaweiRequest): unknown { const obj: any = {}; message.purchase !== undefined && (obj.purchase = message.purchase); message.signature !== undefined && (obj.signature = message.signature); return obj; }, fromPartial( object: DeepPartial<ValidatePurchaseHuaweiRequest> ): ValidatePurchaseHuaweiRequest { const message = { ...baseValidatePurchaseHuaweiRequest, } as ValidatePurchaseHuaweiRequest; if (object.purchase !== undefined && object.purchase !== null) { message.purchase = object.purchase; } if (object.signature !== undefined && object.signature !== null) { message.signature = object.signature; } return message; }, }; const baseValidatedPurchase: object = { product_id: "", transaction_id: "", store: 0, provider_response: "", environment: 0, }; export const ValidatedPurchase = { encode( message: ValidatedPurchase, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.product_id !== "") { writer.uint32(10).string(message.product_id); } if (message.transaction_id !== "") { writer.uint32(18).string(message.transaction_id); } if (message.store !== 0) { writer.uint32(24).int32(message.store); } if (message.purchase_time !== undefined) { Timestamp.encode( toTimestamp(message.purchase_time), writer.uint32(34).fork() ).ldelim(); } if (message.create_time !== undefined) { Timestamp.encode( toTimestamp(message.create_time), writer.uint32(42).fork() ).ldelim(); } if (message.update_time !== undefined) { Timestamp.encode( toTimestamp(message.update_time), writer.uint32(50).fork() ).ldelim(); } if (message.provider_response !== "") { writer.uint32(58).string(message.provider_response); } if (message.environment !== 0) { writer.uint32(64).int32(message.environment); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): ValidatedPurchase { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseValidatedPurchase } as ValidatedPurchase; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.product_id = reader.string(); break; case 2: message.transaction_id = reader.string(); break; case 3: message.store = reader.int32() as any; break; case 4: message.purchase_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 5: message.create_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 6: message.update_time = fromTimestamp( Timestamp.decode(reader, reader.uint32()) ); break; case 7: message.provider_response = reader.string(); break; case 8: message.environment = reader.int32() as any; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ValidatedPurchase { const message = { ...baseValidatedPurchase } as ValidatedPurchase; if (object.product_id !== undefined && object.product_id !== null) { message.product_id = String(object.product_id); } if (object.transaction_id !== undefined && object.transaction_id !== null) { message.transaction_id = String(object.transaction_id); } if (object.store !== undefined && object.store !== null) { message.store = validatedPurchase_StoreFromJSON(object.store); } if (object.purchase_time !== undefined && object.purchase_time !== null) { message.purchase_time = fromJsonTimestamp(object.purchase_time); } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = fromJsonTimestamp(object.create_time); } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = fromJsonTimestamp(object.update_time); } if ( object.provider_response !== undefined && object.provider_response !== null ) { message.provider_response = String(object.provider_response); } if (object.environment !== undefined && object.environment !== null) { message.environment = validatedPurchase_EnvironmentFromJSON( object.environment ); } return message; }, toJSON(message: ValidatedPurchase): unknown { const obj: any = {}; message.product_id !== undefined && (obj.product_id = message.product_id); message.transaction_id !== undefined && (obj.transaction_id = message.transaction_id); message.store !== undefined && (obj.store = validatedPurchase_StoreToJSON(message.store)); message.purchase_time !== undefined && (obj.purchase_time = message.purchase_time.toISOString()); message.create_time !== undefined && (obj.create_time = message.create_time.toISOString()); message.update_time !== undefined && (obj.update_time = message.update_time.toISOString()); message.provider_response !== undefined && (obj.provider_response = message.provider_response); message.environment !== undefined && (obj.environment = validatedPurchase_EnvironmentToJSON( message.environment )); return obj; }, fromPartial(object: DeepPartial<ValidatedPurchase>): ValidatedPurchase { const message = { ...baseValidatedPurchase } as ValidatedPurchase; if (object.product_id !== undefined && object.product_id !== null) { message.product_id = object.product_id; } if (object.transaction_id !== undefined && object.transaction_id !== null) { message.transaction_id = object.transaction_id; } if (object.store !== undefined && object.store !== null) { message.store = object.store; } if (object.purchase_time !== undefined && object.purchase_time !== null) { message.purchase_time = object.purchase_time; } if (object.create_time !== undefined && object.create_time !== null) { message.create_time = object.create_time; } if (object.update_time !== undefined && object.update_time !== null) { message.update_time = object.update_time; } if ( object.provider_response !== undefined && object.provider_response !== null ) { message.provider_response = object.provider_response; } if (object.environment !== undefined && object.environment !== null) { message.environment = object.environment; } return message; }, }; const baseValidatePurchaseResponse: object = {}; export const ValidatePurchaseResponse = { encode( message: ValidatePurchaseResponse, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.validated_purchases) { ValidatedPurchase.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): ValidatePurchaseResponse { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseValidatePurchaseResponse, } as ValidatePurchaseResponse; message.validated_purchases = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.validated_purchases.push( ValidatedPurchase.decode(reader, reader.uint32()) ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): ValidatePurchaseResponse { const message = { ...baseValidatePurchaseResponse, } as ValidatePurchaseResponse; message.validated_purchases = []; if ( object.validated_purchases !== undefined && object.validated_purchases !== null ) { for (const e of object.validated_purchases) { message.validated_purchases.push(ValidatedPurchase.fromJSON(e)); } } return message; }, toJSON(message: ValidatePurchaseResponse): unknown { const obj: any = {}; if (message.validated_purchases) { obj.validated_purchases = message.validated_purchases.map((e) => e ? ValidatedPurchase.toJSON(e) : undefined ); } else { obj.validated_purchases = []; } return obj; }, fromPartial( object: DeepPartial<ValidatePurchaseResponse> ): ValidatePurchaseResponse { const message = { ...baseValidatePurchaseResponse, } as ValidatePurchaseResponse; message.validated_purchases = []; if ( object.validated_purchases !== undefined && object.validated_purchases !== null ) { for (const e of object.validated_purchases) { message.validated_purchases.push(ValidatedPurchase.fromPartial(e)); } } return message; }, }; const basePurchaseList: object = { cursor: "" }; export const PurchaseList = { encode( message: PurchaseList, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.validated_purchases) { ValidatedPurchase.encode(v!, writer.uint32(10).fork()).ldelim(); } if (message.cursor !== "") { writer.uint32(18).string(message.cursor); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): PurchaseList { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...basePurchaseList } as PurchaseList; message.validated_purchases = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.validated_purchases.push( ValidatedPurchase.decode(reader, reader.uint32()) ); break; case 2: message.cursor = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): PurchaseList { const message = { ...basePurchaseList } as PurchaseList; message.validated_purchases = []; if ( object.validated_purchases !== undefined && object.validated_purchases !== null ) { for (const e of object.validated_purchases) { message.validated_purchases.push(ValidatedPurchase.fromJSON(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = String(object.cursor); } return message; }, toJSON(message: PurchaseList): unknown { const obj: any = {}; if (message.validated_purchases) { obj.validated_purchases = message.validated_purchases.map((e) => e ? ValidatedPurchase.toJSON(e) : undefined ); } else { obj.validated_purchases = []; } message.cursor !== undefined && (obj.cursor = message.cursor); return obj; }, fromPartial(object: DeepPartial<PurchaseList>): PurchaseList { const message = { ...basePurchaseList } as PurchaseList; message.validated_purchases = []; if ( object.validated_purchases !== undefined && object.validated_purchases !== null ) { for (const e of object.validated_purchases) { message.validated_purchases.push(ValidatedPurchase.fromPartial(e)); } } if (object.cursor !== undefined && object.cursor !== null) { message.cursor = object.cursor; } return message; }, }; const baseWriteLeaderboardRecordRequest: object = { leaderboard_id: "" }; export const WriteLeaderboardRecordRequest = { encode( message: WriteLeaderboardRecordRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.leaderboard_id !== "") { writer.uint32(10).string(message.leaderboard_id); } if (message.record !== undefined) { WriteLeaderboardRecordRequest_LeaderboardRecordWrite.encode( message.record, writer.uint32(18).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): WriteLeaderboardRecordRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseWriteLeaderboardRecordRequest, } as WriteLeaderboardRecordRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.leaderboard_id = reader.string(); break; case 2: message.record = WriteLeaderboardRecordRequest_LeaderboardRecordWrite.decode( reader, reader.uint32() ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): WriteLeaderboardRecordRequest { const message = { ...baseWriteLeaderboardRecordRequest, } as WriteLeaderboardRecordRequest; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = String(object.leaderboard_id); } if (object.record !== undefined && object.record !== null) { message.record = WriteLeaderboardRecordRequest_LeaderboardRecordWrite.fromJSON( object.record ); } return message; }, toJSON(message: WriteLeaderboardRecordRequest): unknown { const obj: any = {}; message.leaderboard_id !== undefined && (obj.leaderboard_id = message.leaderboard_id); message.record !== undefined && (obj.record = message.record ? WriteLeaderboardRecordRequest_LeaderboardRecordWrite.toJSON( message.record ) : undefined); return obj; }, fromPartial( object: DeepPartial<WriteLeaderboardRecordRequest> ): WriteLeaderboardRecordRequest { const message = { ...baseWriteLeaderboardRecordRequest, } as WriteLeaderboardRecordRequest; if (object.leaderboard_id !== undefined && object.leaderboard_id !== null) { message.leaderboard_id = object.leaderboard_id; } if (object.record !== undefined && object.record !== null) { message.record = WriteLeaderboardRecordRequest_LeaderboardRecordWrite.fromPartial( object.record ); } return message; }, }; const baseWriteLeaderboardRecordRequest_LeaderboardRecordWrite: object = { score: 0, subscore: 0, metadata: "", operator: 0, }; export const WriteLeaderboardRecordRequest_LeaderboardRecordWrite = { encode( message: WriteLeaderboardRecordRequest_LeaderboardRecordWrite, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.score !== 0) { writer.uint32(8).int64(message.score); } if (message.subscore !== 0) { writer.uint32(16).int64(message.subscore); } if (message.metadata !== "") { writer.uint32(26).string(message.metadata); } if (message.operator !== 0) { writer.uint32(32).int32(message.operator); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): WriteLeaderboardRecordRequest_LeaderboardRecordWrite { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseWriteLeaderboardRecordRequest_LeaderboardRecordWrite, } as WriteLeaderboardRecordRequest_LeaderboardRecordWrite; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.score = longToNumber(reader.int64() as Long); break; case 2: message.subscore = longToNumber(reader.int64() as Long); break; case 3: message.metadata = reader.string(); break; case 4: message.operator = reader.int32() as any; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): WriteLeaderboardRecordRequest_LeaderboardRecordWrite { const message = { ...baseWriteLeaderboardRecordRequest_LeaderboardRecordWrite, } as WriteLeaderboardRecordRequest_LeaderboardRecordWrite; if (object.score !== undefined && object.score !== null) { message.score = Number(object.score); } if (object.subscore !== undefined && object.subscore !== null) { message.subscore = Number(object.subscore); } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = String(object.metadata); } if (object.operator !== undefined && object.operator !== null) { message.operator = overrideOperatorFromJSON(object.operator); } return message; }, toJSON( message: WriteLeaderboardRecordRequest_LeaderboardRecordWrite ): unknown { const obj: any = {}; message.score !== undefined && (obj.score = message.score); message.subscore !== undefined && (obj.subscore = message.subscore); message.metadata !== undefined && (obj.metadata = message.metadata); message.operator !== undefined && (obj.operator = overrideOperatorToJSON(message.operator)); return obj; }, fromPartial( object: DeepPartial<WriteLeaderboardRecordRequest_LeaderboardRecordWrite> ): WriteLeaderboardRecordRequest_LeaderboardRecordWrite { const message = { ...baseWriteLeaderboardRecordRequest_LeaderboardRecordWrite, } as WriteLeaderboardRecordRequest_LeaderboardRecordWrite; if (object.score !== undefined && object.score !== null) { message.score = object.score; } if (object.subscore !== undefined && object.subscore !== null) { message.subscore = object.subscore; } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = object.metadata; } if (object.operator !== undefined && object.operator !== null) { message.operator = object.operator; } return message; }, }; const baseWriteStorageObject: object = { collection: "", key: "", value: "", version: "", }; export const WriteStorageObject = { encode( message: WriteStorageObject, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.collection !== "") { writer.uint32(10).string(message.collection); } if (message.key !== "") { writer.uint32(18).string(message.key); } if (message.value !== "") { writer.uint32(26).string(message.value); } if (message.version !== "") { writer.uint32(34).string(message.version); } if (message.permission_read !== undefined) { Int32Value.encode( { value: message.permission_read! }, writer.uint32(42).fork() ).ldelim(); } if (message.permission_write !== undefined) { Int32Value.encode( { value: message.permission_write! }, writer.uint32(50).fork() ).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): WriteStorageObject { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseWriteStorageObject } as WriteStorageObject; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.collection = reader.string(); break; case 2: message.key = reader.string(); break; case 3: message.value = reader.string(); break; case 4: message.version = reader.string(); break; case 5: message.permission_read = Int32Value.decode( reader, reader.uint32() ).value; break; case 6: message.permission_write = Int32Value.decode( reader, reader.uint32() ).value; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): WriteStorageObject { const message = { ...baseWriteStorageObject } as WriteStorageObject; if (object.collection !== undefined && object.collection !== null) { message.collection = String(object.collection); } if (object.key !== undefined && object.key !== null) { message.key = String(object.key); } if (object.value !== undefined && object.value !== null) { message.value = String(object.value); } if (object.version !== undefined && object.version !== null) { message.version = String(object.version); } if ( object.permission_read !== undefined && object.permission_read !== null ) { message.permission_read = Number(object.permission_read); } if ( object.permission_write !== undefined && object.permission_write !== null ) { message.permission_write = Number(object.permission_write); } return message; }, toJSON(message: WriteStorageObject): unknown { const obj: any = {}; message.collection !== undefined && (obj.collection = message.collection); message.key !== undefined && (obj.key = message.key); message.value !== undefined && (obj.value = message.value); message.version !== undefined && (obj.version = message.version); message.permission_read !== undefined && (obj.permission_read = message.permission_read); message.permission_write !== undefined && (obj.permission_write = message.permission_write); return obj; }, fromPartial(object: DeepPartial<WriteStorageObject>): WriteStorageObject { const message = { ...baseWriteStorageObject } as WriteStorageObject; if (object.collection !== undefined && object.collection !== null) { message.collection = object.collection; } if (object.key !== undefined && object.key !== null) { message.key = object.key; } if (object.value !== undefined && object.value !== null) { message.value = object.value; } if (object.version !== undefined && object.version !== null) { message.version = object.version; } if ( object.permission_read !== undefined && object.permission_read !== null ) { message.permission_read = object.permission_read; } if ( object.permission_write !== undefined && object.permission_write !== null ) { message.permission_write = object.permission_write; } return message; }, }; const baseWriteStorageObjectsRequest: object = {}; export const WriteStorageObjectsRequest = { encode( message: WriteStorageObjectsRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { for (const v of message.objects) { WriteStorageObject.encode(v!, writer.uint32(10).fork()).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): WriteStorageObjectsRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseWriteStorageObjectsRequest, } as WriteStorageObjectsRequest; message.objects = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.objects.push( WriteStorageObject.decode(reader, reader.uint32()) ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): WriteStorageObjectsRequest { const message = { ...baseWriteStorageObjectsRequest, } as WriteStorageObjectsRequest; message.objects = []; if (object.objects !== undefined && object.objects !== null) { for (const e of object.objects) { message.objects.push(WriteStorageObject.fromJSON(e)); } } return message; }, toJSON(message: WriteStorageObjectsRequest): unknown { const obj: any = {}; if (message.objects) { obj.objects = message.objects.map((e) => e ? WriteStorageObject.toJSON(e) : undefined ); } else { obj.objects = []; } return obj; }, fromPartial( object: DeepPartial<WriteStorageObjectsRequest> ): WriteStorageObjectsRequest { const message = { ...baseWriteStorageObjectsRequest, } as WriteStorageObjectsRequest; message.objects = []; if (object.objects !== undefined && object.objects !== null) { for (const e of object.objects) { message.objects.push(WriteStorageObject.fromPartial(e)); } } return message; }, }; const baseWriteTournamentRecordRequest: object = { tournament_id: "" }; export const WriteTournamentRecordRequest = { encode( message: WriteTournamentRecordRequest, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.tournament_id !== "") { writer.uint32(10).string(message.tournament_id); } if (message.record !== undefined) { WriteTournamentRecordRequest_TournamentRecordWrite.encode( message.record, writer.uint32(18).fork() ).ldelim(); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): WriteTournamentRecordRequest { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseWriteTournamentRecordRequest, } as WriteTournamentRecordRequest; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.tournament_id = reader.string(); break; case 2: message.record = WriteTournamentRecordRequest_TournamentRecordWrite.decode( reader, reader.uint32() ); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): WriteTournamentRecordRequest { const message = { ...baseWriteTournamentRecordRequest, } as WriteTournamentRecordRequest; if (object.tournament_id !== undefined && object.tournament_id !== null) { message.tournament_id = String(object.tournament_id); } if (object.record !== undefined && object.record !== null) { message.record = WriteTournamentRecordRequest_TournamentRecordWrite.fromJSON( object.record ); } return message; }, toJSON(message: WriteTournamentRecordRequest): unknown { const obj: any = {}; message.tournament_id !== undefined && (obj.tournament_id = message.tournament_id); message.record !== undefined && (obj.record = message.record ? WriteTournamentRecordRequest_TournamentRecordWrite.toJSON( message.record ) : undefined); return obj; }, fromPartial( object: DeepPartial<WriteTournamentRecordRequest> ): WriteTournamentRecordRequest { const message = { ...baseWriteTournamentRecordRequest, } as WriteTournamentRecordRequest; if (object.tournament_id !== undefined && object.tournament_id !== null) { message.tournament_id = object.tournament_id; } if (object.record !== undefined && object.record !== null) { message.record = WriteTournamentRecordRequest_TournamentRecordWrite.fromPartial( object.record ); } return message; }, }; const baseWriteTournamentRecordRequest_TournamentRecordWrite: object = { score: 0, subscore: 0, metadata: "", operator: 0, }; export const WriteTournamentRecordRequest_TournamentRecordWrite = { encode( message: WriteTournamentRecordRequest_TournamentRecordWrite, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.score !== 0) { writer.uint32(8).int64(message.score); } if (message.subscore !== 0) { writer.uint32(16).int64(message.subscore); } if (message.metadata !== "") { writer.uint32(26).string(message.metadata); } if (message.operator !== 0) { writer.uint32(32).int32(message.operator); } return writer; }, decode( input: _m0.Reader | Uint8Array, length?: number ): WriteTournamentRecordRequest_TournamentRecordWrite { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseWriteTournamentRecordRequest_TournamentRecordWrite, } as WriteTournamentRecordRequest_TournamentRecordWrite; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.score = longToNumber(reader.int64() as Long); break; case 2: message.subscore = longToNumber(reader.int64() as Long); break; case 3: message.metadata = reader.string(); break; case 4: message.operator = reader.int32() as any; break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): WriteTournamentRecordRequest_TournamentRecordWrite { const message = { ...baseWriteTournamentRecordRequest_TournamentRecordWrite, } as WriteTournamentRecordRequest_TournamentRecordWrite; if (object.score !== undefined && object.score !== null) { message.score = Number(object.score); } if (object.subscore !== undefined && object.subscore !== null) { message.subscore = Number(object.subscore); } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = String(object.metadata); } if (object.operator !== undefined && object.operator !== null) { message.operator = overrideOperatorFromJSON(object.operator); } return message; }, toJSON(message: WriteTournamentRecordRequest_TournamentRecordWrite): unknown { const obj: any = {}; message.score !== undefined && (obj.score = message.score); message.subscore !== undefined && (obj.subscore = message.subscore); message.metadata !== undefined && (obj.metadata = message.metadata); message.operator !== undefined && (obj.operator = overrideOperatorToJSON(message.operator)); return obj; }, fromPartial( object: DeepPartial<WriteTournamentRecordRequest_TournamentRecordWrite> ): WriteTournamentRecordRequest_TournamentRecordWrite { const message = { ...baseWriteTournamentRecordRequest_TournamentRecordWrite, } as WriteTournamentRecordRequest_TournamentRecordWrite; if (object.score !== undefined && object.score !== null) { message.score = object.score; } if (object.subscore !== undefined && object.subscore !== null) { message.subscore = object.subscore; } if (object.metadata !== undefined && object.metadata !== null) { message.metadata = object.metadata; } if (object.operator !== undefined && object.operator !== null) { message.operator = object.operator; } return message; }, }; declare var self: any | undefined; declare var window: any | undefined; var globalThis: any = (() => { if (typeof globalThis !== "undefined") return globalThis; if (typeof self !== "undefined") return self; if (typeof window !== "undefined") return window; if (typeof global !== "undefined") return global; throw "Unable to locate global object"; })(); type Builtin = | Date | Function | Uint8Array | string | number | boolean | undefined; export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends { $case: string } ? { [K in keyof Omit<T, "$case">]?: DeepPartial<T[K]> } & { $case: T["$case"]; } : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T>; function toTimestamp(date: Date): Timestamp { const seconds = date.getTime() / 1_000; const nanos = (date.getTime() % 1_000) * 1_000_000; return { seconds, nanos }; } function fromTimestamp(t: Timestamp): Date { let millis = t.seconds * 1_000; millis += t.nanos / 1_000_000; return new Date(millis); } function fromJsonTimestamp(o: any): Date { if (o instanceof Date) { return o; } else if (typeof o === "string") { return new Date(o); } else { return fromTimestamp(Timestamp.fromJSON(o)); } } function longToNumber(long: Long): number { if (long.gt(Number.MAX_SAFE_INTEGER)) { throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER"); } return long.toNumber(); } if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); }
the_stack
import {ATTRIBUTE_TYPE} from '@typedorm/common'; import {User, UserPrimaryKey} from '@typedorm/core/__mocks__/user'; import {Condition} from '../condition'; import {ExpressionInputParser} from '../expression-input-parser'; import {Filter} from '../filter'; import {KeyCondition} from '../key-condition'; import {Projection} from '../projection'; import {Update} from '../update/update'; let expInputParser: ExpressionInputParser; beforeEach(() => { expInputParser = new ExpressionInputParser(); }); /** * @group parseToKeyCondition */ test('parses keyCondition input', () => { const parsedCondition = expInputParser.parseToKeyCondition('SK', { BEGINS_WITH: 'USER#', }); expect(parsedCondition).toBeInstanceOf(KeyCondition); expect(parsedCondition.expression).toEqual( 'begins_with(#KY_CE_SK, :KY_CE_SK)' ); }); /** * @group parseToFilter */ test('parses simple filter input', () => { const parsedFilter = expInputParser.parseToFilter<User, UserPrimaryKey>({ age: { EQ: 12, }, }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter?.expression).toEqual('#FE_age = :FE_age'); }); /** * Issue #139 */ test('parses nested key filter input to valid expression', () => { const parsedFilter = expInputParser.parseToFilter<any, {}>({ AND: { 'contact.addresses[0]': { EQ: 12, }, 'bio[0].age': { LE: 2, }, }, }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter).toEqual({ _names: { '#FE_contact': 'contact', '#FE_contact_addresses': 'addresses', '#FE_bio': 'bio', '#FE_bio_age': 'age', }, _values: { ':FE_contact_addresses': 12, ':FE_bio_age': 2, }, expression: '(#FE_contact.#FE_contact_addresses[0] = :FE_contact_addresses) AND (#FE_bio[0].#FE_bio_age <= :FE_bio_age)', }); }); test('parses filter with range operator', () => { const parsedFilter = expInputParser.parseToFilter<User, UserPrimaryKey>({ name: { CONTAINS: 'tes', }, }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter?.expression).toEqual('contains(#FE_name, :FE_name)'); }); test('parses filter with key only operator', () => { const parsedFilter = expInputParser.parseToFilter<User, UserPrimaryKey>({ status: 'ATTRIBUTE_EXISTS', }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter?.expression).toEqual('attribute_exists(#FE_status)'); }); test('parses filter with attribute type operator', () => { const parsedFilter = expInputParser.parseToFilter<User, UserPrimaryKey>({ status: { ATTRIBUTE_TYPE: ATTRIBUTE_TYPE.BOOLEAN, }, }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter?.expression).toEqual( 'attribute_type(#FE_status, :FE_status)' ); expect(parsedFilter?.values).toEqual({':FE_status': 'BOOL'}); }); test('parses filter with size operator', () => { const parsedFilter = expInputParser.parseToFilter<User, UserPrimaryKey>({ status: { SIZE: { EQ: 1, }, }, }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter?.expression).toEqual('size(#FE_status) = :FE_status'); }); test('parses filter with single logical operator', () => { const parsedFilter = expInputParser.parseToFilter<User, UserPrimaryKey>({ AND: { age: { BETWEEN: [1, 3], }, name: { CONTAINS: 'zuki', }, }, }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter?.expression).toEqual( '(#FE_age BETWEEN :FE_age_start AND :FE_age_end) AND (contains(#FE_name, :FE_name))' ); expect(parsedFilter?.names).toEqual({'#FE_age': 'age', '#FE_name': 'name'}); expect(parsedFilter?.values).toEqual({ ':FE_age_end': 3, ':FE_age_start': 1, ':FE_name': 'zuki', }); }); test('parses filter with `NOT` logical operator', () => { const parsedFilter = expInputParser.parseToFilter<User, UserPrimaryKey>({ NOT: { age: { BEGINS_WITH: 1, }, }, }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter?.expression).toEqual( 'NOT (begins_with(#FE_age, :FE_age))' ); }); test('parses nester object property', () => { const parsedFilter = expInputParser.parseToFilter< User & {'profile.name.firstName': string}, UserPrimaryKey >({ 'profile.name.firstName': { EQ: 'sam', }, }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter?.expression).toEqual( '#FE_profile.#FE_profile_name.#FE_profile_name_firstName = :FE_profile_name_firstName' ); expect(parsedFilter?.names).toEqual({ '#FE_profile': 'profile', '#FE_profile_name': 'name', '#FE_profile_name_firstName': 'firstName', }); expect(parsedFilter?.values).toEqual({ ':FE_profile_name_firstName': 'sam', }); }); test('parses filter with complex nested logical operators', () => { const parsedFilter = expInputParser.parseToFilter<User, UserPrimaryKey>({ OR: { AND: { age: { BETWEEN: [1, 4], }, NOT: { status: { ATTRIBUTE_TYPE: ATTRIBUTE_TYPE.STRING_SET, }, }, }, name: { EQ: 'admin', }, }, }); expect(parsedFilter).toBeInstanceOf(Filter); expect(parsedFilter?.expression).toEqual( '((#FE_age BETWEEN :FE_age_start AND :FE_age_end) AND (NOT (attribute_type(#FE_status, :FE_status)))) OR (#FE_name = :FE_name)' ); expect(parsedFilter?.names).toEqual({ '#FE_age': 'age', '#FE_name': 'name', '#FE_status': 'status', }); expect(parsedFilter?.values).toEqual({ ':FE_age_end': 4, ':FE_age_start': 1, ':FE_name': 'admin', ':FE_status': 'SS', }); }); test('parses deep nested condition', () => { const parsedCondition = expInputParser.parseToCondition<User>({ NOT: { NOT: { OR: { AND: { age: 'ATTRIBUTE_EXISTS', name: 'ATTRIBUTE_NOT_EXISTS', }, status: { LE: '1', }, }, }, }, }); expect(parsedCondition).toBeInstanceOf(Condition); expect(parsedCondition?.expression).toEqual( 'NOT (NOT (((attribute_exists(#CE_age)) AND (attribute_not_exists(#CE_name))) OR (#CE_status <= :CE_status)))' ); expect(parsedCondition?.names).toEqual({ '#CE_age': 'age', '#CE_name': 'name', '#CE_status': 'status', }); expect(parsedCondition?.values).toEqual({ ':CE_status': '1', }); }); /** * @group parseToProjection */ test('parses options to valid projection', () => { const projection = expInputParser.parseToProjection<User>([ 'id', 'name', 'status.active', ]); expect(projection).toBeInstanceOf(Projection); expect(projection.expression).toEqual( '#PE_id, #PE_name, #PE_status.#PE_status_active' ); }); /** * @group parseToUpdate * */ test('parses update body to update expression', () => { const update = expInputParser.parseToUpdate< User, {'user.newAddresses': Array<string>} >({ id: '2', name: { IF_NOT_EXISTS: { $PATH: 'id', $VALUE: '123', }, }, status: { IF_NOT_EXISTS: '1', }, age: { INCREMENT_BY: 2, }, addresses: { LIST_APPEND: ['1234'], }, 'user.newAddresses': { LIST_APPEND: { $PATH: 'addresses', $VALUE: ['123'], }, }, }); expect(update).toBeInstanceOf(Update); expect(update).toEqual({ _names: { '#UE_addresses': 'addresses', '#UE_age': 'age', '#UE_id': 'id', '#UE_name': 'name', '#UE_status': 'status', '#UE_user': 'user', '#UE_user_newAddresses': 'newAddresses', }, _values: { ':UE_addresses': ['1234'], ':UE_user_newAddresses': ['123'], ':UE_age': 2, ':UE_id': '2', ':UE_name': '123', ':UE_status': '1', }, expression: 'SET #UE_id = :UE_id, #UE_name = if_not_exists(#UE_id, :UE_name), #UE_status = if_not_exists(#UE_status, :UE_status), #UE_age = #UE_age + :UE_age, #UE_addresses = list_append(#UE_addresses, :UE_addresses), #UE_user.#UE_user_newAddresses = list_append(#UE_addresses, :UE_user_newAddresses)', prefix: '', }); }); test('parses update body to update expression with custom transform overrides ', () => { const update = expInputParser.parseToUpdate< User, {'user.newAddresses': Array<string>} >( { id: '2', name: { IF_NOT_EXISTS: { $PATH: 'id', $VALUE: '123', }, }, }, { // when custom transformation is applied name: 'custom-transformed-name', } ); expect(update).toBeInstanceOf(Update); expect(update).toEqual({ _names: { '#UE_id': 'id', '#UE_name': 'name', }, _values: { ':UE_id': '2', ':UE_name': 'custom-transformed-name', }, expression: 'SET #UE_id = :UE_id, #UE_name = if_not_exists(#UE_id, :UE_name)', prefix: '', }); }); test('parses dynamic body to update expression with custom transform overrides', () => { const update = expInputParser.parseToUpdate< User, {'user.newAddresses': Array<string>} >( { id: '2', age: { ADD: 2, }, }, { // even tho we provided custom transformed value here, it should not be included age: 200, } ); expect(update).toBeInstanceOf(Update); expect(update).toEqual({ _names: { '#UE_age': 'age', '#UE_id': 'id', }, _values: { ':UE_age': 2, ':UE_id': '2', }, expression: 'SET #UE_id = :UE_id ADD #UE_age :UE_age', prefix: '', }); }); test('parses explicit set update body', () => { const update = expInputParser.parseToUpdate<User, UserPrimaryKey>({ id: { SET: '2', }, name: { SET: { IF_NOT_EXISTS: { $PATH: 'age', $VALUE: '2', }, }, }, age: { SET: { INCREMENT_BY: 2, }, }, addresses: { SET: { LIST_APPEND: ['1234'], }, }, }); expect(update).toBeInstanceOf(Update); expect(update.expression).toEqual( 'SET #UE_id = :UE_id, #UE_name = if_not_exists(#UE_age, :UE_name), #UE_age = #UE_age + :UE_age, #UE_addresses = list_append(#UE_addresses, :UE_addresses)' ); expect(update).toEqual({ _names: { '#UE_addresses': 'addresses', '#UE_age': 'age', '#UE_id': 'id', '#UE_name': 'name', }, _values: { ':UE_addresses': ['1234'], ':UE_age': 2, ':UE_id': '2', ':UE_name': '2', }, expression: 'SET #UE_id = :UE_id, #UE_name = if_not_exists(#UE_age, :UE_name), #UE_age = #UE_age + :UE_age, #UE_addresses = list_append(#UE_addresses, :UE_addresses)', prefix: '', }); }); test('parses explicit "ADD" update body', () => { const update = expInputParser.parseToUpdate< User, {newAddresses: Array<number>} >({ age: { ADD: 1, }, addresses: { ADD: ['123'], }, newAddresses: { ADD: [1234], }, }); expect(update).toBeInstanceOf(Update); expect(update).toEqual({ _names: { '#UE_addresses': 'addresses', '#UE_age': 'age', '#UE_newAddresses': 'newAddresses', }, _values: { ':UE_addresses': ['123'], ':UE_age': 1, ':UE_newAddresses': [1234], }, expression: 'ADD #UE_age :UE_age, #UE_addresses :UE_addresses, #UE_newAddresses :UE_newAddresses', prefix: '', }); }); test('parses explicit "REMOVE" update body', () => { const update = expInputParser.parseToUpdate< User, {newAddresses: Array<Buffer>} >({ age: { REMOVE: true, }, newAddresses: { REMOVE: { $AT_INDEX: [1, 3, 4], }, }, }); expect(update).toBeInstanceOf(Update); expect(update).toEqual({ _names: { '#UE_age': 'age', '#UE_newAddresses': 'newAddresses', }, _values: {}, expression: 'REMOVE #UE_age, #UE_newAddresses[1], #UE_newAddresses[3], #UE_newAddresses[4]', prefix: '', }); }); test('parses explicit "DELETE" update body', () => { const update = expInputParser.parseToUpdate< User, {newAddresses: Array<Buffer>} >({ addresses: { DELETE: ['123'], }, newAddresses: { DELETE: [Buffer.from('12')], }, }); expect(update).toBeInstanceOf(Update); expect(update).toEqual({ _names: { '#UE_addresses': 'addresses', '#UE_newAddresses': 'newAddresses', }, _values: { ':UE_addresses': ['123'], ':UE_newAddresses': [Buffer.from('12')], }, expression: 'DELETE #UE_addresses :UE_addresses, #UE_newAddresses :UE_newAddresses', prefix: '', }); }); test('parses update body with mixed actions', () => { const update = expInputParser.parseToUpdate<User>({ id: '2', name: { IF_NOT_EXISTS: { $PATH: 'id', $VALUE: '123', }, }, status: { SET: { IF_NOT_EXISTS: 'active', }, }, age: { ADD: 1, }, addresses: { DELETE: ['123'], }, }); expect(update).toBeInstanceOf(Update); expect(update).toEqual({ _names: { '#UE_addresses': 'addresses', '#UE_age': 'age', '#UE_id': 'id', '#UE_name': 'name', '#UE_status': 'status', }, _values: { ':UE_addresses': ['123'], ':UE_age': 1, ':UE_id': '2', ':UE_name': '123', ':UE_status': 'active', }, expression: 'SET #UE_id = :UE_id, #UE_name = if_not_exists(#UE_id, :UE_name), #UE_status = if_not_exists(#UE_status, :UE_status) ADD #UE_age :UE_age DELETE #UE_addresses :UE_addresses', prefix: '', }); }); /** * @group parseToUpdateValue */ test('correctly parses ADD and returns update values', () => { const value = expInputParser.parseAttributeToUpdateValue('age', { ADD: 1, }); expect(value).toEqual({type: 'dynamic', value: 1}); }); test('skips parsing and returns update values', () => { const value = expInputParser.parseAttributeToUpdateValue('name', { firstName: 'test', }); expect(value).toEqual({ type: 'static', value: { firstName: 'test', }, }); }); test('parses SET action with static value', () => { const value = expInputParser.parseAttributeToUpdateValue('name', { IF_NOT_EXISTS: 'new name', }); expect(value).toEqual({ type: 'static', value: 'new name', }); }); test('parses SET action as dynamic value', () => { const value = expInputParser.parseAttributeToUpdateValue('age', { INCREMENT_BY: 2, }); expect(value).toEqual({ type: 'dynamic', value: 2, }); }); test('parses SET action as dynamic value for nested list actions', () => { const value = expInputParser.parseAttributeToUpdateValue( 'addresses[1]', 'new address' ); expect(value).toEqual({ type: 'dynamic', value: 'new address', }); });
the_stack
import Vue from 'vue'; import { mount } from '@vue/test-utils'; import { defineComponent } from '@vue/composition-api'; import outdent from 'outdent'; import frag from '..'; import { dualMount, createMountTarget, } from './utils'; Vue.config.ignoredElements = ['app', 'frag']; test('Nested frags', async () => { const ChildComp = defineComponent({ template: '<div v-frag>{{ depth }} <child-comp v-if="depth" :depth="depth - 1" /></div>', props: { depth: { type: Number, default: 5, }, }, directives: { frag, }, beforeCreate() { this.$options.components!.ChildComp = ChildComp; }, }); const ParentComp = { template: '<div v-frag>Parent <child-comp /></div>', directives: { frag, }, components: { ChildComp, }, }; const usage = { template: '<parent-comp />', components: { ParentComp, }, }; const wrapper = mount(usage, { attachTo: createMountTarget(), }); expect(document.body.innerHTML).toBe('Parent 5 4 3 2 1 0 <!---->'); wrapper.destroy(); }); test('v-html', async () => { const FragComponent = defineComponent({ template: '<frag v-frag v-html="code" />', directives: { frag, }, props: { num: { type: Number, required: true, }, }, computed: { code(): string { return `<child-a>${this.num}</child-a><child-b>${this.num + 1}</child-b>`; }, }, }); const usage = { template: '<app><frag-component :num="num"/></app>', components: { FragComponent, }, data() { return { num: 0, }; }, }; const wrapper = mount(usage); expect(wrapper.html()).toBe(outdent` <app> <child-a>0</child-a> <child-b>1</child-b> </app> `); await wrapper.setData({ num: 1 }); expect(wrapper.html()).toBe(outdent` <app> <child-a>1</child-a> <child-b>2</child-b> </app> `); await wrapper.setData({ num: 2 }); expect(wrapper.html()).toBe(outdent` <app> <child-a>2</child-a> <child-b>3</child-b> </app> `); }); describe('Reactivity', () => { test('Data', async () => { const FragComponent = { template: ` <frag v-frag>Hello world {{ number }}</frag> `, directives: { frag, }, props: ['number'], }; const usage = { template: ` <app><frag-component :number="number" /></app> `, components: { FragComponent, }, data() { return { number: 0, }; }, }; const wrapper = dualMount(usage); const number = Date.now(); await wrapper.setData({ number }); expect(wrapper.frag.html()).toBe(`<app>Hello world ${number}</app>`); wrapper.expectMatchingDom(); }); test('v-if template', async () => { const usage = { template: ` <app> <frag v-frag> <template v-if="show">A</template> </frag> </app> `, directives: { frag, }, data() { return { show: false, }; }, }; const empty = outdent` <app> <!----> </app> `; const ifTrue = '<app>A</app>'; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe(empty); wrapper.expectMatchingDom(); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe(ifTrue); wrapper.expectMatchingDom(); await wrapper.setData({ show: false }); expect(wrapper.frag.html()).toBe(empty); wrapper.expectMatchingDom(); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe(ifTrue); wrapper.expectMatchingDom(); }); test('v-if element', async () => { const FragComponent = { template: ` <frag v-frag> <div v-if="show">A</div> </frag> `, directives: { frag, }, props: ['show'], }; const usage = { template: ` <app class="wrapper"> <frag-component :show="show" /> </app> `, components: { FragComponent, }, data() { return { show: false, }; }, }; const empty = outdent` <app class="wrapper"> <!----> </app> `; const ifTrue = outdent` <app class="wrapper"> <div>A</div> </app> `; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe(empty); wrapper.expectMatchingDom(); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe(ifTrue); wrapper.expectMatchingDom(); await wrapper.setData({ show: false }); expect(wrapper.frag.html()).toBe(empty); wrapper.expectMatchingDom(); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe(ifTrue); wrapper.expectMatchingDom(); }); test('v-for template', async () => { const FragComponent = { template: '<frag v-frag><template v-for="i in num">{{ i }}</template></frag>', directives: { frag, }, props: ['num'], }; const usage = { template: '<app><frag-component :num="num" /></app>', components: { FragComponent, }, data() { return { num: 0, }; }, }; const tpl = (content: string) => `<app>${content}</app>`; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe(tpl('\n <!---->\n')); wrapper.expectMatchingDom(); await wrapper.setData({ num: 1 }); expect(wrapper.frag.html()).toBe(tpl('1')); await wrapper.setData({ num: 2 }); expect(wrapper.frag.html()).toBe(tpl('12')); await wrapper.setData({ num: 3 }); expect(wrapper.frag.html()).toBe(tpl('123')); }); test('v-for element', async () => { const FragComponent = { template: ` <frag v-frag> <div v-for="i in num">{{ i }}</div> </frag> `, directives: { frag, }, props: ['num'], }; const usage = { template: ` <app> <frag-component :num="num" /> </app> `, components: { FragComponent, }, data() { return { num: 1, }; }, }; const tpl = (children: number[]) => outdent` <app> ${children.map(n => `<div>${n}</div>`).join('\n ')} </app> `; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe(tpl([1])); wrapper.expectMatchingDom(); await wrapper.setData({ num: 2 }); expect(wrapper.frag.html()).toBe(tpl([1, 2])); wrapper.expectMatchingDom(); await wrapper.setData({ num: 3 }); expect(wrapper.frag.html()).toBe(tpl([1, 2, 3])); wrapper.expectMatchingDom(); }); test('slot w/ v-if', async () => { const FragComponent = { template: ` <frag v-frag> <template v-if="show">{{ name }}</template> <slot /> </frag> `, directives: { frag, }, props: ['name', 'show'], }; const usage = { template: ` <app class="wrapper"> <frag-component name="A" :show="show"> <frag-component name="B" :show="show" /> </frag-component> </app> `, components: { FragComponent, }, data() { return { show: false, }; }, }; const empty = outdent` <app class="wrapper"> <!----> <!----> </app> `; const ifTrue = '<app class="wrapper">A B </app>'; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe(empty); wrapper.expectMatchingDom(); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe(ifTrue); wrapper.expectMatchingDom(); await wrapper.setData({ show: false }); expect(wrapper.frag.html()).toBe(empty); wrapper.expectMatchingDom(); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe(ifTrue); wrapper.expectMatchingDom(); }); test('slot w/ v-for', async () => { const FragComponent = { template: ` <frag v-frag> <div v-for="i in num">{{ name }} {{ i }}</div> <slot /> </frag> `, directives: { frag, }, props: ['name', 'num'], }; const usage = { template: ` <app> <frag-component name="A" :num="num"> <frag-component name="B" :num="num"> <frag-component name="C" :num="num" /> </frag-component> </frag-component> </frag-component> </app> `, components: { FragComponent, }, data() { return { num: 1, }; }, }; const tpl = (children: string[]) => outdent` <app> ${children.map(n => `<div>${n}</div>`).join('\n ')} </app> `; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe(tpl(['A 1', 'B 1', 'C 1'])); wrapper.expectMatchingDom(); await wrapper.setData({ num: 2 }); expect(wrapper.frag.html()).toBe(tpl(['A 1', 'A 2', 'B 1', 'B 2', 'C 1', 'C 2'])); wrapper.expectMatchingDom(); await wrapper.setData({ num: 3 }); expect(wrapper.frag.html()).toBe(tpl(['A 1', 'A 2', 'A 3', 'B 1', 'B 2', 'B 3', 'C 1', 'C 2', 'C 3'])); wrapper.expectMatchingDom(); }); }); test('Parent v-if', async () => { const FragComponent = { template: '<frag v-frag>Hello world</frag>', directives: { frag, }, }; const fragApp = { template: '<app><frag-component v-if="show" /></app>', components: { FragComponent, }, data() { return { show: true, }; }, }; const wrapper = dualMount(fragApp); expect(wrapper.frag.html()).toBe('<app>Hello world</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ show: false }); expect(wrapper.frag.html()).toBe(outdent` <app> <!----> </app> `); wrapper.expectMatchingDom(); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe('<app>Hello world</app>'); wrapper.expectMatchingDom(); }); test('Parent multiple v-if', async () => { const FragComponent = { template: '<frag v-frag><div>Hello world {{ name }}</div></frag>', directives: { frag, }, props: ['name'], }; const usage = { template: ` <app> <frag-component name="A" key="a" v-if="show" /> <frag-component name="B" key="b" v-if="!show"/> <frag-component name="C" key="c" v-if="show" /> </app> `, components: { FragComponent, }, data() { return { show: true, }; }, }; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe(outdent` <app> <div>Hello world A</div> <!----> <div>Hello world C</div> </app> `); await wrapper.setData({ show: false }); expect(wrapper.frag.html()).toBe(outdent` <app> <!----> <div>Hello world B</div> <!----> </app> `); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe(outdent` <app> <div>Hello world A</div> <!----> <div>Hello world C</div> </app> `); }); test('Parent nested v-if empty', async () => { const ChildComp = { template: '<frag v-frag></frag>', directives: { frag, }, }; const ParentComp = { template: '<frag v-frag>Parent <child-comp v-if="shown" ref="child" /><div v-else>No Child</div></frag>', directives: { frag, }, components: { ChildComp, }, data() { return { shown: true, }; }, }; const attachTo = document.createElement('header'); document.body.append(attachTo); const $parent = mount(ParentComp, { attachTo }); expect(document.body.innerHTML).toBe('Parent <!---->'); await $parent.setData({ shown: false }); expect(document.body.innerHTML).toBe('Parent <div>No Child</div>'); await $parent.setData({ shown: true }); expect(document.body.innerHTML).toBe('Parent <!---->'); $parent.destroy(); attachTo.remove(); expect(document.body.innerHTML).toBe(''); }); test('Parent nested v-if text', async () => { const ChildComp = { template: '<frag v-frag>A</frag>', directives: { frag, }, }; const ParentComp = { template: '<frag v-frag><child-comp v-if="shown" /></frag>', directives: { frag, }, components: { ChildComp, }, data() { return { shown: false, }; }, }; const attachTo = document.createElement('header'); document.body.append(attachTo); const wrapper = mount(ParentComp, { attachTo }); expect(document.body.innerHTML).toBe('<!---->'); await wrapper.setData({ shown: true }); expect(document.body.innerHTML).toBe('A'); await wrapper.setData({ shown: false }); expect(document.body.innerHTML).toBe('<!---->'); await wrapper.setData({ shown: true }); expect(document.body.innerHTML).toBe('A'); wrapper.destroy(); attachTo.remove(); expect(document.body.innerHTML).toBe(''); }); test('Parent nested v-if', async () => { const ChildComp = { template: '<frag v-frag><div v-if="shown">Child</div></frag>', directives: { frag, }, data() { return { shown: true, }; }, }; const ParentComp = { template: '<frag v-frag>Parent <child-comp v-if="shown" ref="child" /></frag>', directives: { frag, }, components: { ChildComp, }, data() { return { shown: true, }; }, }; const $parent = mount(ParentComp, { attachTo: createMountTarget(), }); expect(document.body.innerHTML).toBe('Parent <div>Child</div>'); const $child = $parent.findComponent({ ref: 'child' }); await $parent.setData({ shown: false }); expect(document.body.innerHTML).toBe('Parent <!---->'); // Updating destroyed child should have no lingering effects on parent await $child.setData({ shown: true }); expect(document.body.innerHTML).toBe('Parent <!---->'); await $parent.setData({ shown: true }); expect(document.body.innerHTML).toBe('Parent <div>Child</div>'); $parent.destroy(); expect(document.body.innerHTML).toBe(''); }); // #17 test('child order change', async () => { const FragComponent = { template: '<frag v-frag>{{ num }}</frag>', directives: { frag, }, props: ['num'], }; const usage = { template: '<app><frag-component v-for="i in numbers" :key="i" :num="i" /></app>', components: { FragComponent, }, data() { return { numbers: [1, 2, 3], }; }, }; const spliceAndReverse = (vm: Vue & { numbers: number[] }) => { vm.numbers.splice(1, 1); vm.numbers.reverse(); }; const tpl = (content: number) => `<app>${content}</app>`; const wrapper = mount<Vue & { numbers: number[]; }>(usage); expect(wrapper.html()).toBe(tpl(123)); spliceAndReverse(wrapper.vm); await wrapper.vm.$nextTick(); expect(wrapper.html()).toBe(tpl(31)); spliceAndReverse(wrapper.vm); await wrapper.vm.$nextTick(); expect(wrapper.html()).toBe(tpl(3)); }); // #21 test('v-if slot', async () => { const FragComponent = { template: '<frag v-frag><slot /></frag>', directives: { frag, }, }; const usage = { template: ` <app class="wrapper"> <frag-component><div v-if="show">A</div></frag-component> </app> `, components: { FragComponent, }, data() { return { show: false, }; }, }; const empty = '<app class="wrapper">\n <!---->\n</app>'; const ifTrue = '<app class="wrapper">\n <div>A</div>\n</app>'; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe(empty); wrapper.expectMatchingDom(); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe(ifTrue); wrapper.expectMatchingDom(); await wrapper.setData({ show: false }); expect(wrapper.frag.html()).toBe(empty); wrapper.expectMatchingDom(); await wrapper.setData({ show: true }); expect(wrapper.frag.html()).toBe(ifTrue); wrapper.expectMatchingDom(); }); // #27 test('transition - swapping components', async () => { const ChildA = { template: '<frag v-frag>1a</frag>', directives: { frag, }, }; const ChildB = { template: '<div>1b</div>', }; const usage = { template: ` <app> <transition :css="false"> <child-a v-if="showA" /> <child-b v-else /> </transition> 2 </app> `, components: { ChildA, ChildB, }, data() { return { showA: true, }; }, }; const wrapper = mount(usage, { stubs: { // Disable the default transition stub transition: false, }, }); expect(wrapper.html()).toBe('<app>1a\n 2\n</app>'); await wrapper.setData({ showA: false }); expect(wrapper.html()).toBe('<app>\n <div>1b</div>\n 2\n</app>'); }); test('transition - frag to element', async () => { const usage = { data() { return { showA: true, }; }, template: ` <app> <transition :css="false"> <span v-if="showA" v-frag key="a">1a</span> <span v-else key="b">1b</span> </transition> 2 </app> `, directives: { frag, }, }; const wrapper = mount(usage, { stubs: { // Disable the default transition stub transition: false, }, }); expect(wrapper.html()).toBe('<app>1a\n 2\n</app>'); await wrapper.setData({ showA: false }); expect(wrapper.html()).toBe('<app><span>1b</span>\n 2\n</app>'); }); // #16 test('updating sibling node - update', async () => { const Child = { template: '<frag v-frag v-if="show">Child</frag>', props: ['show'], directives: { frag, }, }; const usage = { // Important that this is in one-line // When breaking into multiple lines, it inserts a textNode in between and breaks reproduction template: '<app><child :show="isVisible" /><span v-if="isVisible" /></app>', components: { Child, }, data() { return { isVisible: true, }; }, }; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe('<app>Child<span></span></app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisible: false }); expect(wrapper.frag.html()).toBe('<app>\n <!---->\n <!---->\n</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisible: true }); expect(wrapper.frag.html()).toBe('<app>Child<span></span></app>'); wrapper.expectMatchingDom(); }); // #16 2 test('updating sibling node - removal', async () => { const Child = { template: '<frag v-frag v-if="show">Child</frag>', props: ['show'], directives: { frag, }, }; const usage = { // Important that this is in one-line // When breaking into multiple lines, it inserts a textNode in between and breaks reproduction template: '<app><child :show="isVisible" /><child :show="isVisible" /></app>', components: { Child, }, data() { return { isVisible: false, }; }, }; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe('<app>\n <!---->\n <!---->\n</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisible: true }); expect(wrapper.frag.html()).toBe('<app>ChildChild</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisible: false }); expect(wrapper.frag.html()).toBe('<app>\n <!---->\n <!---->\n</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisible: true }); expect(wrapper.frag.html()).toBe('<app>ChildChild</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisible: false }); expect(wrapper.frag.html()).toBe('<app>\n <!---->\n <!---->\n</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisible: true }); expect(wrapper.frag.html()).toBe('<app>ChildChild</app>'); wrapper.expectMatchingDom(); }); // #16 3 test('updating sibling node - removal - no nextSibling', async () => { const Child = { template: '<frag v-frag v-if="show">Child</frag>', props: ['show'], directives: { frag, }, }; const usage = { // Important that this is in one-line // When breaking into multiple lines, it inserts a textNode in between and breaks reproduction template: '<app><span v-if="isVisible" /><child :show="isVisible" /><span v-if="isVisible" /></app>', components: { Child, }, data() { return { isVisible: true, }; }, }; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe('<app><span></span>Child<span></span></app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisible: false }); expect(wrapper.frag.html()).toBe('<app>\n <!---->\n <!---->\n <!---->\n</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisible: true }); expect(wrapper.frag.html()).toBe('<app><span></span>Child<span></span></app>'); wrapper.expectMatchingDom(); }); // #16 4 test('updating sibling node - insertion - previous non-frag sibling', async () => { const Child = { template: '<frag v-frag v-if="show">Child</frag>', props: ['show'], directives: { frag, }, }; const usage = { // Important that this is in one-line // When breaking into multiple lines, it inserts a textNode in between and breaks reproduction template: '<app><child :show="isVisibleA" /><child :show="isVisibleB" /></app>', components: { Child, }, data() { return { isVisibleA: false, isVisibleB: true, }; }, }; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe('<app>\n <!---->Child</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisibleA: true }); expect(wrapper.frag.html()).toBe('<app>ChildChild</app>'); wrapper.expectMatchingDom(); }); // #16 5 test('updating sibling node - insertion - placeholder before frag-child should be patched', async () => { const Child = { template: '<frag v-frag v-if="show">Child</frag>', props: ['show'], directives: { frag, }, }; const usage = { // Important that this is in one-line // When breaking into multiple lines, it inserts a textNode in between and breaks reproduction template: '<app><child :show="isVisibleA" /><child :show="isVisibleB" /></app>', components: { Child, }, data() { return { isVisibleA: true, isVisibleB: true, }; }, }; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe('<app>ChildChild</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisibleA: false }); expect(wrapper.frag.html()).toBe('<app>\n <!---->Child</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisibleA: true }); expect(wrapper.frag.html()).toBe('<app>ChildChild</app>'); wrapper.expectMatchingDom(); }); // #16 6 test('updating sibling node - insertion', async () => { const Child = { template: '<frag v-frag v-if="show">Child</frag>', props: ['show'], directives: { frag, }, }; const usage = { // Important that this is in one-line // When breaking into multiple lines, it inserts a textNode in between and breaks reproduction template: '<app><child :show="isVisibleA" /><child :show="isVisibleB" /></app>', components: { Child, }, data() { return { isVisibleA: true, isVisibleB: true, }; }, }; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe('<app>ChildChild</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisibleB: false }); expect(wrapper.frag.html()).toBe('<app>Child\n <!---->\n</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisibleA: false }); expect(wrapper.frag.html()).toBe('<app>\n <!---->\n <!---->\n</app>'); wrapper.expectMatchingDom(); await wrapper.setData({ isVisibleA: true }); expect(wrapper.frag.html()).toBe('<app>Child\n <!---->\n</app>'); wrapper.expectMatchingDom(); }); // #48 test('nested fragments', async () => { const Fragment = { directives: { frag }, template: '<frag v-frag><slot /></frag>', }; const usage = { template: ` <app> <component :is="fragment"> <Fragment> <div :key="id">{{ id }}</div> </Fragment> </component> </app> `, components: { Fragment, Fragment2: Fragment, }, data() { return { id: 1, fragment: 'Fragment', }; }, }; const wrapper = dualMount(usage); expect(wrapper.frag.html()).toBe(outdent` <app> <div>1</div> </app> `); wrapper.expectMatchingDom(); await wrapper.setData({ id: 2 }); expect(wrapper.frag.html()).toBe(outdent` <app> <div>2</div> </app> `); wrapper.expectMatchingDom(); await wrapper.setData({ fragment: 'Fragment2' }); expect(wrapper.frag.html()).toBe(outdent` <app> <div>2</div> </app> `); wrapper.expectMatchingDom(); });
the_stack
import Random from "./random"; import Room from "./room"; import TILES, { DebugTileMap } from "./tiles"; import { debugMap, debugHtmlMap, DebugHtmlConfig, DebugConsoleConfig } from "./debug"; import create2DArray from "./create-2d-array"; import Point from "./point"; import { isOdd, isEven } from "./math"; type DimensionConfig = { min: number; max: number; onlyOdd?: boolean; onlyEven?: boolean }; type DimensionConfigRequired = Required<DimensionConfig>; type RoomConfig = { width: DimensionConfig; height: DimensionConfig; maxArea?: number; maxRooms?: number; }; export type DungeonConfig = { width: number; height: number; randomSeed?: string; doorPadding?: number; rooms: RoomConfig; }; export default class Dungeon { public height: number; public width: number; public tiles: TILES[][]; public rooms: Room[] = []; private doorPadding: number; private r: Random; // 2D grid matching map dimensions where every element contains an array of all the rooms in // that location. public roomGrid: Room[][][] = []; private maxRooms: number; private maxRoomArea: number; private roomWidthConfig: DimensionConfigRequired; private roomHeightConfig: DimensionConfigRequired; private randomSeed?: string; constructor(config: DungeonConfig) { this.width = config.width; this.height = config.height; this.doorPadding = config.doorPadding ?? 1; this.rooms = []; this.randomSeed = config.randomSeed; this.r = new Random(this.randomSeed); const rooms = config.rooms; const roomWidth = rooms.width; const roomHeight = rooms.height; const maxPossibleRoomArea = roomWidth.max * roomHeight.max; const minPossibleRoomArea = roomWidth.min * roomHeight.min; const maxPossibleRooms = Math.floor((this.width * this.height) / minPossibleRoomArea); this.roomWidthConfig = { min: roomWidth.min, max: roomWidth.max, onlyOdd: roomWidth.onlyOdd ?? false, onlyEven: roomWidth.onlyEven ?? false }; this.roomHeightConfig = { min: roomHeight.min, max: roomHeight.max, onlyOdd: roomHeight.onlyOdd ?? false, onlyEven: roomHeight.onlyEven ?? false }; this.maxRooms = rooms.maxRooms ?? maxPossibleRooms; this.maxRoomArea = rooms.maxArea ?? maxPossibleRoomArea; this.adjustDimensionConfigForParity(this.roomWidthConfig); this.adjustDimensionConfigForParity(this.roomHeightConfig); this.checkDimensionConfig(this.roomWidthConfig); this.checkDimensionConfig(this.roomHeightConfig); // Validate the room width and height settings. if (this.roomWidthConfig.max > this.width) { throw new Error("Room max width cannot exceed dungeon width."); } if (this.roomHeightConfig.max > this.height) { throw new Error("Room max height cannot exceed dungeon height."); } // Validate the max area based on min dimensions. if (this.maxRoomArea < minPossibleRoomArea) { throw new Error("The minimum dimensions specified exceeds the given maxArea."); } this.generate(); this.tiles = this.getTiles(); } /** * Adjust the given dimension config for parity settings (onlyOdd, onlyEven) so that min/max are * adjusted to reflect actual possible values. * @param dimensionConfig */ private adjustDimensionConfigForParity(dimensionConfig: DimensionConfigRequired) { if (dimensionConfig.onlyOdd) { if (isEven(dimensionConfig.min)) { dimensionConfig.min++; console.log("Dungeon: warning, min dimension adjusted to match onlyOdd setting."); } if (isEven(dimensionConfig.max)) { dimensionConfig.max--; console.log("Dungeon: warning, max dimension adjusted to match onlyOdd setting."); } } else if (dimensionConfig.onlyEven) { if (isOdd(dimensionConfig.min)) { dimensionConfig.min++; console.log("Dungeon: warning, min dimension adjusted to match onlyEven setting."); } if (isOdd(dimensionConfig.max)) { dimensionConfig.max--; console.log("Dungeon: warning, max dimension adjusted to match onlyEven setting."); } } } private checkDimensionConfig(dimensionConfig: DimensionConfigRequired) { const { max, min, onlyEven, onlyOdd } = dimensionConfig; if (onlyEven && onlyOdd) { throw new Error("Cannot use both onlyEven and onlyOdd in room's width/height config."); } if (max < min) { throw new Error("Room width and height max must be >= min."); } if (min < 3) { throw new Error("Room width and height must be >= 3."); } } public getConfig(): DungeonConfig { return { width: this.width, height: this.height, doorPadding: this.doorPadding, randomSeed: this.randomSeed, rooms: { width: this.roomWidthConfig, height: this.roomHeightConfig, maxArea: this.maxRoomArea, maxRooms: this.maxRooms } }; } public drawToConsole(config: DebugConsoleConfig) { debugMap(this, config); } public drawToHtml(config: DebugHtmlConfig) { return debugHtmlMap(this, config); } public getMappedTiles(tileMapping: DebugTileMap = {}) { tileMapping = Object.assign({}, { empty: 0, wall: 1, floor: 2, door: 3 }, tileMapping); return this.tiles.map(row => row.map(tile => { if (tile === TILES.EMPTY) return tileMapping.empty; else if (tile === TILES.WALL) return tileMapping.wall; else if (tile === TILES.FLOOR) return tileMapping.floor; else if (tile === TILES.DOOR) return tileMapping.door; }) ); } public getCenter(): Point { return { x: Math.floor(this.width / 2), y: Math.floor(this.height / 2) }; } public generate() { this.rooms = []; this.roomGrid = []; for (let y = 0; y < this.height; y++) { this.roomGrid.push([]); for (let x = 0; x < this.width; x++) { this.roomGrid[y].push([]); } } // Seed the map with a starting randomly sized room in the center of the map. const mapCenter = this.getCenter(); const room = this.createRandomRoom(); room.setPosition( mapCenter.x - Math.floor(room.width / 2), mapCenter.y - Math.floor(room.height / 2) ); this.addRoom(room); // Continue generating rooms until we hit our cap or have hit our maximum iterations (generally // due to not being able to fit any more rooms in the map). let attempts = 0; const maxAttempts = this.maxRooms * 5; while (this.rooms.length < this.maxRooms && attempts < maxAttempts) { this.generateRoom(); attempts++; } } public hasRoomAt(x: number, y: number) { return x < 0 || y < 0 || x >= this.width || y >= this.height || this.roomGrid[y][x].length > 0; } public getRoomAt(x: number, y: number): Room | null { if (this.hasRoomAt(x, y)) { // Assumes 1 room per tile, which is valid for now return this.roomGrid[y][x][0]; } else { return null; } } /** * Attempt to add a room and return true/false based on whether it was successful. * @param room */ private addRoom(room: Room): Boolean { if (!this.canFitRoom(room)) return false; this.rooms.push(room); // Update all tiles in the roomGrid to indicate that this room is sitting on them. for (let y = room.top; y <= room.bottom; y++) { for (let x = room.left; x <= room.right; x++) { this.roomGrid[y][x].push(room); } } return true; } private canFitRoom(room: Room) { // Make sure the room fits inside the dungeon. if (room.x < 0 || room.right > this.width - 1) return false; if (room.y < 0 || room.bottom > this.height - 1) return false; // Make sure this room doesn't intersect any existing rooms. for (let i = 0; i < this.rooms.length; i++) { if (room.overlaps(this.rooms[i])) return false; } return true; } private createRandomRoom(): Room { let width = 0; let height = 0; let area = 0; // Find width and height using min/max sizes while keeping under the maximum area. const { roomWidthConfig, roomHeightConfig } = this; do { width = this.r.randomInteger(roomWidthConfig.min, roomWidthConfig.max, { onlyEven: roomWidthConfig.onlyEven, onlyOdd: roomWidthConfig.onlyOdd }); height = this.r.randomInteger(roomHeightConfig.min, roomHeightConfig.max, { onlyEven: roomHeightConfig.onlyEven, onlyOdd: roomHeightConfig.onlyOdd }); area = width * height; } while (area > this.maxRoomArea); return new Room(width, height); } private generateRoom() { const room = this.createRandomRoom(); // Only allow 150 tries at placing the room let i = 150; while (i > 0) { // Attempt to find another room to attach this one to const result = this.findRoomAttachment(room); room.setPosition(result.x, result.y); // Try to add it. If successful, add the door between the rooms and break the loop. if (this.addRoom(room)) { const [door1, door2] = this.findNewDoorLocation(room, result.target); this.addDoor(door1); this.addDoor(door2); break; } i -= 1; } } public getTiles() { const tiles = create2DArray<TILES>(this.width, this.height, TILES.EMPTY); this.rooms.forEach(room => { room.forEachTile((point, tile) => { tiles[room.y + point.y][room.x + point.x] = tile; }); }); return tiles; } private getPotentiallyTouchingRooms(room: Room) { const touchingRooms: Room[] = []; // function that checks the list of rooms at a point in our grid for any potential touching // rooms const checkRoomList = (x: number, y: number) => { const r = this.roomGrid[y][x]; for (let i = 0; i < r.length; i++) { // make sure this room isn't the one we're searching around and that it isn't already in the // list if (r[i] != room && touchingRooms.indexOf(r[i]) === -1) { // make sure this isn't a corner of the room (doors can't go into corners) const lx = x - r[i].x; const ly = y - r[i].y; if ((lx > 0 && lx < r[i].width - 1) || (ly > 0 && ly < r[i].height - 1)) { touchingRooms.push(r[i]); } } } }; // iterate the north and south walls, looking for other rooms in those tile locations for (let x = room.x + 1; x < room.x + room.width - 1; x++) { checkRoomList(x, room.y); checkRoomList(x, room.y + room.height - 1); } // iterate the west and east walls, looking for other rooms in those tile locations for (let y = room.y + 1; y < room.y + room.height - 1; y++) { checkRoomList(room.x, y); checkRoomList(room.x + room.width - 1, y); } return touchingRooms; } private findNewDoorLocation(room1: Room, room2: Room): [Point, Point] { const door1 = { x: -1, y: -1 }; const door2 = { x: -1, y: -1 }; if (room1.y === room2.y - room1.height) { // North door1.x = door2.x = this.r.randomInteger( Math.floor(Math.max(room2.left, room1.left) + this.doorPadding), Math.floor(Math.min(room2.right, room1.right) - this.doorPadding) ); door1.y = room1.y + room1.height - 1; door2.y = room2.y; } else if (room1.x == room2.x - room1.width) { // West door1.x = room1.x + room1.width - 1; door2.x = room2.x; door1.y = door2.y = this.r.randomInteger( Math.floor(Math.max(room2.top, room1.top) + this.doorPadding), Math.floor(Math.min(room2.bottom, room1.bottom) - this.doorPadding) ); } else if (room1.x == room2.x + room2.width) { // East door1.x = room1.x; door2.x = room2.x + room2.width - 1; door1.y = door2.y = this.r.randomInteger( Math.floor(Math.max(room2.top, room1.top) + this.doorPadding), Math.floor(Math.min(room2.bottom, room1.bottom) - this.doorPadding) ); } else if (room1.y == room2.y + room2.height) { // South door1.x = door2.x = this.r.randomInteger( Math.floor(Math.max(room2.left, room1.left) + this.doorPadding), Math.floor(Math.min(room2.right, room1.right) - this.doorPadding) ); door1.y = room1.y; door2.y = room2.y + room2.height - 1; } return [door1, door2]; } private findRoomAttachment(room: Room) { const r = this.r.randomPick(this.rooms); let x = 0; let y = 0; const pad = 2 * this.doorPadding; // 2x padding to account for the padding both rooms need // Randomly position this room on one of the sides of the random room. switch (this.r.randomInteger(0, 3)) { // north case 0: // x = r.left - (room.width - 1) would have rooms sharing exactly 1x tile x = this.r.randomInteger(r.left - (room.width - 1) + pad, r.right - pad); y = r.top - room.height; break; // west case 1: x = r.left - room.width; y = this.r.randomInteger(r.top - (room.height - 1) + pad, r.bottom - pad); break; // east case 2: x = r.right + 1; y = this.r.randomInteger(r.top - (room.height - 1) + pad, r.bottom - pad); break; // south case 3: x = this.r.randomInteger(r.left - (room.width - 1) + pad, r.right - pad); y = r.bottom + 1; break; } // Return the position for this new room and the target room return { x: x, y: y, target: r }; } private addDoor(doorPos: Point) { // Get all the rooms at the location of the door const rooms = this.roomGrid[doorPos.y][doorPos.x]; rooms.forEach(room => { room.setTileAt(doorPos.x - room.x, doorPos.y - room.y, TILES.DOOR); }); } }
the_stack
import { Production } from '../production'; import { WorldInterface } from './worldInterface'; import { Unit } from '../units/unit'; import { GameModel } from '../gameModel'; import { BuyAction, BuyAndUnlockAction, UpAction, UpHire, UpSpecial, Research } from '../units/action'; import { Cost } from '../cost'; import { TypeList } from '../typeList'; import { World } from '../world'; export class BaseWorld implements WorldInterface { // Materials food: Unit crystal: Unit soil: Unit science: Unit fungus: Unit wood: Unit sand: Unit nectar: Unit honey: Unit ice: Unit listMaterial = Array<Unit>() // Hunting hunter: Unit advancedHunter: Unit // Tier 1 geologist: Unit carpenter: Unit farmer: Unit lumberjack: Unit level1 = Array<Unit>() // Tier 2 composterAnt: Unit refineryAnt: Unit laserAnt: Unit hydroAnt: Unit planterAnt: Unit level2 = Array<Unit>() jobMaterial: Unit[][] listJobs = Array<Unit>() baseFood = new Decimal(800) price2 = new Decimal(100) // Prices specialProduction = new Decimal(100) specialCost = new Decimal(-40) specialFood = new Decimal(1E7) specialRes2 = new Decimal(1E4) prestigeFood = new Decimal(1E10) prestigeOther1 = new Decimal(1E6) prestigeOther2 = new Decimal(1E5) prestigeUnit = new Decimal(200) // Generators littleAnt: Unit queenAnt: Unit nestAnt: Unit list = Array<Unit>() constructor(public game: GameModel) { } declareStuff() { this.declareMaterials() this.declareGenerators() this.declareJobs() this.game.lists.push(new TypeList("Material", this.listMaterial)) this.game.lists.push(new TypeList("Jobs", this.level1)) this.game.lists.push(new TypeList("Advanced Jobs", this.level2)) this.game.lists.push(new TypeList("Ants", this.list)) } initStuff() { this.initGenerators() this.initJobs() } declareMaterials() { this.food = new Unit(this.game, "food", "Food", "Food is used to support almost all your units.") this.food.unlocked = true this.listMaterial.push(this.food) this.crystal = new Unit(this.game, "cri", "Crystal", "Crystals are needed to get science.") this.listMaterial.push(this.crystal) this.soil = new Unit(this.game, "soil", "Soil", "Soil is used to make nests.") this.listMaterial.push(this.soil) this.science = new Unit(this.game, "sci", "Science", "Science is used to improve and unlock stuff.") this.listMaterial.push(this.science) this.fungus = new Unit(this.game, "fun", "Fungus", "Fungus is a source of food.") this.listMaterial.push(this.fungus) this.wood = new Unit(this.game, "wood", "Wood", "Wood is used to make better nests and machinery.") this.listMaterial.push(this.wood) this.sand = new Unit(this.game, "sand", "Sand", "Sand can be used to make crystals.") this.listMaterial.push(this.sand) this.nectar = new Unit(this.game, "nectar", "Nectar", "Nectar is used to make honey.") this.listMaterial.push(this.nectar) this.honey = new Unit(this.game, "honey", "Honey", "Honey is the main resource for bees.") this.listMaterial.push(this.honey) this.ice = new Unit(this.game, "ice", "Ice", "Ice") this.listMaterial.push(this.ice) // Fungus this.fungus.actions.push(new UpSpecial(this.game, this.fungus)) } declareGenerators() { this.littleAnt = new Unit(this.game, "G1", "Ant", "Ants are the lowest class of worker. They continuously gather food.") this.queenAnt = new Unit(this.game, "G2", "Queen", "Queen produces ants.") this.nestAnt = new Unit(this.game, "G3", "Nest", "Nest produces queens.") } declareJobs() { this.geologist = new Unit(this.game, "geo", "Geologist", "Geologists yield crystals.") // this.geologist.types = [Type.Ant, Type.Mining] this.listJobs.push(this.geologist) this.carpenter = new Unit(this.game, "car", "Carpenter", "carpenters yield soils.") // this.carpenter.types = [Type.Ant, Type.SoilG] this.listJobs.push(this.carpenter) this.farmer = new Unit(this.game, "far", "Farmer", "Farmers yield fungus.") // this.farmer.types = [Type.Ant, Type.Farmer] this.listJobs.push(this.farmer) this.lumberjack = new Unit(this.game, "lum", "Lumberjack", "Lumberjacks yield woods.") // this.lumberjack.types = [Type.Ant, Type.WoodG] this.listJobs.push(this.lumberjack) this.composterAnt = new Unit(this.game, "com", "Composter Ant", "Transform wood into soil.") this.refineryAnt = new Unit(this.game, "ref", "Refinery Ant", "Transform soil into sand.") this.laserAnt = new Unit(this.game, "las", "Laser Ant", "Transform sand into crystal.") this.hydroAnt = new Unit(this.game, "hydroFarmer", "Hydroponic Ant", "Transform crystal into fungus.") this.planterAnt = new Unit(this.game, "planterAnt", "Planter Ant", "Transform fungus into wood.") this.hunter = new Unit(this.game, "hunter", "Hunter", "Hunter yield food.") this.advancedHunter = new Unit(this.game, "advhunter", "Advanced Hunter", "Advanced Hunter yield food.") this.level1 = [this.geologist, this.farmer, this.carpenter, this.lumberjack, this.hunter, this.advancedHunter] } initGenerators() { this.list.push(this.littleAnt, this.queenAnt, this.nestAnt) // this.list.forEach(ant => ant.types = [Type.Ant, Type.Generator]) this.littleAnt.unlocked = true this.littleAnt.actions.push(new BuyAndUnlockAction(this.game, this.littleAnt, [new Cost(this.food, new Decimal(15), new Decimal(this.game.buyExp))], [this.queenAnt] )) this.queenAnt.actions.push(new BuyAndUnlockAction(this.game, this.queenAnt, [ new Cost(this.food, new Decimal(8E2), new Decimal(this.game.buyExp)), new Cost(this.littleAnt, new Decimal(20), new Decimal(this.game.buyExpUnit)) ], [this.nestAnt, this.geologist] )) this.nestAnt.actions.push(new BuyAction(this.game, this.nestAnt, [ new Cost(this.food, this.prestigeFood, new Decimal(this.game.buyExp)), new Cost(this.soil, this.prestigeOther1, new Decimal(this.game.buyExp)), new Cost(this.wood, this.prestigeOther2, new Decimal(this.game.buyExp)), new Cost(this.queenAnt, this.prestigeUnit, new Decimal(this.game.buyExpUnit)) ], )) for (let i = 0; i < this.list.length - 1; i++) this.list[i].addProductor(new Production(this.list[i + 1])) for (let i = 0; i < this.list.length; i++) { this.list[i].actions.push(new UpAction(this.game, this.list[i], [new Cost(this.science, new Decimal(new Decimal(100).times(Decimal.pow(10, new Decimal(i)))), this.game.upgradeScienceExp)])) this.list[i].actions.push(new UpHire(this.game, this.list[i], [new Cost(this.science, new Decimal(new Decimal(100).times(Decimal.pow(10, new Decimal(i)))), this.game.upgradeScienceHireExp)])) } this.list = this.list.reverse() } initJobs() { // Prices && Production this.food.addProductor(new Production(this.littleAnt, new Decimal(1))) this.food.addProductor(new Production(this.fungus, new Decimal(2))) this.fungus.addProductor(new Production(this.farmer)) this.soil.addProductor(new Production(this.farmer, new Decimal(-1))) this.crystal.addProductor(new Production(this.geologist, new Decimal(0.2))) this.soil.addProductor(new Production(this.carpenter)) this.wood.addProductor(new Production(this.lumberjack)) this.food.addProductor(new Production(this.hunter, new Decimal(50))) this.wood.addProductor(new Production(this.hunter, new Decimal(-2))) this.food.addProductor(new Production(this.advancedHunter, new Decimal(250))) this.wood.addProductor(new Production(this.advancedHunter, new Decimal(-10))) this.crystal.addProductor(new Production(this.advancedHunter, new Decimal(-5))) // Geologist this.geologist.actions.push(new BuyAndUnlockAction(this.game, this.geologist, [ new Cost(this.food, this.baseFood, this.game.buyExp), new Cost(this.littleAnt, new Decimal(1), this.game.buyExpUnit) ], [this.crystal, this.game.science.student] )) // Carpenter this.carpenter.actions.push(new BuyAndUnlockAction(this.game, this.carpenter, [ new Cost(this.food, this.baseFood, new Decimal(this.game.buyExp)), new Cost(this.littleAnt, new Decimal(1), new Decimal(this.game.buyExpUnit)) ], [this.science] )) // Lumberjack this.lumberjack.actions.push(new BuyAndUnlockAction(this.game, this.lumberjack, [ new Cost(this.food, this.baseFood, new Decimal(this.game.buyExp)), new Cost(this.soil, this.price2, new Decimal(this.game.buyExp)), new Cost(this.littleAnt, new Decimal(1), new Decimal(this.game.buyExpUnit)), ], [this.wood] )) // Farmer this.farmer.actions.push(new BuyAndUnlockAction(this.game, this.farmer, [ new Cost(this.food, this.baseFood, new Decimal(this.game.buyExp)), new Cost(this.soil, this.price2, new Decimal(this.game.buyExp)), new Cost(this.littleAnt, new Decimal(1), new Decimal(this.game.buyExpUnit)), ], [this.fungus] )) // Hunter this.hunter.actions.push(new BuyAction(this.game, this.hunter, [ new Cost(this.food, this.baseFood.div(1.5), new Decimal(this.game.buyExp)), new Cost(this.wood, this.price2.div(1.5), new Decimal(this.game.buyExp)), new Cost(this.littleAnt, new Decimal(1), new Decimal(this.game.buyExpUnit)), ] )) // Hunter 2 this.advancedHunter.actions.push(new BuyAction(this.game, this.advancedHunter, [ new Cost(this.food, this.baseFood, new Decimal(this.game.buyExp)), new Cost(this.wood, this.price2, new Decimal(this.game.buyExp)), new Cost(this.crystal, this.price2.div(1.5), new Decimal(this.game.buyExp)), new Cost(this.littleAnt, new Decimal(1), new Decimal(this.game.buyExpUnit)), ] )) this.level1.forEach(l => { l.actions.push(new UpAction(this.game, l, [new Cost(this.science, this.game.scienceCost2, this.game.upgradeScienceExp)])) l.actions.push(new UpHire(this.game, l, [new Cost(this.science, this.game.scienceCost2, this.game.upgradeScienceHireExp)])) }) // // Special // // Composter // this.composterAnt.types = [Type.Ant] this.level2.push(this.composterAnt) this.composterAnt.actions.push(new BuyAction(this.game, this.composterAnt, [ new Cost(this.food, this.specialFood, this.game.buyExp), new Cost(this.wood, this.specialRes2, this.game.buyExp), new Cost(this.littleAnt, new Decimal(1), this.game.buyExpUnit) ] )) this.soil.addProductor(new Production(this.composterAnt, this.specialProduction)) this.wood.addProductor(new Production(this.composterAnt, this.specialCost)) // Refinery // this.refineryAnt.types = [Type.Ant] this.level2.push(this.refineryAnt) this.refineryAnt.actions.push(new BuyAction(this.game, this.refineryAnt, [ new Cost(this.food, this.specialFood, this.game.buyExp), new Cost(this.soil, this.specialRes2, this.game.buyExp), new Cost(this.littleAnt, new Decimal(1), this.game.buyExpUnit) ] )) this.sand.addProductor(new Production(this.refineryAnt, this.specialProduction)) this.soil.addProductor(new Production(this.refineryAnt, this.specialCost)) // Laser // this.laserAnt.types = [Type.Ant] this.level2.push(this.laserAnt) this.laserAnt.actions.push(new BuyAction(this.game, this.laserAnt, [ new Cost(this.food, this.specialFood, this.game.buyExp), new Cost(this.sand, this.specialRes2, this.game.buyExp), new Cost(this.littleAnt, new Decimal(1), this.game.buyExpUnit) ] )) this.crystal.addProductor(new Production(this.laserAnt, this.specialProduction)) this.sand.addProductor(new Production(this.laserAnt, this.specialCost)) // Hydro // this.hydroAnt.types = [Type.Ant] this.level2.push(this.hydroAnt) this.hydroAnt.actions.push(new BuyAction(this.game, this.hydroAnt, [ new Cost(this.food, this.specialFood, this.game.buyExp), new Cost(this.crystal, this.specialRes2, this.game.buyExp), new Cost(this.littleAnt, new Decimal(1), this.game.buyExpUnit) ] )) this.fungus.addProductor(new Production(this.hydroAnt, this.specialProduction)) this.crystal.addProductor(new Production(this.hydroAnt, this.specialCost)) // Planter // this.planterAnt.types = [Type.Ant] this.level2.push(this.planterAnt) this.planterAnt.actions.push(new BuyAction(this.game, this.planterAnt, [ new Cost(this.food, this.specialFood, this.game.buyExp), new Cost(this.fungus, this.specialRes2, this.game.buyExp), new Cost(this.littleAnt, new Decimal(1), this.game.buyExpUnit) ] )) this.wood.addProductor(new Production(this.planterAnt, this.specialProduction)) this.fungus.addProductor(new Production(this.planterAnt, this.specialCost)) this.level2.forEach(l => { l.actions.push(new UpAction(this.game, l, [new Cost(this.science, this.game.scienceCost3, this.game.upgradeScienceExp)])) l.actions.push(new UpHire(this.game, l, [new Cost(this.science, this.game.scienceCost3, this.game.upgradeScienceHireExp)])) }) } addWorld() { World.worldTypes.push( new World(this.game, "Park", "", [], [], [] ), new World(this.game, "Mine", "A mine", [this.game.machines.mine, this.game.engineers.mineEnginer], [ [this.game.baseWorld.crystal, new Decimal(1.2)], [this.game.baseWorld.wood, new Decimal(0.8)], [this.game.baseWorld.fungus, new Decimal(0.8)] ], [] ) ) World.worldPrefix.push( new World(this.game, "", "", [], [], []), new World(this.game, "Hot", "", [], [[this.game.baseWorld.food, new Decimal(2)]], [], [], [], [], new Decimal(2) ), new World(this.game, "Arid", "", [], [[this.game.baseWorld.fungus, new Decimal(0.5)]], [], [], [], [], new Decimal(3.2) ), new World(this.game, "Wooded", "", [this.game.engineers.woodEnginer, this.game.machines.loggingMachine], [[this.game.baseWorld.wood, new Decimal(2)]], [], [], [], [], new Decimal(2.5) ), new World(this.game, "Crystallized", "", [this.game.machines.mine, this.game.engineers.mineEnginer], [ [this.game.baseWorld.crystal, new Decimal(1.5)], [this.game.baseWorld.food, new Decimal(0.4)], [this.game.baseWorld.fungus, new Decimal(0.4)] ], [] ), new World(this.game, "Dying", "", [], [ [this.food, new Decimal(0.5)], [this.fungus, new Decimal(0.5)], [this.wood, new Decimal(0.5)], [this.honey, new Decimal(0.5)], [this.nectar, new Decimal(0.5)] ], [], [], [], [], new Decimal(3.2) ), new World(this.game, "Rainy", "", [], [ [this.wood, new Decimal(1.5)], [this.fungus, new Decimal(1.5)] ], [], [], [], [], new Decimal(2.5) ), new World(this.game, "Foggy", "", [], [ [this.wood, new Decimal(0.7)], [this.fungus, new Decimal(0.7)] ], [], [], [], [], new Decimal(3.2) ), new World(this.game, "Technological", "", [], [ [this.science, new Decimal(1.5)] ], [], [], [], [], new Decimal(2.5) ), new World(this.game, "Starving", "", [], [ [this.food, new Decimal(0.3)] ], [], [], [], [], new Decimal(3.2) ), ) World.worldSuffix.push( new World(this.game, "", "", [], [], []), new World(this.game, "of Fungus", "", [], [[this.game.baseWorld.fungus, new Decimal(2)]], [new Cost(this.game.baseWorld.fungus, new Decimal(1E7))], [], [], [], new Decimal(3) ), new World(this.game, "of Ant", "", [], [], [], [[this.littleAnt, new Decimal(2)]], [], [], new Decimal(2) ), new World(this.game, "of Scientist", "", [], [], [], [[this.game.science.scientist, new Decimal(2)]], [], [], new Decimal(2) ), new World(this.game, "of Farming", "", [], [], [], [[this.farmer, new Decimal(2)]], [], [], new Decimal(2) ), new World(this.game, "of Crystal", "", [this.game.machines.mine, this.game.engineers.mineEnginer], [[this.crystal, new Decimal(2)]], [], [], [], [], new Decimal(2) ), ) } }
the_stack
import areShallowEqual from 'are-shallow-equal'; import * as isPrimitive from 'is-primitive'; import {record} from 'proxy-watcher'; import {EMPTY_ARRAY, COMPARATOR_FALSE, SELECTOR_IDENTITY} from './consts'; import ChangesSubscribers from './changes_subscribers'; import Errors from './errors'; import Scheduler from './scheduler'; import Utils from './utils'; import {Primitive, Disposer, Listener} from './types'; /* ON CHANGE */ function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, S9 extends object> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9], listener: Listener<[S1, S2, S3, S4, S5, S6, S7, S8, S9]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8], listener: Listener<[S1, S2, S3, S4, S5, S6, S7, S8]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object> ( stores: [S1, S2, S3, S4, S5, S6, S7], listener: Listener<[S1, S2, S3, S4, S5, S6, S7]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object> ( stores: [S1, S2, S3, S4, S5, S6], listener: Listener<[S1, S2, S3, S4, S5, S6]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object> ( stores: [S1, S2, S3, S4, S5], listener: Listener<[S1, S2, S3, S4, S5]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object> ( stores: [S1, S2, S3, S4], listener: Listener<[S1, S2, S3, S4]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object> ( stores: [S1, S2, S3], listener: Listener<[S1, S2, S3]> ): Disposer; function onChange<S1 extends object, S2 extends object> ( stores: [S1, S2], listener: Listener<[S1, S2]> ): Disposer; function onChange<S1 extends object> ( store: S1, listener: Listener<[S1]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, S9 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9] ) => R, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7, S8] ) => R, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7] ) => R, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6], selector: ( ...stores: [S1, S2, S3, S4, S5, S6] ) => R, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, R> ( stores: [S1, S2, S3, S4, S5], selector: ( ...stores: [S1, S2, S3, S4, S5] ) => R, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, R> ( stores: [S1, S2, S3, S4], selector: ( ...stores: [S1, S2, S3, S4] ) => R, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, R> ( stores: [S1, S2, S3], selector: ( ...stores: [S1, S2, S3] ) => R, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, R> ( stores: [S1, S2], selector: ( ...stores: [S1, S2] ) => R, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, R> ( store: S1, selector: ( store: S1 ) => R, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, S9 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7, S8] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6], selector: ( ...stores: [S1, S2, S3, S4, S5, S6] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, R> ( stores: [S1, S2, S3, S4, S5], selector: ( ...stores: [S1, S2, S3, S4, S5] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, S4 extends object, R> ( stores: [S1, S2, S3, S4], selector: ( ...stores: [S1, S2, S3, S4] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, S3 extends object, R> ( stores: [S1, S2, S3], selector: ( ...stores: [S1, S2, S3] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, S2 extends object, R> ( stores: [S1, S2], selector: ( ...stores: [S1, S2] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener: Listener<[R]> ): Disposer; function onChange<S1 extends object, R> ( store: S1, selector: ( store: S1 ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener: Listener<[R]> ): Disposer; function onChange<Store extends object, R> ( store: Store | Store[], selector: (( store: Store ) => R) | (( ...stores: Store[] ) => R), comparator?: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, listener?: Listener<[R] | Store[]> ): Disposer { if ( !listener && !comparator ) return onChange ( store, SELECTOR_IDENTITY, COMPARATOR_FALSE, selector ); if ( !listener ) return onChange ( store, selector, COMPARATOR_FALSE, comparator as any ); //TSC const stores = Utils.isStores ( store ) ? store : [store], storesNr = stores.length; if ( !storesNr ) throw Errors.storesEmpty (); const disposers: Disposer[] = []; let rootsChangeAllCache: Map<Store, string[]> = new Map (), dataPrev = selector.apply ( undefined, stores ), // Fetching initial data comparatorDataPrev = dataPrev; const handler = () => { if ( selector === SELECTOR_IDENTITY ) return listener.apply ( undefined, stores ); let data; const rootsChangeAll = rootsChangeAllCache, rootsGetAll = record ( stores, () => data = selector.apply ( undefined, stores ) ) as unknown as Map<any, string[]>; //TSC rootsChangeAllCache = new Map (); if ( isPrimitive ( data ) || isPrimitive ( dataPrev ) ) { // Primitives involved if ( Object.is ( data, dataPrev ) ) return; // The selected primitive didn't actually change dataPrev = data; return listener ( data ); } comparatorDataPrev = dataPrev; dataPrev = data; const isDataIdentity = ( storesNr === 1 ) ? data === stores[0] : areShallowEqual ( data, stores ); if ( isDataIdentity ) return listener.apply ( undefined, stores ); const isDataStore = stores.indexOf ( data ) >= 0; if ( isDataStore && ( rootsChangeAll.get ( data ) || EMPTY_ARRAY ).length ) return listener ( data ); const isSimpleSelector = Array.from ( rootsGetAll.values () ).every ( paths => !paths.length ); if ( isSimpleSelector ) return listener ( data ); for ( let i = 0; i < storesNr; i++ ) { const store = stores[i], rootsChange = rootsChangeAll.get ( store ) || EMPTY_ARRAY; if ( !rootsChange.length ) continue; const rootsGet = rootsGetAll.get ( store ) || EMPTY_ARRAY; if ( !rootsGet.length ) continue; const changed = Utils.uniq ( rootsGet ).some ( rootGet => rootsChange.indexOf ( rootGet ) >= 0 ); if ( !changed ) continue; if ( comparator && comparator !== COMPARATOR_FALSE && comparator ( comparatorDataPrev, data ) ) return; // Custom comparator says nothing changed return listener ( data ); } }; for ( let i = 0; i < storesNr; i++ ) { const store = stores[i], changes = ChangesSubscribers.get ( store ); if ( !changes ) throw Errors.storeNotFound (); const disposer = changes.subscribe ( rootsChange => { const rootsChangePrev = rootsChangeAllCache.get ( store ); if ( rootsChangePrev ) { rootsChangePrev.push ( ...rootsChange ); } else { rootsChangeAllCache.set ( store, rootsChange ); } if ( storesNr === 1 ) return handler (); return Scheduler.schedule ( handler ); }); disposers.push ( disposer ); } return () => { for ( let i = 0, l = disposers.length; i < l; i++ ) disposers[i](); }; } /* EXPORT */ export default onChange;
the_stack
import React, { FunctionComponent, useEffect, useMemo, useRef, useState, } from "react"; import { ScrollViewProps, View, Animated as NativeAnimated, } from "react-native"; import { PanGestureHandler } from "react-native-gesture-handler"; import Animated, { Easing } from "react-native-reanimated"; import { stableSort } from "../../utils/stable-sort"; interface MemoizedItem<Item extends { key: string }> { item: Item; virtualIndex: Animated.Value<number>; } export interface FixedHeightSortableListProps<Item extends { key: string }> extends ScrollViewProps { itemHeight: number; data: ReadonlyArray<Item>; renderItem: ( item: Item, anims: { readonly isDragging: Animated.Value<number>; readonly onGestureEvent: (...args: any[]) => void; } ) => React.ReactElement | null; onDragEnd: (sortedKeys: string[]) => void; dividerIndex?: number; delegateOnGestureEventToItemView?: boolean; gapTop?: number; gapBottom?: number; } /** * TODO: Translate to English. * * 동일한 높이를 가진 Item들을 가지는 ScrollView 안의 list를 구현한다. * 이 list는 터치를 통해서 drag and sort 할 수 있다. * * 리액트 네이티브의 한계로 리렌더링이 일어나면 끊기는 현상이 일어나서 부드러운 애니메이션이 불가능하다. * 그렇기 때문에 이 컴포넌트의 내부 구현은 최대한 리렌더링을 막는 방향으로 구현되어 있다. * 사용하는 쪽에서도 리렌더링이 최대한 발생하지 않도록 약간 신경을 써야한다. * data prop을 통해서 각 Item으로 전달될 prop을 반환할 수 있다. * 그 prop들은 얇은 비교를 통해서 리렌더링을 수행할 지 결정된다. * 그러므로 각 data들은 얇은 비교만으로 구분할 수 있도록 primitive type만을 사용하는게 추천된다. * * 이 컴포넌트는 사실 chain list screen을 구현하기 위해서 만들어진 것이다. * dividerIndex prop은 위의 스크린에서 필요한 행동을 구현하기 위해서 존재한다. * dividerIndex의 위쪽에 있는 Item들과 아래쪽에 있는 Item들을 서로의 구역으로 이동할 수 없다. * 하지만 리렌더링을 막기 위해서 dividerIndex는 reanimated의 value로 구현되어 있고 * prop이 변하더라도 reanimated의 프로세스로 value를 변경하도록 요청한다. * 이 요청은 동기적으로 이루어지지 않는다. * 일반적인 유저 행동에서는 문제가 되지 않지만 비동기적으로 작동되기 때문에 * 유저가 이상하게 행동하면 버그가 발생할 수 있다. 이건 현재로서는 방법이 없다. * * NOTE: renderItem prop을 통해서 Item을 렌더링할 컴포넌트를 전달받을 수 있다. * 하지만 리렌더링을 컨트롤하기 위해서 renderItem prop을 사용하는 쪽에서 useCallback 등을 통해서 * memoization하는 것을 강제하는 것보다 더 간편하게 사용할 수 있도록 하기 위해서 * renderItem에 대해서는 리렌더링 검사를 하지 않는다. * 그러므로 renderItem의 변화를 이 컴포넌트에서 감지할 수 없다. * renderItem이 변경되더라도 data를 통해서 전달된 prop이 변하지 않는다면 리렌더링이 되지 않기 때문에 적용되지 않는다. * 이건 버그가 아니라 의도된 행동이다. * 일반적으로 renderItem의 행동이 변경될 일은 없다. 그러므로 이러한 한계를 무시한 것이다. * @param props * @constructor */ export function FixedHeightSortableList<Item extends { key: string }>( props: FixedHeightSortableListProps<Item> ) { const { data, renderItem, itemHeight, onDragEnd, dividerIndex = -1, delegateOnGestureEventToItemView = false, gapTop = 0, gapBottom = 0, ...scrollViewProps } = props; // It is hard to handle multi touch. // So, prevent multi touch by using this. const [draggingGlobalLock] = useState(() => new Animated.Value(0)); const [virtualDividerIndex] = useState( () => new Animated.Value(dividerIndex) ); useEffect(() => { virtualDividerIndex.setValue(dividerIndex); }, [dividerIndex, virtualDividerIndex]); const memoizationMap = useRef< Map< string, { virtualIndex: Animated.Value<number>; } > >(new Map()); const memoizedItems = useMemo<MemoizedItem<Item>[]>(() => { const usedKeys = new Map<string, boolean>(); const result = data .slice() .map((item, index) => { return { item, index, }; }) .sort((a, b) => { // Sort by key to maintain rendering order. return a.item.key < b.item.key ? -1 : 1; }) .map(({ item, index }) => { usedKeys.set(item.key, true); // Use memoized data (with memoized animated value) to reduce rendering. let memoizedData = memoizationMap.current.get(item.key); if (memoizedData) { memoizedData.virtualIndex.setValue(index); } else { memoizedData = { virtualIndex: new Animated.Value(index), }; memoizationMap.current.set(item.key, memoizedData); } return { item, virtualIndex: memoizedData.virtualIndex, }; }); // Remove unused memoized data for (const key of memoizationMap.current.keys()) { if (!usedKeys.get(key)) { usedKeys.delete(key); } } return result; }, [data]); const onDragEndRef = useRef(onDragEnd); onDragEndRef.current = onDragEnd; const procMemoization = useRef< | { onItemMove: any; onDragEnd: any; keys: string; } | undefined >(undefined); const procs = useMemo(() => { const keys = memoizedItems.map((item) => item.item.key).join(","); if (procMemoization.current && procMemoization.current.keys === keys) { return { onItemMove: procMemoization.current.onItemMove, onDragEnd: procMemoization.current.onDragEnd, }; } else { const onItemMoveProc = Animated.proc( (before: Animated.Value<number>, after: Animated.Value<number>) => Animated.block([ ...memoizedItems.map((item) => { return [ Animated.cond(Animated.not(Animated.eq(before, after)), [ Animated.cond( Animated.eq(before, item.virtualIndex), [ Animated.set(item.virtualIndex, after), Animated.cond(Animated.lessThan(item.virtualIndex, 0), [ Animated.set(item.virtualIndex, 0), ]), Animated.cond( Animated.greaterOrEq( item.virtualIndex, memoizedItems.length ), [ Animated.set( item.virtualIndex, memoizedItems.length - 1 ), ] ), ], [ Animated.cond( Animated.lessThan(Animated.sub(before, after), 0), [ Animated.cond( Animated.and( Animated.greaterThan(item.virtualIndex, before), Animated.lessOrEq(item.virtualIndex, after) ), [ Animated.set( item.virtualIndex, Animated.sub(item.virtualIndex, 1) ), ] ), ], [ Animated.cond( Animated.and( Animated.lessThan(item.virtualIndex, before), Animated.greaterOrEq(item.virtualIndex, after) ), [ Animated.set( item.virtualIndex, Animated.add(item.virtualIndex, 1) ), ] ), ] ), ] ), ]), ]; }), ]) ); const onDragEndCallback = (indexs: readonly number[]) => { const keysWithIndex = memoizedItems.map((item, i) => { return { key: item.item.key, index: indexs[i], }; }); const sorted = stableSort(keysWithIndex, (a, b) => { if (a.index === b.index) { return 0; } return a.index < b.index ? -1 : 1; }).map(({ key }) => key); onDragEndRef.current(sorted); }; const onDragEndProc = Animated.proc(() => Animated.block([ Animated.call( memoizedItems.map((item) => item.virtualIndex), onDragEndCallback ), ]) ); procMemoization.current = { keys, onItemMove: onItemMoveProc, onDragEnd: onDragEndProc, }; return { onItemMove: procMemoization.current.onItemMove, onDragEnd: procMemoization.current.onDragEnd, }; } }, [memoizedItems]); return ( <NativeAnimated.ScrollView {...scrollViewProps}> <View style={{ height: itemHeight * memoizedItems.length + gapTop + gapBottom, }} /> {memoizedItems.map((memoizedItem) => { const { key, ...rest } = memoizedItem.item; return ( <MemoizedChildrenRenderer key={key} {...rest} itemHeight={itemHeight} procOnItemMove={procs.onItemMove} procOnDragEnd={procs.onDragEnd} delegateOnGestureEventToItemView={delegateOnGestureEventToItemView} gapTop={gapTop} > <FixedHeightSortableListItem itemHeight={itemHeight} procOnItemMove={procs.onItemMove} procOnDragEnd={procs.onDragEnd} delegateOnGestureEventToItemView={ delegateOnGestureEventToItemView } gapTop={gapTop} // Belows no need to be under `MemoizedChildrenRenderer` virtualIndex={memoizedItem.virtualIndex} virtualDividerIndex={virtualDividerIndex} draggingGlobalLock={draggingGlobalLock} renderItem={renderItem} item={memoizedItem.item} /> </MemoizedChildrenRenderer> ); })} </NativeAnimated.ScrollView> ); } // eslint-disable-next-line react/display-name const MemoizedChildrenRenderer: FunctionComponent<any> = React.memo((props) => { const { children } = props; return children; }); const usePreviousDiff = (initialValue: number) => { const [previous] = useState(() => new Animated.Value<number>(initialValue)); return useMemo(() => { return { set: (value: Animated.Adaptable<number>) => Animated.set(previous, value), diff: (value: Animated.Adaptable<number>) => Animated.cond( Animated.defined(previous), Animated.sub(value, previous), value ), previous, }; }, [previous]); }; const FixedHeightSortableListItem: FunctionComponent<{ itemHeight: number; virtualIndex: Animated.Value<number>; virtualDividerIndex: Animated.Value<number>; draggingGlobalLock: Animated.Value<number>; procOnItemMove: any; procOnDragEnd: any; delegateOnGestureEventToItemView: boolean; item: any; renderItem: FixedHeightSortableListProps<any>["renderItem"]; gapTop: number; }> = ({ itemHeight, virtualIndex, virtualDividerIndex, draggingGlobalLock, procOnItemMove, procOnDragEnd, delegateOnGestureEventToItemView, item, renderItem, gapTop, }) => { const [animatedState] = useState(() => { return { clock: new Animated.Clock(), finished: new Animated.Value(0), position: new Animated.Value<number>(undefined), time: new Animated.Value(0), frameTime: new Animated.Value(0), }; }); const [isDragging] = useState(() => new Animated.Value(0)); const [zIndexAdditionOnTransition] = useState(() => new Animated.Value(0)); const [currentDraggingIndex] = useState(() => new Animated.Value(0)); const translateYDiff = usePreviousDiff(0); const virtualIndexDiff = usePreviousDiff(-1); const onGestureEvent = useMemo(() => { return Animated.event([ { nativeEvent: ({ translationY, state, }: { translationY: number; state: number; }) => { return Animated.block([ Animated.cond( // Check that the state is BEGEN or ACTIVE. Animated.or(Animated.eq(state, 2), Animated.eq(state, 4)), [ Animated.cond( Animated.and( Animated.eq(isDragging, 0), Animated.and( Animated.not(Animated.clockRunning(animatedState.clock)), Animated.eq(draggingGlobalLock, 0) ) ), [ Animated.debug("start dragging", virtualIndex), Animated.set(isDragging, 1), Animated.set(draggingGlobalLock, 1), Animated.set(zIndexAdditionOnTransition, 10000000), Animated.set(currentDraggingIndex, virtualIndex), ] ), ], [ Animated.cond(Animated.greaterThan(isDragging, 0), [ Animated.debug("stop dragging", virtualIndex), Animated.set(isDragging, 0), Animated.set(draggingGlobalLock, 0), Animated.set(translateYDiff.previous, 0), Animated.set(animatedState.finished, 0), Animated.set(animatedState.time, 0), Animated.set(animatedState.frameTime, 0), Animated.cond( Animated.not(Animated.clockRunning(animatedState.clock)), Animated.startClock(animatedState.clock) ), procOnDragEnd(), ]), ] ), Animated.cond( Animated.greaterThan(isDragging, 0), [ Animated.cond( Animated.eq(translateYDiff.previous, 0), [ Animated.set( animatedState.position, Animated.add(animatedState.position, translationY) ), ], [ Animated.set( animatedState.position, Animated.add( animatedState.position, translateYDiff.diff(translationY) ) ), ] ), translateYDiff.set(translationY), ], [Animated.set(translateYDiff.previous, 0)] ), ]); }, }, ]); }, [ animatedState.clock, animatedState.finished, animatedState.frameTime, animatedState.position, animatedState.time, currentDraggingIndex, draggingGlobalLock, isDragging, procOnDragEnd, translateYDiff, virtualIndex, zIndexAdditionOnTransition, ]); const positionY = useMemo(() => { return Animated.block([ Animated.cond(Animated.not(Animated.defined(animatedState.position)), [ Animated.set( animatedState.position, Animated.add(Animated.multiply(itemHeight, virtualIndex), gapTop) ), ]), Animated.cond( Animated.eq(isDragging, 0), [ Animated.cond(Animated.greaterOrEq(virtualIndexDiff.previous, 0), [ Animated.cond( Animated.not(Animated.eq(virtualIndexDiff.diff(virtualIndex), 0)), [ Animated.set( zIndexAdditionOnTransition, Animated.multiply( 10000, Animated.abs(virtualIndexDiff.diff(virtualIndex)) ) ), Animated.set(animatedState.finished, 0), Animated.set(animatedState.time, 0), Animated.set(animatedState.frameTime, 0), Animated.cond( Animated.not(Animated.clockRunning(animatedState.clock)), Animated.startClock(animatedState.clock) ), ] ), ]), Animated.timing(animatedState.clock, animatedState, { duration: 350, toValue: Animated.add( Animated.multiply(itemHeight, virtualIndex), gapTop ), easing: Easing.out(Easing.cubic), }), Animated.cond(animatedState.finished, [ Animated.stopClock(animatedState.clock), Animated.set(zIndexAdditionOnTransition, 0), ]), ], [ Animated.set( currentDraggingIndex, Animated.floor( Animated.divide( Animated.add( Animated.sub(animatedState.position, gapTop), itemHeight / 2 ), itemHeight ) ) ), Animated.cond(Animated.greaterThan(virtualDividerIndex, 0), [ Animated.cond( Animated.lessThan(virtualIndex, virtualDividerIndex), [ Animated.cond( Animated.greaterOrEq( currentDraggingIndex, virtualDividerIndex ), [ Animated.set( currentDraggingIndex, Animated.sub(virtualDividerIndex, 1) ), ] ), ], [ Animated.cond( Animated.lessThan(currentDraggingIndex, virtualDividerIndex), [Animated.set(currentDraggingIndex, virtualDividerIndex)] ), ] ), ]), Animated.cond( Animated.not(Animated.eq(virtualIndex, currentDraggingIndex)), [procOnItemMove(virtualIndex, currentDraggingIndex)] ), ] ), virtualIndexDiff.set(virtualIndex), animatedState.position, ]); }, [ animatedState, currentDraggingIndex, gapTop, isDragging, itemHeight, procOnItemMove, virtualDividerIndex, virtualIndex, virtualIndexDiff, zIndexAdditionOnTransition, ]); return ( <PanGestureHandler enabled={!delegateOnGestureEventToItemView} onGestureEvent={onGestureEvent} onHandlerStateChange={onGestureEvent} > <Animated.View style={{ position: "absolute", height: itemHeight, width: "100%", top: positionY, zIndex: Animated.add(virtualIndex, zIndexAdditionOnTransition), }} > {renderItem(item, { isDragging, onGestureEvent, })} </Animated.View> </PanGestureHandler> ); };
the_stack
import { assert } from '@canvas-ui/assert' import { NonConstructiable } from '../foundation' import { Point, Rect } from '../math' import { PlatformAdapter } from '../platform' export type Directive = [string, ...number[]] export class Path extends NonConstructiable { /** * 解析 SVG 路径 */ static parse(str: string): Directive[] { const result: Directive[] = [] const coords: string[] = [] let currentPath: string let parsed: number let match: RegExpExecArray | null = null let coordsStr: string if (!str || !str.match) { return result } const path = str.match(InvalidDirectiveReg) if (!path) { return result } for (let i = 0, n = path.length; i < n; i++) { currentPath = path[i] coordsStr = currentPath.slice(1).trim() coords.length = 0 let command = currentPath.charAt(0) const coordsParsed: Directive = [command] if (command.toLowerCase() === 'a') { for (let args; (args = ArcArgsReg.exec(coordsStr));) { for (let j = 1; j < args.length; j++) { coords.push(args[j]) } } } else { while ((match = FirstArgReg.exec(coordsStr))) { coords.push(match[0]) } } for (let j = 0, jlen = coords.length; j < jlen; j++) { parsed = parseFloat(coords[j]) if (!isNaN(parsed)) { coordsParsed.push(parsed) } } const commandLength = ArgLengths[command.toLowerCase()] const repeatedCommand = RepeatedCommands[command] || command if (coordsParsed.length - 1 > commandLength) { for (let k = 1, klen = coordsParsed.length; k < klen; k += commandLength) { result.push(([command] as Directive).concat(coordsParsed.slice(k, k + commandLength) as number[]) as Directive) command = repeatedCommand } } else { result.push(coordsParsed) } } return result } /** * 转换所有相对指令到绝对指令 */ static simplify(path: Directive[]) { let x = 0 let y = 0 const n = path.length let x1 = 0 let y1 = 0 let current: Directive | undefined let converted = false let result: Directive[] = [] let previous: string | undefined let controlX = 0 let controlY = 0 for (let i = 0; i < n; ++i) { converted = false current = path[i].slice(0) as Directive switch (current[0]) { case 'l': current[0] = 'L' current[1] += x current[2] += y // falls through case 'L': x = current[1] y = current[2] break case 'h': current[1] += x // falls through case 'H': current[0] = 'L' current[2] = y x = current[1] break case 'v': current[1] += y // falls through case 'V': current[0] = 'L' y = current[1] current[1] = x current[2] = y break case 'm': current[0] = 'M' current[1] += x current[2] += y // falls through case 'M': x = current[1] y = current[2] x1 = current[1] y1 = current[2] break case 'c': current[0] = 'C' current[1] += x current[2] += y current[3] += x current[4] += y current[5] += x current[6] += y // falls through case 'C': controlX = current[3] controlY = current[4] x = current[5] y = current[6] break case 's': current[0] = 'S' current[1] += x current[2] += y current[3] += x current[4] += y // falls through case 'S': if (previous === 'C') { controlX = 2 * x - controlX controlY = 2 * y - controlY } else { controlX = x controlY = y } x = current[3] y = current[4] current[0] = 'C' current[5] = current[3] current[6] = current[4] current[3] = current[1] current[4] = current[2] current[1] = controlX current[2] = controlY controlX = current[3] controlY = current[4] break case 'q': current[0] = 'Q' current[1] += x current[2] += y current[3] += x current[4] += y // falls through case 'Q': controlX = current[1] controlY = current[2] x = current[3] y = current[4] break case 't': current[0] = 'T' current[1] += x current[2] += y // falls through case 'T': if (previous === 'Q') { controlX = 2 * x - controlX controlY = 2 * y - controlY } else { controlX = x controlY = y } current[0] = 'Q' x = current[1] y = current[2] current[1] = controlX current[2] = controlY current[3] = x current[4] = y break case 'a': current[0] = 'A' current[6] += x current[7] += y // falls through case 'A': converted = true result = result.concat(fromArcToBeziers(x, y, current)) x = current[6] y = current[7] break case 'z': case 'Z': x = x1 y = y1 break default: } if (!converted) { result.push(current) } previous = current[0] } return result } static calculateBounds(path: Directive[]) { const aX = [] const aY = [] let current: Directive let subpathStartX = 0 let subpathStartY = 0 let x = 0 let y = 0 let bounds: { x: number, y: number }[] for (let i = 0, n = path.length; i < n; ++i) { current = path[i] switch (current[0]) { case 'L': x = current[1] y = current[2] bounds = [] break case 'M': x = current[1] y = current[2] subpathStartX = x subpathStartY = y bounds = [] break case 'C': bounds = getBoundsOfCurve(x, y, current[1], current[2], current[3], current[4], current[5], current[6] ) x = current[5] y = current[6] break case 'Q': bounds = getBoundsOfCurve(x, y, current[1], current[2], current[1], current[2], current[3], current[4] ) x = current[3] y = current[4] break case 'z': case 'Z': x = subpathStartX y = subpathStartY break } bounds!.forEach(function (point) { aX.push(point.x) aY.push(point.y) }) aX.push(x) aY.push(y) } const minX = Math.min(...aX), minY = Math.min(...aY), maxX = Math.max(...aX), maxY = Math.max(...aY) return Rect.fromLTRB( minX, minY, maxX, maxY, ) } private static _testContext: CanvasDrawPath & CanvasPathDrawingStyles private static get testContext() { if (Path._testContext) { return Path._testContext } const size = 1 const canvas = PlatformAdapter.supportOffscreenCanvas ? PlatformAdapter.createOffscreenCanvas(size, size) : PlatformAdapter.createCanvas(size, size) const context = canvas.getContext('2d') assert(context) context.lineCap = 'round' return Path._testContext = context } static isPointInStroke(path: Path2D, point: Point, strokeWidth = 1) { const { testContext } = Path testContext.lineWidth = strokeWidth return testContext.isPointInStroke(path, point.x, point.y) } } const NumberPattern = '[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?\\s*' const CommaWspPattern = '(?:\\s+,?\\s*|,\\s*)' const FirstArgReg = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/ig const NumberCommaWspPattern = '(' + NumberPattern + ')' + CommaWspPattern const FlagCommaWspPattern = '([01])' + CommaWspPattern + '?' const ArcArgsReg = new RegExp( NumberCommaWspPattern + '?' + NumberCommaWspPattern + '?' + NumberCommaWspPattern + FlagCommaWspPattern + FlagCommaWspPattern + NumberCommaWspPattern + '?(' + NumberPattern + ')', 'g') const InvalidDirectiveReg = /[mzlhvcsqta][^mzlhvcsqta]*/gi const ArgLengths: Record<string, number> = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, } as const const RepeatedCommands: Record<string, string> = { m: 'l', M: 'L', } as const function fromArcToBeziers(fx: number, fy: number, coords: any[]) { const rx = coords[1], ry = coords[2], rot = coords[3], large = coords[4], sweep = coords[5], tx = coords[6], ty = coords[7], segs = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot) for (let i = 0, len = segs.length; i < len; i++) { segs[i][1] += fx segs[i][2] += fy segs[i][3] += fx segs[i][4] += fy segs[i][5] += fx segs[i][6] += fy } return segs } /** * http://dxr.mozilla.org/mozilla-central/source/content/svg/content/src/nsSVGPathDataParser.cpp */ function arcToSegments( toX: number, toY: number, rx: number, ry: number, large: number, sweep: number, rotateX: number,) { const PI = Math.PI const th = rotateX * PI / 180 const sinTh = Math.sin(th) const cosTh = Math.cos(th) let fromX = 0 let fromY = 0 rx = Math.abs(rx) ry = Math.abs(ry) const px = -cosTh * toX * 0.5 - sinTh * toY * 0.5, py = -cosTh * toY * 0.5 + sinTh * toX * 0.5, rx2 = rx * rx, ry2 = ry * ry, py2 = py * py, px2 = px * px, pl = rx2 * ry2 - rx2 * py2 - ry2 * px2 let root = 0 if (pl < 0) { const s = Math.sqrt(1 - pl / (rx2 * ry2)) rx *= s ry *= s } else { root = (large === sweep ? -1.0 : 1.0) * Math.sqrt(pl / (rx2 * py2 + ry2 * px2)) } const cx = root * rx * py / ry, cy = -root * ry * px / rx, cx1 = cosTh * cx - sinTh * cy + toX * 0.5, cy1 = sinTh * cx + cosTh * cy + toY * 0.5 let mTheta = calcVectorAngle(1, 0, (px - cx) / rx, (py - cy) / ry) let dtheta = calcVectorAngle((px - cx) / rx, (py - cy) / ry, (-px - cx) / rx, (-py - cy) / ry) if (sweep === 0 && dtheta > 0) { dtheta -= 2 * PI } else if (sweep === 1 && dtheta < 0) { dtheta += 2 * PI } // Convert into cubic bezier segments <= 90deg const segments = Math.ceil(Math.abs(dtheta / PI * 2)) const result = [] const mDelta = dtheta / segments const mT = 8 / 3 * Math.sin(mDelta / 4) * Math.sin(mDelta / 4) / Math.sin(mDelta / 2) let th3 = mTheta + mDelta for (let i = 0; i < segments; i++) { result[i] = segmentToBezier(mTheta, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY) fromX = result[i][5] fromY = result[i][6] mTheta = th3 th3 += mDelta } return result } function calcVectorAngle(ux: number, uy: number, vx: number, vy: number) { const ta = Math.atan2(uy, ux) const tb = Math.atan2(vy, vx) if (tb >= ta) { return tb - ta } else { return 2 * Math.PI - (ta - tb) } } function segmentToBezier( th2: number, th3: number, cosTh: number, sinTh: number, rx: number, ry: number, cx1: number, cy1: number, mT: number, fromX: number, fromY: number ) { const costh2 = Math.cos(th2), sinth2 = Math.sin(th2), costh3 = Math.cos(th3), sinth3 = Math.sin(th3), toX = cosTh * rx * costh3 - sinTh * ry * sinth3 + cx1, toY = sinTh * rx * costh3 + cosTh * ry * sinth3 + cy1, cp1X = fromX + mT * (-cosTh * rx * sinth2 - sinTh * ry * costh2), cp1Y = fromY + mT * (-sinTh * rx * sinth2 + cosTh * ry * costh2), cp2X = toX + mT * (cosTh * rx * sinth3 + sinTh * ry * costh3), cp2Y = toY + mT * (sinTh * rx * sinth3 - cosTh * ry * costh3) return [ 'C', cp1X, cp1Y, cp2X, cp2Y, toX, toY ] as Directive } // http://jsbin.com/ivomiq/56/edit function getBoundsOfCurve(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number) { const sqrt = Math.sqrt, min = Math.min, max = Math.max, abs = Math.abs, tvalues = [], bounds: any[] = [[], []] let a, b, c, t, t1, t2, b2ac, sqrtb2ac b = 6 * x0 - 12 * x1 + 6 * x2 a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3 c = 3 * x1 - 3 * x0 for (let i = 0; i < 2; ++i) { if (i > 0) { b = 6 * y0 - 12 * y1 + 6 * y2 a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3 c = 3 * y1 - 3 * y0 } if (abs(a) < 1e-12) { if (abs(b) < 1e-12) { continue } t = -c / b if (0 < t && t < 1) { tvalues.push(t) } continue } b2ac = b * b - 4 * c * a if (b2ac < 0) { continue } sqrtb2ac = sqrt(b2ac) t1 = (-b + sqrtb2ac) / (2 * a) if (0 < t1 && t1 < 1) { tvalues.push(t1) } t2 = (-b - sqrtb2ac) / (2 * a) if (0 < t2 && t2 < 1) { tvalues.push(t2) } } let x, y, j = tvalues.length const jlen = j let mt: number while (j--) { t = tvalues[j] mt = 1 - t x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3) bounds[0][j] = x y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3) bounds[1][j] = y } bounds[0][jlen] = x0 bounds[1][jlen] = y0 bounds[0][jlen + 1] = x3 bounds[1][jlen + 1] = y3 const result = [ { // eslint-disable-next-line prefer-spread x: min.apply(null, bounds[0]), // eslint-disable-next-line prefer-spread y: min.apply(null, bounds[1]) }, { // eslint-disable-next-line prefer-spread x: max.apply(null, bounds[0]), // eslint-disable-next-line prefer-spread y: max.apply(null, bounds[1]) } ] return result }
the_stack
import fs from "fs"; import { strict as assert } from "assert"; import { ArgumentParser } from "argparse"; import { ZonedDateTime } from "@js-joda/core"; import { rndstring } from "./util"; import { log, changeStderrLogLevel } from "./log"; import { DEFAULT_LOG_LEVEL_STDERR } from "./index"; interface CfgInterface { n_series: number; n_chars_per_msg: number; n_samples_per_series_fragment: number; n_cycles: number; n_fragments_per_push_message: number; cycle_stop_write_after_n_fragments: number; cycle_stop_write_after_n_seconds: number; cycle_stop_write_after_n_seconds_jitter: number; max_concurrent_writes: number; max_concurrent_reads: number; logLevel: string; apibaseurl: string; invocation_id: string; log_start_time: string; log_time_increment_ns: number; http_server_port: number; additional_labels: Array<[string, string]> | undefined; compressability: string; change_series_every_n_cycles: number; metrics_mode: boolean; // max_start_time_offset_minutes: number; metrics_time_increment_ms: number; bearer_token_file: string; retry_post_deadline_seconds: number; retry_post_min_delay_seconds: number; retry_post_max_delay_seconds: number; retry_post_jitter: number; skip_read: boolean; read_n_series_only: number; } export let CFG: CfgInterface; export let BEARER_TOKEN: undefined | string; // Formatter with support of `\n` in Help texts. // class HelpFormatter extends RawDescriptionHelpFormatter { // // executes parent _split_lines for each line of the help, then flattens the result // _split_lines(text: string, width: number) { // return [].concat( // ...text.split("\n").map(line => super._split_lines(line, width)) // ); // } // } export function parseCmdlineArgs(): void { const parser = new ArgumentParser({ //formatter_class: HelpFormatter, description: `Looker is a Loki / Cortex testing and benchmarking tool. Looker originated as a black-box storage testing program for Loki with strict and deep read validation. Since then, it has evolved quite a bit. ` // .replace("\n\n", "FOO") // .replace("\n", " ") // .replace("FOO", "\n") }); parser.add_argument("apibaseurl", { help: "Push API base URL (/loki/api/v1/push and " + "/api/v1/push are prepended automatically in logs and metrics mode, " + "respectively).", type: "str" }); parser.add_argument("--log-level", { help: `Set log level for output on stderr. ` + `One of: debug, info, warning, error. ` + `Default: ${DEFAULT_LOG_LEVEL_STDERR}`, type: "str", choices: ["debug", "info", "warning", "error"], default: DEFAULT_LOG_LEVEL_STDERR, metavar: "LEVEL", dest: "logLevel" }); // Rename to "--send-logs" or "--send-metrics"? parser.add_argument("--metrics-mode", { help: "'Metrics mode' (Cortex) instead of 'Logs mode' (Loki).", action: "store_true", default: false }); parser.add_argument("--n-series", { help: "Number of synthetic time series to generate and consume from in each " + "write/read cycle.", type: "int", metavar: "N", required: true }); parser.add_argument("--n-samples-per-series-fragment", { help: "Number of samples (log entries or metric samples) to put into " + "each time series fragment. A time series fragment is a distinct set " + "of samples in chronological order. A push message is comprised of " + "one or more time series fragments (with F fragments from F different " + "time series -- a push message generated by Looker never contains " + "more than one time series fragment from the same time series.", type: "int", metavar: "N", required: true }); // think/todo: rename to reflect that this is the desired (max) N. Boundary // effects may result in much smaller fragment counts. Maybe make it so that // this must be at most --n-series because if that (number of // series) is smaller than this number here then no push message will have // the desired fragment count. parser.add_argument("--n-fragments-per-push-message", { help: "Number of series fragments to serialize into a single binary push message " + "(HTTP POST request body), mixed from different series. Default: 1.", type: "int", metavar: "N", default: 1 }); parser.add_argument("--n-chars-per-msg", { help: "Number of characters per log message (ignored in metrics mode). " + "Default: 100.", type: "int", metavar: "N", default: 100 }); // note: looking for a more expressive name // consider removing this options now that we're aligning log and metrics // mode w.r.t. walltime coupling. parser.add_argument("--log-start-time", { help: "This disables the loose coupling of synthetic time to wall time " + "and defines the timestamp of the first sample for all synthetic " + "log time series. Does not apply in metrics mode. Is useful when " + "writing to Loki that is configured to allow ingesting log samples " + "far from the past or future. Must be provided in " + "RFC3339 notation. Note that across cycles the same " + "start time is used.", type: "str", default: "" }); parser.add_argument("--log-time-increment-ns", { help: "Time difference in nanonseconds between adjacent log entries in a " + "log series (between log entry timestamps) (ignored in metrics mode). " + "Default: 1 ns.", type: "int", metavar: "N", default: 1 }); // parser.add_argument("--max-start-time-offset-minutes", { // help: // "The syntheic time series start time is chosen randomly from the interval " + // "between the initialization wall time ('now', during runtime) and a " + // "point in time in the past (unless --log-start-time is provided). " + // "This parameter defines the lower bound of said interval, i.e. how far " + // "at most to go into the past compared to the " + // "the initialization wall time. Defaults to 10 minutes." + // "other time constants).", // type: "int", // default: 10 * 60 // }); parser.add_argument("--metrics-time-increment-ms", { help: "Time difference in milliseconds between adjacent samples in a " + "time series. Default: 1 ms.", type: "int", metavar: "N", default: 1 }); parser.add_argument("--max-concurrent-writes", { help: "Maximum number of POST HTTP requests to perform concurrently. " + "Default: use 10 concurrent writers or less if --n-series is smaller.", type: "int", metavar: "N", default: 0 }); const readgroup = parser.add_mutually_exclusive_group(); readgroup.add_argument("--max-concurrent-reads", { help: "Maximum number of GET HTTP requests to perform concurrently during " + "the read/validation phase. " + "Default: use 10 concurrent writers or less if --n-series is smaller.", type: "int", metavar: "N", default: 0 }); readgroup.add_argument("--skip-read", { help: "Skip the readout in the write/read cycle, proceed to the next " + "cycle instead.", action: "store_true", default: false }); // This must not be used with `--skip-read`, but it can be used with // --max-concurrent-reads. The `add_mutually_exclusive_group()` architecture // of argparse is not really the right way to solve this, also see // https://stackoverflow.com/a/60958103/145400 and // https://bugs.python.org/issue10984. Simply do ad-hoch manual validation // below. Caveat: the [ ... | ... ]- like notation in the auto-generated // help text will not be entirely correct. parser.add_argument("--read-n-series-only", { help: "Maximum number of series to read (validate) in the read phase of a " + "write/read cycle. Use this if you want to read (validate) less data " + "than what was written. The subset of series is picked randomly at the " + "beginning of each read phase. Default: 0 " + "(read back everything that was written).", type: "int", metavar: "N", default: 0 }); // parser.add_argument("--inspect-every-nth-log-entry", { // help: // "When a log time series is selected for read validation then all " + // "entries from that series are fetched, but not all log entries are .." + // "NOTE(JP): while I write this I realize that it is better to only have " + // "--read-n-series-only for now, and to look at each entry when "+ // "a series is selected for read-validation", // type: "int", // default: 200 // }); parser.add_argument("--compressability", { help: "Compressability characteristic of generated log messages " + "(ignored in metrics mode).", type: "str", choices: ["min", "max", "medium"], default: "min" }); parser.add_argument("--n-cycles", { help: "Number of write/read cycles to perform before terminating the program. " + "Every cycle allows for (potentially sparse) read validation of " + "what was previously written, and also generates a performance report. " + "Default: 0 (perform an infinite amount of cycles).", type: "int", metavar: "N", default: 0 }); parser.add_argument("--change-series-every-n-cycles", { help: "Use the same log/metric time series for N cycles, then create a new " + "set of series (unique label sets). If set to 0 then the initial set " + "of time series is reused for the process lifetime (the default).", type: "int", metavar: "N", default: 0 }); parser.add_argument("--label", { help: "add a label key/value pair to all emitted log entries", metavar: ["KEY", "VALUE"], nargs: 2, action: "append", dest: "additional_labels" }); parser.add_argument("--http-server-port", { help: "HTTP server listen port (serves /metrics Prometheus endpoint). " + "Default: try 8900-8990.", type: "int", default: 0 }); const stopgroup = parser.add_mutually_exclusive_group({ required: true }); stopgroup.add_argument("--cycle-stop-write-after-n-fragments", { help: "Cycle write phase stop criterion A: stop write (and enter read phase) " + "when this many fragments were written for each time series. " + "Default: 0 (never enter the read phase).", type: "int", metavar: "N", default: 0 }); stopgroup.add_argument("--cycle-stop-write-after-n-seconds", { help: "Cycle write phase stop criterion A: stop write (and enter read phase) " + "having written for approximately that many seconds. " + "Default: 0 (never enter the read phase).", type: "int", metavar: "N", default: 0 }); parser.add_argument("--cycle-stop-write-after-n-seconds-jitter", { help: "Add random number of seconds from interval [-J,J] " + "to --cycle-stop-write-after-n-seconds. Default: 0.", metavar: "J", type: "float", default: 0 }); parser.add_argument("--retry-post-deadline-seconds", { help: "Maximum time spent retrying POST requests, in seconds. Default: 420.", type: "int", default: 420 }); parser.add_argument("--retry-post-min-delay-seconds", { help: "Minimal delay between POST request retries, in seconds. Default: 3.", type: "int", default: 3 }); parser.add_argument("--retry-post-max-delay-seconds", { help: "Maximum delay between POST request retries, in seconds. Deault: 30.", type: "int", default: 30 }); parser.add_argument("--retry-post-jitter", { help: "Relative jitter to apply for calculating the retry delay " + "(1: max). Default: 0.5.", type: "float", metavar: "FLOAT", default: 0.5 }); parser.add_argument("--bearer-token-file", { help: "Read authentication token from file. Add header " + "`Authorization: Bearer <token>` to each HTTP request.", type: "str", default: "" }); parser.add_argument("--invocation-id", { help: "Name of this looker instance to be included in labels. " + "By default a random looker-<X> string is used. " + "If read validation is enabled then care should be taken to ensure " + "uniqueness at the server.", type: "str", default: "" }); CFG = parser.parse_args(); changeStderrLogLevel(CFG.logLevel); if (CFG.invocation_id === "") { // Generate invocation ID. For long-running test scenarios where individual // lookers are started at high rate this should not create collisions. const uniqueInvocationId = `looker-${rndstring(10)}`; CFG.invocation_id = uniqueInvocationId; } if (CFG.log_start_time !== "") { // validate input, let this blow up for now if input is invalid ZonedDateTime.parse(CFG.log_start_time); // In metrics mode, don't support this feature assert(!CFG.metrics_mode); } if ( CFG.cycle_stop_write_after_n_seconds !== 0 && CFG.cycle_stop_write_after_n_fragments !== 0 ) { log.error("Only one per-cycle write stop criterion must be defined"); process.exit(1); } if (CFG.change_series_every_n_cycles > CFG.n_cycles) { log.error( "--change-series-every-n-cycles must not be larger than --n-cycles" ); process.exit(1); } if (CFG.change_series_every_n_cycles < 0) { log.error("--change-series-every-n-cycles must not be negative"); process.exit(1); } // if ( // CFG.max_start_time_offset_minutes * 60 < // WALLTIME_COUPLING_PARAMS.minLagSeconds // ) { // log.error( // "--max-start-time-offset-minutes must not be smaller than " + // `WALLTIME_COUPLING_PARAMS.minLagSeconds (${WALLTIME_COUPLING_PARAMS.minLagSeconds})` // ); // process.exit(1); // } if (CFG.max_concurrent_writes > CFG.n_series) { log.error("--max-concurrent-writes must not be larger than --n-series"); process.exit(1); } if (CFG.cycle_stop_write_after_n_seconds_jitter) { if (CFG.cycle_stop_write_after_n_seconds === 0) { log.error( "--cycle-stop-write-after-n-seconds-jitter can only be used with --cycle-stop-write-after-n-seconds" ); process.exit(1); } if ( CFG.cycle_stop_write_after_n_seconds_jitter > CFG.cycle_stop_write_after_n_seconds ) { log.error( "--cycle-stop-write-after-n-seconds-jitter must be smaller than --cycle-stop-write-after-n-seconds" ); process.exit(1); } } // if (CFG.n_fragments_per_push_message > CFG.n_series) { // log.error( // "--n-fragments-per-push-message must not be larger than --n-series" // ); // process.exit(1); // } // Choose a good default for max_concurrent_writes: if (CFG.max_concurrent_writes === 0) { // Default to using at most 10 concurrent writers or less if n_series // is smaller. CFG.max_concurrent_writes = Math.min(10, CFG.n_series); } if ( CFG.n_fragments_per_push_message * CFG.max_concurrent_writes > CFG.n_series ) { log.error( `--n-fragments-per-push-message (${CFG.n_fragments_per_push_message}) ` + "multiplied with max_concurrent_writes " + `(${CFG.max_concurrent_writes}) = ${ CFG.n_fragments_per_push_message * CFG.max_concurrent_writes } ` + `must not be larger than --n-series (${CFG.n_series})` ); process.exit(1); } if (CFG.max_concurrent_reads === 0) { // Default to using at most 10 concurrent writers or less if n_series // is smaller. CFG.max_concurrent_reads = Math.min(10, CFG.n_series); } if (CFG.bearer_token_file !== "") { try { // Strip leading and trailing whitespace. Otherwise, for example a // trailing newline (as it's written by any sane editor like e.g. vim) // would result in an invalid file. BEARER_TOKEN = fs .readFileSync(CFG.bearer_token_file, { encoding: "utf8" }) .trim(); } catch (err: any) { log.error( "failed to read file %s: %s", CFG.bearer_token_file, err.message ); process.exit(1); } log.info( "authentication token read from --bearer-token-file `%s` (%s characters)", CFG.bearer_token_file, BEARER_TOKEN.length ); } if (CFG.retry_post_jitter <= 0 || CFG.retry_post_jitter >= 1) { log.error("--retry-post-jitter must be larger than 0 and smaller than 1"); process.exit(1); } if (CFG.skip_read && CFG.read_n_series_only !== 0) { // see above, can't easily be covered by the mutually_exclusive_group // technique; this here is a cheap but at least quite helpful validation. log.error("--skip-read must not be used with --read-n-series-only"); process.exit(1); } if (CFG.read_n_series_only > CFG.n_series) { log.error("--read-n-series-only must not be larger than --n-series"); process.exit(1); } log.info("rendered config:\n%s", JSON.stringify(CFG, null, 2)); }
the_stack
interface KnockoutSubscribableFunctions<T> { [key: string]: KnockoutBindingHandler | undefined; notifySubscribers(valueToWrite?: T, event?: string): void; } interface KnockoutComputedFunctions<T> { [key: string]: KnockoutBindingHandler | undefined; } interface KnockoutObservableFunctions<T> { [key: string]: KnockoutBindingHandler | undefined; equalityComparer(a: any, b: any): boolean; } interface KnockoutObservableArrayFunctions<T> { // General Array functions indexOf(searchElement: T, fromIndex?: number): number; slice(start: number, end?: number): T[]; splice(start: number): T[]; splice(start: number, deleteCount: number, ...items: T[]): T[]; pop(): T; push(...items: T[]): void; shift(): T; unshift(...items: T[]): number; reverse(): KnockoutObservableArray<T>; sort(): KnockoutObservableArray<T>; sort(compareFunction: (left: T, right: T) => number): KnockoutObservableArray<T>; // Ko specific [key: string]: KnockoutBindingHandler | undefined; replace(oldItem: T, newItem: T): void; remove(item: T): T[]; remove(removeFunction: (item: T) => boolean): T[]; removeAll(items: T[]): T[]; removeAll(): T[]; destroy(item: T): void; destroy(destroyFunction: (item: T) => boolean): void; destroyAll(items: T[]): void; destroyAll(): void; } interface KnockoutSubscribableStatic { fn: KnockoutSubscribableFunctions<any>; new <T>(): KnockoutSubscribable<T>; } interface KnockoutSubscription { dispose(): void; } interface KnockoutSubscribable<T> extends KnockoutSubscribableFunctions<T> { subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription; subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription; subscribe<TEvent>(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable<T>; getSubscriptionsCount(): number; } interface KnockoutComputedStatic { fn: KnockoutComputedFunctions<any>; <T>(): KnockoutComputed<T>; <T>(func: () => T, context?: any, options?: any): KnockoutComputed<T>; <T>(def: KnockoutComputedDefine<T>, context?: any): KnockoutComputed<T>; } interface KnockoutComputed<T> extends KnockoutObservable<T>, KnockoutComputedFunctions<T> { fn: KnockoutComputedFunctions<any>; dispose(): void; isActive(): boolean; getDependenciesCount(): number; extend(requestedExtenders: { [key: string]: any; }): KnockoutComputed<T>; } interface KnockoutObservableArrayStatic { fn: KnockoutObservableArrayFunctions<any>; <T>(value?: T[] | null): KnockoutObservableArray<T>; } interface KnockoutObservableArray<T> extends KnockoutObservable<T[]>, KnockoutObservableArrayFunctions<T> { subscribe(callback: (newValue: KnockoutArrayChange<T>[]) => void, target: any, event: "arrayChange"): KnockoutSubscription; subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription; subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription; subscribe<TEvent>(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray<T>; } interface KnockoutObservableStatic { fn: KnockoutObservableFunctions<any>; <T>(value?: T | null): KnockoutObservable<T>; } interface KnockoutObservable<T> extends KnockoutSubscribable<T>, KnockoutObservableFunctions<T> { (): T; (value: T | null): void; peek(): T; valueHasMutated?:{(): void;}; valueWillMutate?:{(): void;}; extend(requestedExtenders: { [key: string]: any; }): KnockoutObservable<T>; } interface KnockoutComputedDefine<T> { read(): T; write? (value: T): void; disposeWhenNodeIsRemoved?: Node; disposeWhen? (): boolean; owner?: any; deferEvaluation?: boolean; pure?: boolean; } interface KnockoutBindingContext { $parent: any; $parents: any[]; $root: any; $data: any; $rawData: any | KnockoutObservable<any>; $index?: KnockoutObservable<number>; $parentContext?: KnockoutBindingContext; $component: any; $componentTemplateNodes: Node[]; extend(properties: any): any; createChildContext(dataItemOrAccessor: any, dataItemAlias?: any, extendCallback?: Function): any; } interface KnockoutAllBindingsAccessor { (): any; get(name: string): any; has(name: string): boolean; } interface KnockoutBindingHandler { after?: Array<string>; init?: (element: any, valueAccessor: () => any, allBindingsAccessor?: KnockoutAllBindingsAccessor, viewModel?: any, bindingContext?: KnockoutBindingContext) => void | { controlsDescendantBindings: boolean; }; update?: (element: any, valueAccessor: () => any, allBindingsAccessor?: KnockoutAllBindingsAccessor, viewModel?: any, bindingContext?: KnockoutBindingContext) => void; options?: any; preprocess?: (value: string, name: string, addBindingCallback?: (name: string, value: string) => void) => string; } interface KnockoutBindingHandlers { [bindingHandler: string]: KnockoutBindingHandler; // Controlling text and appearance visible: KnockoutBindingHandler; text: KnockoutBindingHandler; html: KnockoutBindingHandler; css: KnockoutBindingHandler; style: KnockoutBindingHandler; attr: KnockoutBindingHandler; // Control Flow foreach: KnockoutBindingHandler; if: KnockoutBindingHandler; ifnot: KnockoutBindingHandler; with: KnockoutBindingHandler; // Working with form fields click: KnockoutBindingHandler; event: KnockoutBindingHandler; submit: KnockoutBindingHandler; enable: KnockoutBindingHandler; disable: KnockoutBindingHandler; value: KnockoutBindingHandler; textInput: KnockoutBindingHandler; hasfocus: KnockoutBindingHandler; checked: KnockoutBindingHandler; options: KnockoutBindingHandler; selectedOptions: KnockoutBindingHandler; uniqueName: KnockoutBindingHandler; // Rendering templates template: KnockoutBindingHandler; // Components (new for v3.2) component: KnockoutBindingHandler; } interface KnockoutMemoization { memoize(callback: () => string): string; unmemoize(memoId: string, callbackParams: any[]): boolean; unmemoizeDomNodeAndDescendants(domNode: any, extraCallbackParamsArray: any[]): boolean; parseMemoText(memoText: string): string; } interface KnockoutVirtualElement {} interface KnockoutVirtualElements { allowedBindings: { [bindingName: string]: boolean; }; emptyNode(node: KnockoutVirtualElement ): void; firstChild(node: KnockoutVirtualElement ): KnockoutVirtualElement; insertAfter( container: KnockoutVirtualElement, nodeToInsert: Node, insertAfter: Node ): void; nextSibling(node: KnockoutVirtualElement): Node; prepend(node: KnockoutVirtualElement, toInsert: Node ): void; setDomNodeChildren(node: KnockoutVirtualElement, newChildren: { length: number;[index: number]: Node; } ): void; childNodes(node: KnockoutVirtualElement ): Node[]; } interface KnockoutExtenders { throttle(target: any, timeout: number): KnockoutComputed<any>; notify(target: any, notifyWhen: string): any; rateLimit(target: any, timeout: number): any; rateLimit(target: any, options: { timeout: number; method?: string; }): any; trackArrayChanges(target: any): any; } // // NOTE TO MAINTAINERS AND CONTRIBUTORS : pay attention to only include symbols that are // publicly exported in the minified version of ko, without that you can give the false // impression that some functions will be available in production builds. // interface KnockoutUtils { ////////////////////////////////// // utils.domData.js ////////////////////////////////// domData: { get (node: Element, key: string): any; set (node: Element, key: string, value: any): void; getAll(node: Element, createIfNotFound: boolean): any; clear(node: Element): boolean; }; ////////////////////////////////// // utils.domNodeDisposal.js ////////////////////////////////// domNodeDisposal: { addDisposeCallback(node: Element, callback: Function): void; removeDisposeCallback(node: Element, callback: Function): void; cleanNode(node: Node): Element; removeNode(node: Node): void; }; addOrRemoveItem<T>(array: T[] | KnockoutObservable<T>, value: T, included: T): void; arrayFilter<T>(array: T[], predicate: (item: T) => boolean): T[]; arrayFirst<T>(array: T[], predicate: (item: T) => boolean, predicateOwner?: any): T; arrayForEach<T>(array: T[], action: (item: T, index: number) => void): void; arrayGetDistinctValues<T>(array: T[]): T[]; arrayIndexOf<T>(array: T[], item: T): number; arrayMap<T, U>(array: T[], mapping: (item: T) => U): U[]; arrayPushAll<T>(array: T[] | KnockoutObservableArray<T>, valuesToPush: T[]): T[]; arrayRemoveItem(array: any[], itemToRemove: any): void; compareArrays<T>(a: T[], b: T[]): Array<KnockoutArrayChange<T>>; extend(target: Object, source: Object): Object; fieldsIncludedWithJsonPost: any[]; getFormFields(form: any, fieldName: string): any[]; objectForEach(obj: any, action: (key: any, value: any) => void): void; parseHtmlFragment(html: string): any[]; parseJson(jsonString: string): any; postJson(urlOrForm: any, data: any, options: any): void; peekObservable<T>(value: KnockoutObservable<T>): T; range(min: any, max: any): any; registerEventHandler(element: any, eventType: any, handler: Function): void; setHtml(node: Element, html: () => string): void; setHtml(node: Element, html: string): void; setTextContent(element: any, textContent: string | KnockoutObservable<string>): void; stringifyJson(data: any, replacer?: Function, space?: string): string; toggleDomNodeCssClass(node: any, className: string, shouldHaveClass: boolean): void; triggerEvent(element: any, eventType: any): void; unwrapObservable<T>(value: KnockoutObservable<T> | T): T; // NOT PART OF THE MINIFIED API SURFACE (ONLY IN knockout-{version}.debug.js) https://github.com/SteveSanderson/knockout/issues/670 // forceRefresh(node: any): void; // ieVersion: number; // isIe6: boolean; // isIe7: boolean; // jQueryHtmlParse(html: string): any[]; // makeArray(arrayLikeObject: any): any[]; // moveCleanedNodesToContainerElement(nodes: any[]): HTMLElement; // replaceDomNodes(nodeToReplaceOrNodeArray: any, newNodesArray: any[]): void; // setDomNodeChildren(domNode: any, childNodes: any[]): void; // setElementName(element: any, name: string): void; // setOptionNodeSelectionState(optionNode: any, isSelected: boolean): void; // simpleHtmlParse(html: string): any[]; // stringStartsWith(str: string, startsWith: string): boolean; // stringTokenize(str: string, delimiter: string): string[]; // stringTrim(str: string): string; // tagNameLower(element: any): string; } interface KnockoutArrayChange<T> { status: "added" | "deleted" | "retained"; value: T; index: number; moved?: number; } ////////////////////////////////// // templateSources.js ////////////////////////////////// interface KnockoutTemplateSourcesDomElement { text(): any; text(value: any): void; data(key: string): any; data(key: string, value: any): any; } interface KnockoutTemplateAnonymous extends KnockoutTemplateSourcesDomElement { nodes(): any; nodes(value: any): void; } interface KnockoutTemplateSources { domElement: { prototype: KnockoutTemplateSourcesDomElement new (element: Element): KnockoutTemplateSourcesDomElement }; anonymousTemplate: { prototype: KnockoutTemplateAnonymous; new (element: Element): KnockoutTemplateAnonymous; }; } ////////////////////////////////// // nativeTemplateEngine.js ////////////////////////////////// interface KnockoutNativeTemplateEngine { renderTemplateSource(templateSource: Object, bindingContext?: KnockoutBindingContext, options?: Object): any[]; } ////////////////////////////////// // templateEngine.js ////////////////////////////////// interface KnockoutTemplateEngine extends KnockoutNativeTemplateEngine { createJavaScriptEvaluatorBlock(script: string): string; makeTemplateSource(template: any, templateDocument?: Document): any; renderTemplate(template: any, bindingContext: KnockoutBindingContext, options: Object, templateDocument: Document): any; isTemplateRewritten(template: any, templateDocument: Document): boolean; rewriteTemplate(template: any, rewriterCallback: Function, templateDocument: Document): void; } ////////////////////////////////// // tasks.js ////////////////////////////////// interface KnockoutTasks { scheduler: (callback: Function) => any; schedule(task: Function): number; cancel(handle: number): void; runEarly(): void; } ///////////////////////////////// interface KnockoutStatic { utils: KnockoutUtils; memoization: KnockoutMemoization; bindingHandlers: KnockoutBindingHandlers; getBindingHandler(handler: string): KnockoutBindingHandler; virtualElements: KnockoutVirtualElements; extenders: KnockoutExtenders; applyBindings(viewModelOrBindingContext?: any, rootNode?: any): void; applyBindingsToDescendants(viewModelOrBindingContext: any, rootNode: any): void; applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, bindingContext: KnockoutBindingContext): void; applyBindingAccessorsToNode(node: Node, bindings: {}, bindingContext: KnockoutBindingContext): void; applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, viewModel: any): void; applyBindingAccessorsToNode(node: Node, bindings: {}, viewModel: any): void; applyBindingsToNode(node: Node, bindings: any, viewModelOrBindingContext?: any): any; subscribable: KnockoutSubscribableStatic; observable: KnockoutObservableStatic; computed: KnockoutComputedStatic; pureComputed<T>(evaluatorFunction: () => T, context?: any): KnockoutComputed<T>; pureComputed<T>(options: KnockoutComputedDefine<T>, context?: any): KnockoutComputed<T>; observableArray: KnockoutObservableArrayStatic; contextFor(node: any): any; isSubscribable(instance: any): instance is KnockoutSubscribable<any>; toJSON(viewModel: any, replacer?: Function, space?: any): string; toJS(viewModel: any): any; isObservable(instance: any): instance is KnockoutObservable<any>; isWriteableObservable(instance: any): instance is KnockoutObservable<any>; isComputed(instance: any): instance is KnockoutComputed<any>; dataFor(node: any): any; removeNode(node: Element): void; cleanNode(node: Element): Element; renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any): any; renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any): any; unwrap<T>(value: KnockoutObservable<T> | T): T; computedContext: KnockoutComputedContext; ////////////////////////////////// // templateSources.js ////////////////////////////////// templateSources: KnockoutTemplateSources; ////////////////////////////////// // templateEngine.js ////////////////////////////////// templateEngine: { prototype: KnockoutTemplateEngine; new (): KnockoutTemplateEngine; }; ////////////////////////////////// // templateRewriting.js ////////////////////////////////// templateRewriting: { ensureTemplateIsRewritten(template: Node, templateEngine: KnockoutTemplateEngine, templateDocument: Document): any; ensureTemplateIsRewritten(template: string, templateEngine: KnockoutTemplateEngine, templateDocument: Document): any; memoizeBindingAttributeSyntax(htmlString: string, templateEngine: KnockoutTemplateEngine): any; applyMemoizedBindingsToNextSibling(bindings: any, nodeName: string): string; }; ////////////////////////////////// // nativeTemplateEngine.js ////////////////////////////////// nativeTemplateEngine: { prototype: KnockoutNativeTemplateEngine; new (): KnockoutNativeTemplateEngine; instance: KnockoutNativeTemplateEngine; }; ////////////////////////////////// // jqueryTmplTemplateEngine.js ////////////////////////////////// jqueryTmplTemplateEngine: { prototype: KnockoutTemplateEngine; renderTemplateSource(templateSource: Object, bindingContext: KnockoutBindingContext, options: Object): Node[]; createJavaScriptEvaluatorBlock(script: string): string; addTemplate(templateName: string, templateMarkup: string): void; }; ////////////////////////////////// // templating.js ////////////////////////////////// setTemplateEngine(templateEngine: KnockoutNativeTemplateEngine | undefined): void; renderTemplate(template: Function, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; renderTemplate(template: any, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; renderTemplate(template: Function, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; renderTemplate(template: any, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; renderTemplate(template: Function, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; renderTemplate(template: any, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; renderTemplate(template: Function, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; renderTemplate(template: any, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; renderTemplateForEach(template: Function, arrayOrObservableArray: any[], options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; renderTemplateForEach(template: any, arrayOrObservableArray: any[], options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; renderTemplateForEach(template: Function, arrayOrObservableArray: KnockoutObservable<any>, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; renderTemplateForEach(template: any, arrayOrObservableArray: KnockoutObservable<any>, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; ignoreDependencies<T>(callback: () => T): T; expressionRewriting: { bindingRewriteValidators: any[]; twoWayBindings: any; parseObjectLiteral: (objectLiteralString: string) => any[]; /** Internal, private KO utility for updating model properties from within bindings property: If the property being updated is (or might be) an observable, pass it here If it turns out to be a writable observable, it will be written to directly allBindings: An object with a get method to retrieve bindings in the current execution context. This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable (See note below) key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus' value: The value to be written checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if it is !== existing value on that writable observable Note that if you need to write to the viewModel without an observable property, you need to set ko.expressionRewriting.twoWayBindings[key] = true; *before* the binding evaluation. */ writeValueToProperty: (property: KnockoutObservable<any> | any, allBindings: KnockoutAllBindingsAccessor, key: string, value: any, checkIfDifferent?: boolean) => void; }; ///////////////////////////////// bindingProvider: { instance: KnockoutBindingProvider; new (): KnockoutBindingProvider; } ///////////////////////////////// // selectExtensions.js ///////////////////////////////// selectExtensions: { readValue(element: HTMLElement): any; writeValue(element: HTMLElement, value: any): void; }; components: KnockoutComponents; ///////////////////////////////// // options.js ///////////////////////////////// options: { deferUpdates: boolean, useOnlyNativeEvents: boolean }; ///////////////////////////////// // tasks.js ///////////////////////////////// tasks: KnockoutTasks; ///////////////////////////////// // utils.js ///////////////////////////////// onError?: (error: Error) => void; } interface KnockoutBindingProvider { nodeHasBindings(node: Node): boolean; getBindings(node: Node, bindingContext: KnockoutBindingContext): {}; getBindingAccessors?(node: Node, bindingContext: KnockoutBindingContext): { [key: string]: string; }; } interface KnockoutComputedContext { getDependenciesCount(): number; isInitial: () => boolean; isSleeping: boolean; } // // refactored types into a namespace to reduce global pollution // and used Union Types to simplify overloads (requires TypeScript 1.4) // declare namespace KnockoutComponentTypes { interface Config { viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule; template: string | Node[]| DocumentFragment | TemplateElement | AMDModule; synchronous?: boolean; } interface ComponentConfig { viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule; template: any; createViewModel?: any; } interface EmptyConfig { } // common AMD type interface AMDModule { require: string; } // viewmodel types interface ViewModelFunction { (params?: any): any; } interface ViewModelSharedInstance { instance: any; } interface ViewModelFactoryFunction { createViewModel: (params?: any, componentInfo?: ComponentInfo) => any; } interface ComponentInfo { element: Node; templateNodes: Node[]; } interface TemplateElement { element: string | Node; } interface Loader { getConfig? (componentName: string, callback: (result: ComponentConfig | null) => void): void; loadComponent? (componentName: string, config: ComponentConfig, callback: (result: Definition) => void): void; loadTemplate? (componentName: string, templateConfig: any, callback: (result: Node[]) => void): void; loadViewModel? (componentName: string, viewModelConfig: any, callback: (result: any) => void): void; suppressLoaderExceptions?: boolean; } interface Definition { template: Node[]; createViewModel? (params: any, options: { element: Node; }): any; } } interface KnockoutComponents { // overloads for register method: register(componentName: string, config: KnockoutComponentTypes.Config | KnockoutComponentTypes.EmptyConfig): void; isRegistered(componentName: string): boolean; unregister(componentName: string): void; get(componentName: string, callback: (definition: KnockoutComponentTypes.Definition) => void): void; clearCachedDefinition(componentName: string): void defaultLoader: KnockoutComponentTypes.Loader; loaders: KnockoutComponentTypes.Loader[]; getComponentNameForNode(node: Node): string; } declare var ko: KnockoutStatic; declare module "knockout" { export = ko; }
the_stack
import {BidiModule} from '@angular/cdk/bidi'; import { BACKSPACE, DOWN_ARROW, END, HOME, LEFT_ARROW, PAGE_DOWN, PAGE_UP, RIGHT_ARROW, UP_ARROW, A, } from '@angular/cdk/keycodes'; import { createMouseEvent, dispatchEvent, dispatchFakeEvent, dispatchKeyboardEvent, dispatchMouseEvent, createKeyboardEvent, createTouchEvent, } from '@angular/cdk/testing/private'; import {Component, DebugElement, Type, ViewChild} from '@angular/core'; import {ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing'; import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {By} from '@angular/platform-browser'; import {MatSlider, MatSliderModule} from './index'; describe('MatSlider', () => { function createComponent<T>(component: Type<T>): ComponentFixture<T> { TestBed.configureTestingModule({ imports: [MatSliderModule, ReactiveFormsModule, FormsModule, BidiModule], declarations: [component], }).compileComponents(); return TestBed.createComponent<T>(component); } describe('standard slider', () => { let fixture: ComponentFixture<StandardSlider>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let trackFillElement: HTMLElement; beforeEach(() => { fixture = createComponent(StandardSlider); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.componentInstance; trackFillElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-track-fill'); }); it('should set the default values', () => { expect(sliderInstance.value).toBe(0); expect(sliderInstance.min).toBe(0); expect(sliderInstance.max).toBe(100); }); it('should update the value on mousedown', () => { expect(sliderInstance.value).toBe(0); dispatchMousedownEventSequence(sliderNativeElement, 0.19); expect(sliderInstance.value).toBe(19); }); it('should not update when pressing the right mouse button', () => { expect(sliderInstance.value).toBe(0); dispatchMousedownEventSequence(sliderNativeElement, 0.19, 1); expect(sliderInstance.value).toBe(0); }); it('should update the value on a slide', () => { expect(sliderInstance.value).toBe(0); dispatchSlideEventSequence(sliderNativeElement, 0, 0.89); expect(sliderInstance.value).toBe(89); }); it('should set the value as min when sliding before the track', () => { expect(sliderInstance.value).toBe(0); dispatchSlideEventSequence(sliderNativeElement, 0, -1.33); expect(sliderInstance.value).toBe(0); }); it('should set the value as max when sliding past the track', () => { expect(sliderInstance.value).toBe(0); dispatchSlideEventSequence(sliderNativeElement, 0, 1.75); expect(sliderInstance.value).toBe(100); }); it('should update the track fill on mousedown', () => { expect(trackFillElement.style.transform).toContain('scale3d(0, 1, 1)'); dispatchMousedownEventSequence(sliderNativeElement, 0.39); fixture.detectChanges(); expect(trackFillElement.style.transform).toContain('scale3d(0.39, 1, 1)'); }); it('should hide the fill element at zero percent', () => { expect(trackFillElement.style.display).toBe('none'); dispatchMousedownEventSequence(sliderNativeElement, 0.39); fixture.detectChanges(); expect(trackFillElement.style.display).toBeFalsy(); }); it('should update the track fill on slide', () => { expect(trackFillElement.style.transform).toContain('scale3d(0, 1, 1)'); dispatchSlideEventSequence(sliderNativeElement, 0, 0.86); fixture.detectChanges(); expect(trackFillElement.style.transform).toContain('scale3d(0.86, 1, 1)'); }); it('should add and remove the mat-slider-sliding class when sliding', () => { expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); dispatchSlideStartEvent(sliderNativeElement, 0); fixture.detectChanges(); expect(sliderNativeElement.classList).toContain('mat-slider-sliding'); dispatchSlideEndEvent(sliderNativeElement, 0.34); fixture.detectChanges(); expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); }); it('should not interrupt sliding by pressing a key', () => { expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); dispatchSlideStartEvent(sliderNativeElement, 0); fixture.detectChanges(); expect(sliderNativeElement.classList).toContain('mat-slider-sliding'); // Any key code will do here. Use A since it isn't associated with other actions. dispatchKeyboardEvent(sliderNativeElement, 'keydown', A); fixture.detectChanges(); dispatchKeyboardEvent(sliderNativeElement, 'keyup', A); fixture.detectChanges(); expect(sliderNativeElement.classList).toContain('mat-slider-sliding'); dispatchSlideEndEvent(sliderNativeElement, 0.34); fixture.detectChanges(); expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); }); it('should stop dragging if the page loses focus', () => { const classlist = sliderNativeElement.classList; expect(classlist).not.toContain('mat-slider-sliding'); dispatchSlideStartEvent(sliderNativeElement, 0); fixture.detectChanges(); expect(classlist).toContain('mat-slider-sliding'); dispatchSlideEvent(sliderNativeElement, 0.34); fixture.detectChanges(); expect(classlist).toContain('mat-slider-sliding'); dispatchFakeEvent(window, 'blur'); fixture.detectChanges(); expect(classlist).not.toContain('mat-slider-sliding'); }); it('should reset active state upon blur', () => { sliderInstance._isActive = true; dispatchFakeEvent(sliderNativeElement, 'blur'); fixture.detectChanges(); expect(sliderInstance._isActive).toBe(false); }); it('should reset thumb gap when blurred on min value', () => { sliderInstance._isActive = true; sliderInstance.value = 0; fixture.detectChanges(); expect(sliderInstance._getThumbGap()).toBe(10); dispatchFakeEvent(sliderNativeElement, 'blur'); fixture.detectChanges(); expect(sliderInstance._getThumbGap()).toBe(7); }); it('should have thumb gap when at min value', () => { expect(trackFillElement.style.transform).toContain('translateX(-7px)'); }); it('should not have thumb gap when not at min value', () => { dispatchMousedownEventSequence(sliderNativeElement, 1); fixture.detectChanges(); // Some browsers use '0' and some use '0px', so leave off the closing paren. expect(trackFillElement.style.transform).toContain('translateX(0'); }); it('should have aria-orientation horizontal', () => { expect(sliderNativeElement.getAttribute('aria-orientation')).toEqual('horizontal'); }); it('should slide to the max value when the steps do not divide evenly into it', () => { sliderInstance.min = 5; sliderInstance.max = 100; sliderInstance.step = 15; dispatchSlideEventSequence(sliderNativeElement, 0, 1); fixture.detectChanges(); expect(sliderInstance.value).toBe(100); }); it('should prevent the default action of the `selectstart` event', () => { const event = dispatchFakeEvent(sliderNativeElement, 'selectstart'); fixture.detectChanges(); expect(event.defaultPrevented).toBe(true); }); it('should have a focus indicator', () => { expect(sliderNativeElement.classList.contains('mat-focus-indicator')).toBe(true); }); it('should not try to preventDefault on a non-cancelable event', () => { const event = createTouchEvent('touchstart'); const spy = spyOn(event, 'preventDefault'); Object.defineProperty(event, 'cancelable', {value: false}); dispatchEvent(sliderNativeElement, event); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); }); }); describe('disabled slider', () => { let fixture: ComponentFixture<StandardSlider>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let trackFillElement: HTMLElement; beforeEach(() => { fixture = createComponent(DisabledSlider); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.componentInstance; trackFillElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-track-fill'); }); it('should be disabled', () => { expect(sliderInstance.disabled).toBeTruthy(); }); it('should not change the value on mousedown when disabled', () => { expect(sliderInstance.value).toBe(0); dispatchMousedownEventSequence(sliderNativeElement, 0.63); expect(sliderInstance.value).toBe(0); }); it('should not change the value on slide when disabled', () => { expect(sliderInstance.value).toBe(0); dispatchSlideEventSequence(sliderNativeElement, 0, 0.5); expect(sliderInstance.value).toBe(0); }); it('should not emit change when disabled', () => { const onChangeSpy = jasmine.createSpy('slider onChange'); sliderInstance.change.subscribe(onChangeSpy); dispatchSlideEventSequence(sliderNativeElement, 0, 0.5); expect(onChangeSpy).toHaveBeenCalledTimes(0); }); it('should not add the mat-slider-active class on mousedown when disabled', () => { expect(sliderNativeElement.classList).not.toContain('mat-slider-active'); dispatchMousedownEventSequence(sliderNativeElement, 0.43); fixture.detectChanges(); expect(sliderNativeElement.classList).not.toContain('mat-slider-active'); }); it('should not add the mat-slider-sliding class on slide when disabled', () => { expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); dispatchSlideStartEvent(sliderNativeElement, 0.46); fixture.detectChanges(); expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); }); it('should leave thumb gap', () => { expect(trackFillElement.style.transform).toContain('translateX(-7px)'); }); it('should disable tabbing to the slider', () => { expect(sliderNativeElement.tabIndex).toBe(-1); }); }); describe('slider with set min and max', () => { let fixture: ComponentFixture<SliderWithMinAndMax>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let trackFillElement: HTMLElement; let ticksContainerElement: HTMLElement; let ticksElement: HTMLElement; let testComponent: SliderWithMinAndMax; beforeEach(() => { fixture = createComponent(SliderWithMinAndMax); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; testComponent = fixture.debugElement.componentInstance; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.injector.get<MatSlider>(MatSlider); trackFillElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-track-fill'); ticksContainerElement = <HTMLElement>( sliderNativeElement.querySelector('.mat-slider-ticks-container') ); ticksElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-ticks'); }); it('should set the default values from the attributes', () => { expect(sliderInstance.value).toBe(4); expect(sliderInstance.min).toBe(4); expect(sliderInstance.max).toBe(6); }); it('should set the correct value on mousedown', () => { dispatchMousedownEventSequence(sliderNativeElement, 0.09); fixture.detectChanges(); // Computed by multiplying the difference between the min and the max by the percentage from // the mousedown and adding that to the minimum. const value = Math.round(4 + 0.09 * (6 - 4)); expect(sliderInstance.value).toBe(value); }); it('should set the correct value on slide', () => { dispatchSlideEventSequence(sliderNativeElement, 0, 0.62); fixture.detectChanges(); // Computed by multiplying the difference between the min and the max by the percentage from // the mousedown and adding that to the minimum. const value = Math.round(4 + 0.62 * (6 - 4)); expect(sliderInstance.value).toBe(value); }); it('should snap the fill to the nearest value on mousedown', () => { dispatchMousedownEventSequence(sliderNativeElement, 0.68); fixture.detectChanges(); // The closest snap is halfway on the slider. expect(trackFillElement.style.transform).toContain('scale3d(0.5, 1, 1)'); }); it('should snap the fill to the nearest value on slide', () => { dispatchSlideEventSequence(sliderNativeElement, 0, 0.74); fixture.detectChanges(); // The closest snap is at the halfway point on the slider. expect(trackFillElement.style.transform).toContain('scale3d(0.5, 1, 1)'); }); it('should adjust fill and ticks on mouse enter when min changes', () => { testComponent.min = -2; fixture.detectChanges(); dispatchMouseenterEvent(sliderNativeElement); fixture.detectChanges(); expect(trackFillElement.style.transform).toContain('scale3d(0.75, 1, 1)'); expect(ticksElement.style.backgroundSize).toBe('75% 2px'); // Make sure it cuts off the last half tick interval. expect(ticksElement.style.transform).toContain('translateX(37.5%)'); expect(ticksContainerElement.style.transform).toBe('translateX(-37.5%)'); }); it('should adjust fill and ticks on mouse enter when max changes', () => { testComponent.min = -2; fixture.detectChanges(); testComponent.max = 10; fixture.detectChanges(); dispatchMouseenterEvent(sliderNativeElement); fixture.detectChanges(); expect(trackFillElement.style.transform).toContain('scale3d(0.5, 1, 1)'); expect(ticksElement.style.backgroundSize).toBe('50% 2px'); // Make sure it cuts off the last half tick interval. expect(ticksElement.style.transform).toContain('translateX(25%)'); expect(ticksContainerElement.style.transform).toBe('translateX(-25%)'); }); it( 'should be able to set the min and max values when they are more precise ' + 'than the step', () => { // Note that we assign min/max with more decimals than the // step to ensure that the value doesn't get rounded up. testComponent.step = 0.5; testComponent.min = 10.15; testComponent.max = 50.15; fixture.detectChanges(); dispatchSlideEventSequence(sliderNativeElement, 0.5, 0); fixture.detectChanges(); expect(sliderInstance.value).toBe(10.15); expect(sliderInstance.percent).toBe(0); dispatchSlideEventSequence(sliderNativeElement, 0.5, 1); fixture.detectChanges(); expect(sliderInstance.value).toBe(50.15); expect(sliderInstance.percent).toBe(1); }, ); it('should properly update ticks when max value changed to 0', () => { testComponent.min = 0; testComponent.max = 100; fixture.detectChanges(); dispatchMouseenterEvent(sliderNativeElement); fixture.detectChanges(); expect(ticksElement.style.backgroundSize).toBe('6% 2px'); expect(ticksElement.style.transform).toContain('translateX(3%)'); testComponent.max = 0; fixture.detectChanges(); dispatchMouseenterEvent(sliderNativeElement); fixture.detectChanges(); expect(ticksElement.style.backgroundSize).toBe('0% 2px'); expect(ticksElement.style.transform).toContain('translateX(0%)'); }); }); describe('slider with set value', () => { let fixture: ComponentFixture<SliderWithValue>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; beforeEach(() => { fixture = createComponent(SliderWithValue); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.injector.get<MatSlider>(MatSlider); }); it('should set the default value from the attribute', () => { expect(sliderInstance.value).toBe(26); }); it('should set the correct value on mousedown', () => { dispatchMousedownEventSequence(sliderNativeElement, 0.92); fixture.detectChanges(); // On a slider with default max and min the value should be approximately equal to the // percentage clicked. This should be the case regardless of what the original set value was. expect(sliderInstance.value).toBe(92); }); it('should set the correct value on slide', () => { dispatchSlideEventSequence(sliderNativeElement, 0, 0.32); fixture.detectChanges(); expect(sliderInstance.value).toBe(32); }); }); describe('slider with set step', () => { let fixture: ComponentFixture<SliderWithStep>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let trackFillElement: HTMLElement; beforeEach(() => { fixture = createComponent(SliderWithStep); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.injector.get<MatSlider>(MatSlider); trackFillElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-track-fill'); }); it('should set the correct step value on mousedown', () => { expect(sliderInstance.value).toBe(0); dispatchMousedownEventSequence(sliderNativeElement, 0.13); fixture.detectChanges(); expect(sliderInstance.value).toBe(25); }); it('should snap the fill to a step on mousedown', () => { dispatchMousedownEventSequence(sliderNativeElement, 0.66); fixture.detectChanges(); // The closest step is at 75% of the slider. expect(trackFillElement.style.transform).toContain('scale3d(0.75, 1, 1)'); }); it('should set the correct step value on slide', () => { dispatchSlideEventSequence(sliderNativeElement, 0, 0.07); fixture.detectChanges(); expect(sliderInstance.value).toBe(0); }); it('should snap the thumb and fill to a step on slide', () => { dispatchSlideEventSequence(sliderNativeElement, 0, 0.88); fixture.detectChanges(); // The closest snap is at the end of the slider. expect(trackFillElement.style.transform).toContain('scale3d(1, 1, 1)'); }); it('should not add decimals to the value if it is a whole number', () => { fixture.componentInstance.step = 0.1; fixture.detectChanges(); dispatchSlideEventSequence(sliderNativeElement, 0, 1); expect(sliderDebugElement.componentInstance.displayValue).toBe(100); }); it('should truncate long decimal values when using a decimal step', () => { fixture.componentInstance.step = 0.1; fixture.detectChanges(); dispatchSlideEventSequence(sliderNativeElement, 0, 0.333333); expect(sliderInstance.value).toBe(33); }); it('should truncate long decimal values when using a decimal step and the arrow keys', () => { fixture.componentInstance.step = 0.1; fixture.detectChanges(); for (let i = 0; i < 3; i++) { dispatchKeyboardEvent(sliderNativeElement, 'keydown', UP_ARROW); } expect(sliderInstance.value).toBe(0.3); }); it('should set the truncated value to the aria-valuetext', () => { fixture.componentInstance.step = 0.1; fixture.detectChanges(); dispatchSlideEventSequence(sliderNativeElement, 0, 0.333333); fixture.detectChanges(); expect(sliderNativeElement.getAttribute('aria-valuetext')).toBe('33'); }); it('should be able to override the aria-valuetext', () => { fixture.componentInstance.step = 0.1; fixture.componentInstance.valueText = 'custom'; fixture.detectChanges(); dispatchSlideEventSequence(sliderNativeElement, 0, 0.333333); fixture.detectChanges(); expect(sliderNativeElement.getAttribute('aria-valuetext')).toBe('custom'); }); it('should be able to clear aria-valuetext', () => { fixture.componentInstance.valueText = ''; fixture.detectChanges(); dispatchSlideEventSequence(sliderNativeElement, 0, 0.333333); fixture.detectChanges(); expect(sliderNativeElement.getAttribute('aria-valuetext')).toBeFalsy(); }); }); describe('slider with auto ticks', () => { let fixture: ComponentFixture<SliderWithAutoTickInterval>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let ticksContainerElement: HTMLElement; let ticksElement: HTMLElement; beforeEach(() => { fixture = createComponent(SliderWithAutoTickInterval); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; ticksContainerElement = <HTMLElement>( sliderNativeElement.querySelector('.mat-slider-ticks-container') ); ticksElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-ticks'); }); it('should set the correct tick separation on mouse enter', () => { dispatchMouseenterEvent(sliderNativeElement); fixture.detectChanges(); // Ticks should be 30px apart (therefore 30% for a 100px long slider). expect(ticksElement.style.backgroundSize).toBe('30% 2px'); // Make sure it cuts off the last half tick interval. expect(ticksElement.style.transform).toContain('translateX(15%)'); expect(ticksContainerElement.style.transform).toBe('translateX(-15%)'); }); }); describe('slider with set tick interval', () => { let fixture: ComponentFixture<SliderWithSetTickInterval>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let ticksContainerElement: HTMLElement; let ticksElement: HTMLElement; beforeEach(() => { fixture = createComponent(SliderWithSetTickInterval); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; ticksContainerElement = <HTMLElement>( sliderNativeElement.querySelector('.mat-slider-ticks-container') ); ticksElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-ticks'); }); it('should set the correct tick separation on mouse enter', () => { dispatchMouseenterEvent(sliderNativeElement); fixture.detectChanges(); // Ticks should be every 18 values (tickInterval of 6 * step size of 3). On a slider 100px // long with 100 values, this is 18%. expect(ticksElement.style.backgroundSize).toBe('18% 2px'); // Make sure it cuts off the last half tick interval. expect(ticksElement.style.transform).toContain('translateX(9%)'); expect(ticksContainerElement.style.transform).toBe('translateX(-9%)'); }); it('should be able to reset the tick interval after it has been set', () => { expect(sliderNativeElement.classList) .withContext('Expected element to have ticks initially.') .toContain('mat-slider-has-ticks'); fixture.componentInstance.tickInterval = 0; fixture.detectChanges(); expect(sliderNativeElement.classList).not.toContain( 'mat-slider-has-ticks', 'Expected element not to have ticks after reset.', ); }); }); describe('slider with thumb label', () => { let fixture: ComponentFixture<SliderWithThumbLabel>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let thumbLabelTextElement: Element; beforeEach(() => { fixture = createComponent(SliderWithThumbLabel); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.componentInstance; thumbLabelTextElement = sliderNativeElement.querySelector('.mat-slider-thumb-label-text')!; }); it('should add the thumb label class to the slider container', () => { expect(sliderNativeElement.classList).toContain('mat-slider-thumb-label-showing'); }); it('should update the thumb label text on mousedown', () => { expect(thumbLabelTextElement.textContent).toBe('0'); dispatchMousedownEventSequence(sliderNativeElement, 0.13); fixture.detectChanges(); // The thumb label text is set to the slider's value. These should always be the same. expect(thumbLabelTextElement.textContent).toBe('13'); }); it('should update the thumb label text on slide', () => { expect(thumbLabelTextElement.textContent).toBe('0'); dispatchSlideEventSequence(sliderNativeElement, 0, 0.56); fixture.detectChanges(); // The thumb label text is set to the slider's value. These should always be the same. expect(thumbLabelTextElement.textContent).toBe(`${sliderInstance.value}`); }); }); describe('slider with custom thumb label formatting', () => { let fixture: ComponentFixture<SliderWithCustomThumbLabelFormatting>; let sliderInstance: MatSlider; let thumbLabelTextElement: Element; beforeEach(() => { fixture = createComponent(SliderWithCustomThumbLabelFormatting); fixture.detectChanges(); const sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; const sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.componentInstance; thumbLabelTextElement = sliderNativeElement.querySelector('.mat-slider-thumb-label-text')!; }); it('should invoke the passed-in `displayWith` function with the value', () => { spyOn(fixture.componentInstance, 'displayWith').and.callThrough(); sliderInstance.value = 1337; fixture.detectChanges(); expect(fixture.componentInstance.displayWith).toHaveBeenCalledWith(1337); }); it('should format the thumb label based on the passed-in `displayWith` function', () => { sliderInstance.value = 200000; fixture.detectChanges(); expect(thumbLabelTextElement.textContent).toBe('200k'); }); }); describe('slider with value property binding', () => { let fixture: ComponentFixture<SliderWithOneWayBinding>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let testComponent: SliderWithOneWayBinding; let trackFillElement: HTMLElement; beforeEach(() => { fixture = createComponent(SliderWithOneWayBinding); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.injector.get<MatSlider>(MatSlider); trackFillElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-track-fill'); }); it('should initialize based on bound value', () => { expect(sliderInstance.value).toBe(50); expect(trackFillElement.style.transform).toContain('scale3d(0.5, 1, 1)'); }); it('should update when bound value changes', () => { testComponent.val = 75; fixture.detectChanges(); expect(sliderInstance.value).toBe(75); expect(trackFillElement.style.transform).toContain('scale3d(0.75, 1, 1)'); }); }); describe('slider with set min and max and a value smaller than min', () => { let fixture: ComponentFixture<SliderWithValueSmallerThanMin>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let trackFillElement: HTMLElement; beforeEach(() => { fixture = createComponent(SliderWithValueSmallerThanMin); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.componentInstance; trackFillElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-track-fill'); }); it('should set the value smaller than the min value', () => { expect(sliderInstance.value).toBe(3); expect(sliderInstance.min).toBe(4); expect(sliderInstance.max).toBe(6); }); it('should set the fill to the min value', () => { expect(trackFillElement.style.transform).toContain('scale3d(0, 1, 1)'); }); }); describe('slider with set min and max and a value greater than max', () => { let fixture: ComponentFixture<SliderWithValueSmallerThanMin>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let trackFillElement: HTMLElement; beforeEach(() => { fixture = createComponent(SliderWithValueGreaterThanMax); fixture.detectChanges(); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.componentInstance; trackFillElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-track-fill'); }); it('should set the value greater than the max value', () => { expect(sliderInstance.value).toBe(7); expect(sliderInstance.min).toBe(4); expect(sliderInstance.max).toBe(6); }); it('should set the fill to the max value', () => { expect(trackFillElement.style.transform).toContain('scale3d(1, 1, 1)'); }); }); describe('slider with change handler', () => { let fixture: ComponentFixture<SliderWithChangeHandler>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let testComponent: SliderWithChangeHandler; beforeEach(() => { fixture = createComponent(SliderWithChangeHandler); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; spyOn(testComponent, 'onChange'); spyOn(testComponent, 'onInput'); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; }); it('should emit change on mouseup', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchMousedownEventSequence(sliderNativeElement, 0.2); fixture.detectChanges(); dispatchSlideEndEvent(sliderNativeElement, 0.2); expect(testComponent.onChange).toHaveBeenCalledTimes(1); }); it('should emit change on slide', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchSlideEventSequence(sliderNativeElement, 0, 0.4); fixture.detectChanges(); expect(testComponent.onChange).toHaveBeenCalledTimes(1); }); it('should not emit multiple changes for the same value', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchMousedownEventSequence(sliderNativeElement, 0.6); dispatchSlideEventSequence(sliderNativeElement, 0.6, 0.6); fixture.detectChanges(); expect(testComponent.onChange).toHaveBeenCalledTimes(1); }); it( 'should dispatch events when changing back to previously emitted value after ' + 'programmatically setting value', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); expect(testComponent.onInput).not.toHaveBeenCalled(); dispatchMousedownEventSequence(sliderNativeElement, 0.2); fixture.detectChanges(); expect(testComponent.onChange).not.toHaveBeenCalled(); expect(testComponent.onInput).toHaveBeenCalledTimes(1); dispatchSlideEndEvent(sliderNativeElement, 0.2); fixture.detectChanges(); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(testComponent.onInput).toHaveBeenCalledTimes(1); testComponent.slider.value = 0; fixture.detectChanges(); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(testComponent.onInput).toHaveBeenCalledTimes(1); dispatchMousedownEventSequence(sliderNativeElement, 0.2); fixture.detectChanges(); dispatchSlideEndEvent(sliderNativeElement, 0.2); expect(testComponent.onChange).toHaveBeenCalledTimes(2); expect(testComponent.onInput).toHaveBeenCalledTimes(2); }, ); }); describe('slider with input event', () => { let fixture: ComponentFixture<SliderWithChangeHandler>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let testComponent: SliderWithChangeHandler; beforeEach(() => { fixture = createComponent(SliderWithChangeHandler); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; spyOn(testComponent, 'onInput'); spyOn(testComponent, 'onChange'); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; }); it('should emit an input event while sliding', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchMouseenterEvent(sliderNativeElement); dispatchSlideStartEvent(sliderNativeElement, 0); dispatchSlideEvent(sliderNativeElement, 0.5); dispatchSlideEvent(sliderNativeElement, 1); dispatchSlideEndEvent(sliderNativeElement, 1); fixture.detectChanges(); // The input event should fire twice, because the slider changed two times. expect(testComponent.onInput).toHaveBeenCalledTimes(2); expect(testComponent.onChange).toHaveBeenCalledTimes(1); }); it('should emit an input event when clicking', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchMousedownEventSequence(sliderNativeElement, 0.75); fixture.detectChanges(); dispatchSlideEndEvent(sliderNativeElement, 0.75); // The `onInput` event should be emitted once due to a single click. expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); }); }); describe('keyboard support', () => { let fixture: ComponentFixture<SliderWithChangeHandler>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let testComponent: SliderWithChangeHandler; let sliderInstance: MatSlider; let trackFillElement: HTMLElement; beforeEach(() => { fixture = createComponent(SliderWithChangeHandler); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; spyOn(testComponent, 'onInput'); spyOn(testComponent, 'onChange'); sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.injector.get<MatSlider>(MatSlider); trackFillElement = sliderNativeElement.querySelector('.mat-slider-track-fill') as HTMLElement; }); it('should increment slider by 1 on up arrow pressed', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', UP_ARROW); fixture.detectChanges(); // The `onInput` event should be emitted once due to a single keyboard press. expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(sliderInstance.value).toBe(1); }); it('should increment slider by 1 on right arrow pressed', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', RIGHT_ARROW); fixture.detectChanges(); // The `onInput` event should be emitted once due to a single keyboard press. expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(sliderInstance.value).toBe(1); }); it('should decrement slider by 1 on down arrow pressed', () => { sliderInstance.value = 100; expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', DOWN_ARROW); fixture.detectChanges(); // The `onInput` event should be emitted once due to a single keyboard press. expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(sliderInstance.value).toBe(99); }); it('should decrement slider by 1 on left arrow pressed', () => { sliderInstance.value = 100; expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', LEFT_ARROW); fixture.detectChanges(); // The `onInput` event should be emitted once due to a single keyboard press. expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(sliderInstance.value).toBe(99); }); it('should decrement from max when interacting after out-of-bounds value is assigned', () => { sliderInstance.max = 100; sliderInstance.value = 200; fixture.detectChanges(); expect(sliderInstance.value).toBe(200); expect(trackFillElement.style.transform).toContain('scale3d(1, 1, 1)'); dispatchKeyboardEvent(sliderNativeElement, 'keydown', LEFT_ARROW); fixture.detectChanges(); expect(sliderInstance.value).toBe(99); expect(trackFillElement.style.transform).toContain('scale3d(0.99, 1, 1)'); }); it('should increment slider by 10 on page up pressed', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', PAGE_UP); fixture.detectChanges(); // The `onInput` event should be emitted once due to a single keyboard press. expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(sliderInstance.value).toBe(10); }); it('should decrement slider by 10 on page down pressed', () => { sliderInstance.value = 100; expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', PAGE_DOWN); fixture.detectChanges(); // The `onInput` event should be emitted once due to a single keyboard press. expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(sliderInstance.value).toBe(90); }); it('should set slider to max on end pressed', () => { expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', END); fixture.detectChanges(); // The `onInput` event should be emitted once due to a single keyboard press. expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(sliderInstance.value).toBe(100); }); it('should set slider to min on home pressed', () => { sliderInstance.value = 100; expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', HOME); fixture.detectChanges(); // The `onInput` event should be emitted once due to a single keyboard press. expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); expect(sliderInstance.value).toBe(0); }); it(`should take no action for presses of keys it doesn't care about`, () => { sliderInstance.value = 50; expect(testComponent.onChange).not.toHaveBeenCalled(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', BACKSPACE); fixture.detectChanges(); // The `onInput` event should be emitted once due to a single keyboard press. expect(testComponent.onInput).not.toHaveBeenCalled(); expect(testComponent.onChange).not.toHaveBeenCalled(); expect(sliderInstance.value).toBe(50); }); it('should ignore events modifier keys', () => { sliderInstance.value = 0; [UP_ARROW, DOWN_ARROW, RIGHT_ARROW, LEFT_ARROW, PAGE_DOWN, PAGE_UP, HOME, END].forEach( key => { const event = createKeyboardEvent('keydown', key, undefined, {alt: true}); dispatchEvent(sliderNativeElement, event); fixture.detectChanges(); expect(event.defaultPrevented).toBe(false); }, ); expect(testComponent.onInput).not.toHaveBeenCalled(); expect(testComponent.onChange).not.toHaveBeenCalled(); expect(sliderInstance.value).toBe(0); }); }); describe('slider with direction and invert', () => { let fixture: ComponentFixture<SliderWithDirAndInvert>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let testComponent: SliderWithDirAndInvert; beforeEach(() => { fixture = createComponent(SliderWithDirAndInvert); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderInstance = sliderDebugElement.injector.get<MatSlider>(MatSlider); sliderNativeElement = sliderDebugElement.nativeElement; }); it('works in inverted mode', () => { testComponent.invert = true; fixture.detectChanges(); dispatchMousedownEventSequence(sliderNativeElement, 0.3); fixture.detectChanges(); expect(sliderInstance.value).toBe(70); }); it('works in RTL languages', () => { testComponent.dir = 'rtl'; fixture.detectChanges(); dispatchMousedownEventSequence(sliderNativeElement, 0.3); fixture.detectChanges(); expect(sliderInstance.value).toBe(70); }); it('works in RTL languages in inverted mode', () => { testComponent.dir = 'rtl'; testComponent.invert = true; fixture.detectChanges(); dispatchMousedownEventSequence(sliderNativeElement, 0.3); fixture.detectChanges(); expect(sliderInstance.value).toBe(30); }); it('should re-render slider with updated style upon directionality change', () => { testComponent.dir = 'rtl'; fixture.detectChanges(); const initialTrackFillStyles = sliderInstance._getTrackFillStyles(); const initialTicksContainerStyles = sliderInstance._getTicksContainerStyles(); const initialTicksStyles = sliderInstance._getTicksStyles(); const initialThumbContainerStyles = sliderInstance._getThumbContainerStyles(); testComponent.dir = 'ltr'; fixture.detectChanges(); expect(initialTrackFillStyles).not.toEqual(sliderInstance._getTrackFillStyles()); expect(initialTicksContainerStyles).not.toEqual(sliderInstance._getTicksContainerStyles()); expect(initialTicksStyles).not.toEqual(sliderInstance._getTicksStyles()); expect(initialThumbContainerStyles).not.toEqual(sliderInstance._getThumbContainerStyles()); }); it('should increment inverted slider by 1 on right arrow pressed', () => { testComponent.invert = true; fixture.detectChanges(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', RIGHT_ARROW); fixture.detectChanges(); expect(sliderInstance.value).toBe(1); }); it('should decrement inverted slider by 1 on left arrow pressed', () => { testComponent.invert = true; sliderInstance.value = 100; fixture.detectChanges(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', LEFT_ARROW); fixture.detectChanges(); expect(sliderInstance.value).toBe(99); }); it('should decrement RTL slider by 1 on right arrow pressed', () => { testComponent.dir = 'rtl'; sliderInstance.value = 100; fixture.detectChanges(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', RIGHT_ARROW); fixture.detectChanges(); expect(sliderInstance.value).toBe(99); }); it('should increment RTL slider by 1 on left arrow pressed', () => { testComponent.dir = 'rtl'; fixture.detectChanges(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', LEFT_ARROW); fixture.detectChanges(); expect(sliderInstance.value).toBe(1); }); it('should decrement inverted RTL slider by 1 on right arrow pressed', () => { testComponent.dir = 'rtl'; testComponent.invert = true; sliderInstance.value = 100; fixture.detectChanges(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', RIGHT_ARROW); fixture.detectChanges(); expect(sliderInstance.value).toBe(99); }); it('should increment inverted RTL slider by 1 on left arrow pressed', () => { testComponent.dir = 'rtl'; testComponent.invert = true; fixture.detectChanges(); dispatchKeyboardEvent(sliderNativeElement, 'keydown', LEFT_ARROW); fixture.detectChanges(); expect(sliderInstance.value).toBe(1); }); it('should hide last tick when inverted and at min value', () => { testComponent.invert = true; fixture.detectChanges(); expect(sliderNativeElement.classList.contains('mat-slider-hide-last-tick')) .withContext('last tick should be hidden') .toBe(true); }); }); describe('vertical slider', () => { let fixture: ComponentFixture<VerticalSlider>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let trackFillElement: HTMLElement; let sliderInstance: MatSlider; let testComponent: VerticalSlider; beforeEach(() => { fixture = createComponent(VerticalSlider); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderInstance = sliderDebugElement.injector.get<MatSlider>(MatSlider); sliderNativeElement = sliderDebugElement.nativeElement; trackFillElement = <HTMLElement>sliderNativeElement.querySelector('.mat-slider-track-fill'); }); it('updates value on mousedown', () => { dispatchMousedownEventSequence(sliderNativeElement, 0.3); fixture.detectChanges(); expect(sliderInstance.value).toBe(70); }); it('updates value on mousedown in inverted mode', () => { testComponent.invert = true; fixture.detectChanges(); dispatchMousedownEventSequence(sliderNativeElement, 0.3); fixture.detectChanges(); expect(sliderInstance.value).toBe(30); }); it('should update the track fill on mousedown', () => { expect(trackFillElement.style.transform).toContain('scale3d(1, 0, 1)'); dispatchMousedownEventSequence(sliderNativeElement, 0.39); fixture.detectChanges(); expect(trackFillElement.style.transform).toContain('scale3d(1, 0.61, 1)'); }); it('should update the track fill on mousedown in inverted mode', () => { testComponent.invert = true; fixture.detectChanges(); expect(trackFillElement.style.transform).toContain('scale3d(1, 0, 1)'); dispatchMousedownEventSequence(sliderNativeElement, 0.39); fixture.detectChanges(); expect(trackFillElement.style.transform).toContain('scale3d(1, 0.39, 1)'); }); it('should have aria-orientation vertical', () => { expect(sliderNativeElement.getAttribute('aria-orientation')).toEqual('vertical'); }); }); describe('tabindex', () => { it('should allow setting the tabIndex through binding', () => { const fixture = createComponent(SliderWithTabIndexBinding); fixture.detectChanges(); const slider = fixture.debugElement.query(By.directive(MatSlider))!.componentInstance; expect(slider.tabIndex) .withContext('Expected the tabIndex to be set to 0 by default.') .toBe(0); fixture.componentInstance.tabIndex = 3; fixture.detectChanges(); expect(slider.tabIndex).withContext('Expected the tabIndex to have been changed.').toBe(3); }); it('should detect the native tabindex attribute', () => { const fixture = createComponent(SliderWithNativeTabindexAttr); fixture.detectChanges(); const slider = fixture.debugElement.query(By.directive(MatSlider))!.componentInstance; expect(slider.tabIndex) .withContext('Expected the tabIndex to be set to the value of the native attribute.') .toBe(5); }); }); describe('slider with ngModel', () => { let fixture: ComponentFixture<SliderWithNgModel>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let testComponent: SliderWithNgModel; beforeEach(() => { fixture = createComponent(SliderWithNgModel); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; }); it('should update the model on mouseup', () => { expect(testComponent.val).toBe(0); dispatchMousedownEventSequence(sliderNativeElement, 0.76); fixture.detectChanges(); dispatchSlideEndEvent(sliderNativeElement, 0.76); expect(testComponent.val).toBe(76); }); it('should update the model on slide', () => { expect(testComponent.val).toBe(0); dispatchSlideEventSequence(sliderNativeElement, 0, 0.19); fixture.detectChanges(); expect(testComponent.val).toBe(19); }); it('should update the model on keydown', () => { expect(testComponent.val).toBe(0); dispatchKeyboardEvent(sliderNativeElement, 'keydown', UP_ARROW); fixture.detectChanges(); expect(testComponent.val).toBe(1); }); it('should be able to reset a slider by setting the model back to undefined', fakeAsync(() => { expect(testComponent.slider.value).toBe(0); testComponent.val = 5; fixture.detectChanges(); flush(); expect(testComponent.slider.value).toBe(5); testComponent.val = undefined; fixture.detectChanges(); flush(); expect(testComponent.slider.value).toBe(0); })); }); describe('slider as a custom form control', () => { let fixture: ComponentFixture<SliderWithFormControl>; let sliderDebugElement: DebugElement; let sliderNativeElement: HTMLElement; let sliderInstance: MatSlider; let testComponent: SliderWithFormControl; beforeEach(() => { fixture = createComponent(SliderWithFormControl); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.injector.get<MatSlider>(MatSlider); }); it('should not update the control when the value is updated', () => { expect(testComponent.control.value).toBe(0); sliderInstance.value = 11; fixture.detectChanges(); expect(testComponent.control.value).toBe(0); }); it('should update the control on mouseup', () => { expect(testComponent.control.value).toBe(0); dispatchMousedownEventSequence(sliderNativeElement, 0.76); fixture.detectChanges(); dispatchSlideEndEvent(sliderNativeElement, 0.76); expect(testComponent.control.value).toBe(76); }); it('should update the control on slide', () => { expect(testComponent.control.value).toBe(0); dispatchSlideEventSequence(sliderNativeElement, 0, 0.19); fixture.detectChanges(); expect(testComponent.control.value).toBe(19); }); it('should update the value when the control is set', () => { expect(sliderInstance.value).toBe(0); testComponent.control.setValue(7); fixture.detectChanges(); expect(sliderInstance.value).toBe(7); }); it('should update the disabled state when control is disabled', () => { expect(sliderInstance.disabled).toBe(false); testComponent.control.disable(); fixture.detectChanges(); expect(sliderInstance.disabled).toBe(true); }); it('should update the disabled state when the control is enabled', () => { sliderInstance.disabled = true; testComponent.control.enable(); fixture.detectChanges(); expect(sliderInstance.disabled).toBe(false); }); it('should have the correct control state initially and after interaction', () => { const sliderControl = testComponent.control; // The control should start off valid, pristine, and untouched. expect(sliderControl.valid).toBe(true); expect(sliderControl.pristine).toBe(true); expect(sliderControl.touched).toBe(false); // After changing the value, the control should become dirty (not pristine), // but remain untouched. dispatchMousedownEventSequence(sliderNativeElement, 0.5); fixture.detectChanges(); dispatchSlideEndEvent(sliderNativeElement, 0.5); expect(sliderControl.valid).toBe(true); expect(sliderControl.pristine).toBe(false); expect(sliderControl.touched).toBe(false); // If the control has been visited due to interaction, the control should remain // dirty and now also be touched. sliderInstance._onBlur(); fixture.detectChanges(); expect(sliderControl.valid).toBe(true); expect(sliderControl.pristine).toBe(false); expect(sliderControl.touched).toBe(true); }); }); describe('slider with a two-way binding', () => { let fixture: ComponentFixture<SliderWithTwoWayBinding>; let testComponent: SliderWithTwoWayBinding; let sliderNativeElement: HTMLElement; beforeEach(() => { fixture = createComponent(SliderWithTwoWayBinding); fixture.detectChanges(); testComponent = fixture.componentInstance; let sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; }); it('should sync the value binding in both directions', () => { expect(testComponent.value).toBe(0); expect(testComponent.slider.value).toBe(0); dispatchMousedownEventSequence(sliderNativeElement, 0.1); fixture.detectChanges(); dispatchSlideEndEvent(sliderNativeElement, 0.1); expect(testComponent.value).toBe(10); expect(testComponent.slider.value).toBe(10); testComponent.value = 20; fixture.detectChanges(); expect(testComponent.value).toBe(20); expect(testComponent.slider.value).toBe(20); }); }); }); // Disable animations and make the slider an even 100px (+ 8px padding on either side) // so we get nice round values in tests. const styles = ` .mat-slider-horizontal { min-width: 116px !important; } .mat-slider-vertical { min-height: 116px !important; } .mat-slider-track-fill { transition: none !important; } `; @Component({ template: `<mat-slider></mat-slider>`, styles: [styles], }) class StandardSlider {} @Component({ template: `<mat-slider disabled></mat-slider>`, styles: [styles], }) class DisabledSlider {} @Component({ template: `<mat-slider [min]="min" [max]="max" [step]="step" tickInterval="6"></mat-slider>`, styles: [styles], }) class SliderWithMinAndMax { min = 4; max = 6; step = 1; } @Component({ template: `<mat-slider value="26"></mat-slider>`, styles: [styles], }) class SliderWithValue {} @Component({ template: `<mat-slider [step]="step" [valueText]="valueText"></mat-slider>`, styles: [styles], }) class SliderWithStep { step = 25; valueText: string; } @Component({ template: `<mat-slider step="5" tickInterval="auto"></mat-slider>`, styles: [styles], }) class SliderWithAutoTickInterval {} @Component({ template: `<mat-slider step="3" [tickInterval]="tickInterval"></mat-slider>`, styles: [styles], }) class SliderWithSetTickInterval { tickInterval = 6; } @Component({ template: `<mat-slider thumbLabel></mat-slider>`, styles: [styles], }) class SliderWithThumbLabel {} @Component({ template: `<mat-slider min="1" max="100000" [displayWith]="displayWith" thumbLabel></mat-slider>`, styles: [styles], }) class SliderWithCustomThumbLabelFormatting { displayWith(value: number) { if (value >= 1000) { return value / 1000 + 'k'; } return value; } } @Component({ template: `<mat-slider [value]="val"></mat-slider>`, styles: [styles], }) class SliderWithOneWayBinding { val = 50; } @Component({ template: `<mat-slider [formControl]="control"></mat-slider>`, styles: [styles], }) class SliderWithFormControl { control = new FormControl(0); } @Component({ template: `<mat-slider [(ngModel)]="val"></mat-slider>`, styles: [styles], }) class SliderWithNgModel { @ViewChild(MatSlider) slider: MatSlider; val: number | undefined = 0; } @Component({ template: `<mat-slider value="3" min="4" max="6"></mat-slider>`, styles: [styles], }) class SliderWithValueSmallerThanMin {} @Component({ template: `<mat-slider value="7" min="4" max="6"></mat-slider>`, styles: [styles], }) class SliderWithValueGreaterThanMax {} @Component({ template: `<mat-slider (change)="onChange($event)" (input)="onInput($event)"></mat-slider>`, styles: [styles], }) class SliderWithChangeHandler { onChange() {} onInput() {} @ViewChild(MatSlider) slider: MatSlider; } @Component({ template: `<div [dir]="dir"><mat-slider [invert]="invert" tickInterval="5"></mat-slider></div>`, styles: [styles], }) class SliderWithDirAndInvert { dir = 'ltr'; invert = false; } @Component({ template: `<mat-slider vertical [invert]="invert"></mat-slider>`, styles: [styles], }) class VerticalSlider { invert = false; } @Component({ template: `<mat-slider [tabIndex]="tabIndex"></mat-slider>`, styles: [styles], }) class SliderWithTabIndexBinding { tabIndex: number; } @Component({ template: `<mat-slider tabindex="5"></mat-slider>`, styles: [styles], }) class SliderWithNativeTabindexAttr { tabIndex: number; } @Component({ template: '<mat-slider [(value)]="value"></mat-slider>', styles: [styles], }) class SliderWithTwoWayBinding { @ViewChild(MatSlider) slider: MatSlider; value = 0; } /** * Dispatches a mousedown event sequence (consisting of moueseenter, mousedown) from an element. * Note: The mouse event truncates the position for the event. * @param sliderElement The mat-slider element from which the event will be dispatched. * @param percentage The percentage of the slider where the event should occur. Used to find the * physical location of the pointer. * @param button Button that should be held down when starting to drag the slider. */ function dispatchMousedownEventSequence( sliderElement: HTMLElement, percentage: number, button = 0, ): void { const trackElement = sliderElement.querySelector('.mat-slider-wrapper')!; const dimensions = trackElement.getBoundingClientRect(); const x = dimensions.left + dimensions.width * percentage; const y = dimensions.top + dimensions.height * percentage; dispatchMouseenterEvent(sliderElement); dispatchEvent(sliderElement, createMouseEvent('mousedown', x, y, undefined, undefined, button)); } /** * Dispatches a slide event sequence (consisting of slidestart, slide, slideend) from an element. * @param sliderElement The mat-slider element from which the event will be dispatched. * @param startPercent The percentage of the slider where the slide will begin. * @param endPercent The percentage of the slider where the slide will end. */ function dispatchSlideEventSequence( sliderElement: HTMLElement, startPercent: number, endPercent: number, ): void { dispatchMouseenterEvent(sliderElement); dispatchSlideStartEvent(sliderElement, startPercent); dispatchSlideEvent(sliderElement, startPercent); dispatchSlideEvent(sliderElement, endPercent); dispatchSlideEndEvent(sliderElement, endPercent); } /** * Dispatches a slide event from an element. * @param sliderElement The mat-slider element from which the event will be dispatched. * @param percent The percentage of the slider where the slide will happen. */ function dispatchSlideEvent(sliderElement: HTMLElement, percent: number): void { const trackElement = sliderElement.querySelector('.mat-slider-wrapper')!; const dimensions = trackElement.getBoundingClientRect(); const x = dimensions.left + dimensions.width * percent; const y = dimensions.top + dimensions.height * percent; dispatchMouseEvent(document, 'mousemove', x, y); } /** * Dispatches a slidestart event from an element. * @param sliderElement The mat-slider element from which the event will be dispatched. * @param percent The percentage of the slider where the slide will begin. */ function dispatchSlideStartEvent(sliderElement: HTMLElement, percent: number): void { const trackElement = sliderElement.querySelector('.mat-slider-wrapper')!; const dimensions = trackElement.getBoundingClientRect(); const x = dimensions.left + dimensions.width * percent; const y = dimensions.top + dimensions.height * percent; dispatchMouseenterEvent(sliderElement); dispatchMouseEvent(sliderElement, 'mousedown', x, y); } /** * Dispatches a slideend event from an element. * @param sliderElement The mat-slider element from which the event will be dispatched. * @param percent The percentage of the slider where the slide will end. */ function dispatchSlideEndEvent(sliderElement: HTMLElement, percent: number): void { const trackElement = sliderElement.querySelector('.mat-slider-wrapper')!; const dimensions = trackElement.getBoundingClientRect(); const x = dimensions.left + dimensions.width * percent; const y = dimensions.top + dimensions.height * percent; dispatchMouseEvent(document, 'mouseup', x, y); } /** * Dispatches a mouseenter event from an element. * Note: The mouse event truncates the position for the event. * @param element The element from which the event will be dispatched. */ function dispatchMouseenterEvent(element: HTMLElement): void { const dimensions = element.getBoundingClientRect(); const y = dimensions.top; const x = dimensions.left; dispatchMouseEvent(element, 'mouseenter', x, y); }
the_stack
import { Enum } from './ServerStateEnum' // ResponseNS import { Response as ResponseSignatureNS } from './ResponseSignature' import { Response as ResponseValidator } from './ResponseValidators' import { Response as ResponseParser } from './ResponseParsers' import ResponseSignature = ResponseSignatureNS.ResponseSignature // Command NS import { Command as CommandNS } from './AbstractCommand' import IAMCPCommand = CommandNS.IAMCPCommand import IAMCPCommandVO = CommandNS.IAMCPCommandVO import AbstractCommand = CommandNS.AbstractCommand import AbstractOrChannelOrLayerCommand = CommandNS.AbstractOrChannelOrLayerCommand import AbstractChannelCommand = CommandNS.AbstractChannelCommand import AbstractChannelOrLayerCommand = CommandNS.AbstractChannelOrLayerCommand import AbstractLayerWithFallbackCommand = CommandNS.AbstractLayerWithFallbackCommand import AbstractLayerWithCgFallbackCommand = CommandNS.AbstractLayerWithCgFallbackCommand // Param NS import { Param as ParamNS } from './ParamSignature' import Param = ParamNS.Param import required = ParamNS.Required import optional = ParamNS.Optional import ParamSignature = ParamNS.ParamSignature // Validation NS import { Validation as ParameterValidator } from './ParamValidators' // Protocol NS import { Protocol as ProtocolNS } from './ProtocolLogic' import Depends = ProtocolNS.Depends import Coupled = ProtocolNS.Coupled import OneOf = ProtocolNS.OneOf /** * Internal */ export namespace AMCP { export class CustomCommand extends AbstractCommand { static readonly commandString = '' paramProtocol = [ new ParamSignature(required, 'command', null, new ParameterValidator.StringValidator(false)) ] } } /** * IVideo */ export namespace AMCP { /** * */ export class LoadbgCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'LOADBG' static readonly protocolLogic = [ new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(required, 'clip', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'loop', null, new ParameterValidator.BooleanValidatorWithDefaults('LOOP')), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'in', 'IN', new ParameterValidator.FrameValidator('IN')), new ParamSignature(optional, 'seek', 'SEEK', new ParameterValidator.FrameValidator('SEEK')), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')), new ParamSignature(optional, 'filter', 'FILTER', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'afilter', 'AF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'vfilter', 'VF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'auto', null, new ParameterValidator.BooleanValidatorWithDefaults('AUTO')), new ParamSignature(optional, 'channelLayout', 'CHANNEL_LAYOUT', new ParameterValidator.ChannelLayoutValidator()), new ParamSignature(optional, 'clearOn404', null, new ParameterValidator.BooleanValidatorWithDefaults('CLEAR_ON_404')) ] } /** * */ export class LoadCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'LOAD' static readonly protocolLogic = [ new Depends('loop', 'clip'), new Depends('in', 'clip'), new Depends('seek', 'clip'), new Depends('length', 'clip'), new Depends('filter', 'clip'), new Depends('transition', 'clip'), new Depends('channelLayout', 'clip'), new Depends('clearOn404', 'clip'), new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(optional, 'clip', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'loop', null, new ParameterValidator.BooleanValidatorWithDefaults('LOOP')), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'in', 'IN', new ParameterValidator.FrameValidator('IN')), new ParamSignature(optional, 'seek', 'SEEK', new ParameterValidator.FrameValidator('SEEK')), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')), new ParamSignature(optional, 'filter', 'FILTER', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'afilter', 'AF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'vfilter', 'VF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'channelLayout', 'CHANNEL_LAYOUT', new ParameterValidator.ChannelLayoutValidator()), new ParamSignature(optional, 'clearOn404', null, new ParameterValidator.BooleanValidatorWithDefaults('CLEAR_ON_404')) ] } /** * */ export class PlayCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'PLAY' static readonly protocolLogic = [ new Depends('loop', 'clip'), new Depends('in', 'clip'), new Depends('seek', 'clip'), new Depends('length', 'clip'), new Depends('filter', 'clip'), new Depends('transition', 'clip'), new Depends('channelLayout', 'clip'), new Depends('clearOn404', 'clip'), new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(optional, 'clip', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'loop', null, new ParameterValidator.BooleanValidatorWithDefaults('LOOP')), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'in', 'IN', new ParameterValidator.FrameValidator('IN')), new ParamSignature(optional, 'seek', 'SEEK', new ParameterValidator.FrameValidator('SEEK')), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')), new ParamSignature(optional, 'filter', 'FILTER', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'afilter', 'AF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'vfilter', 'VF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'channelLayout', 'CHANNEL_LAYOUT', new ParameterValidator.ChannelLayoutValidator()), new ParamSignature(optional, 'clearOn404', null, new ParameterValidator.BooleanValidatorWithDefaults('CLEAR_ON_404')) ] } /** * */ export class PauseCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'PAUSE' } /** * */ export class ResumeCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'RESUME' } /** * */ export class StopCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'STOP' } } /** * IInputOutput */ export namespace AMCP { /** * */ export class LoadDecklinkBgCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'LOADBG' static readonly protocolLogic = [ new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(required, 'device', 'DECKLINK DEVICE', new ParameterValidator.DecklinkDeviceValidator()), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')), new ParamSignature(optional, 'filter', 'FILTER', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'afilter', 'AF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'vfilter', 'VF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'format', 'FORMAT', new ParameterValidator.ChannelFormatValidator()), new ParamSignature(optional, 'channelLayout', 'CHANNEL_LAYOUT', new ParameterValidator.ChannelLayoutValidator()), new ParamSignature(optional, 'auto', null, new ParameterValidator.BooleanValidatorWithDefaults('AUTO')) ] } /** * */ export class LoadDecklinkCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'LOAD' static readonly protocolLogic = [ new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(required, 'device', 'DECKLINK DEVICE', new ParameterValidator.DecklinkDeviceValidator()), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')), new ParamSignature(optional, 'filter', 'FILTER', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'afilter', 'AF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'vfilter', 'VF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'format', 'FORMAT', new ParameterValidator.ChannelFormatValidator()), new ParamSignature(optional, 'channelLayout', 'CHANNEL_LAYOUT', new ParameterValidator.ChannelLayoutValidator()) ] } /** * */ export class PlayDecklinkCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'PLAY' static readonly protocolLogic = [ new Depends('length', 'device'), new Depends('filter', 'device'), new Depends('format', 'device'), new Depends('channelLayout', 'device'), new Depends('transition', 'device'), new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(required, 'device', 'DECKLINK DEVICE', new ParameterValidator.DecklinkDeviceValidator()), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')), new ParamSignature(optional, 'filter', 'FILTER', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'afilter', 'AF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'vfilter', 'VF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'format', 'FORMAT', new ParameterValidator.ChannelFormatValidator()), new ParamSignature(optional, 'channelLayout', 'CHANNEL_LAYOUT', new ParameterValidator.ChannelLayoutValidator()) ] } /** * */ export class LoadRouteBgCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'LOADBG' static readonly protocolLogic = [ new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(required, 'route', null, new ParameterValidator.RouteValidator()), new ParamSignature(optional, 'mode', null, new ParameterValidator.RouteModeValidator()), new ParamSignature(optional, 'framesDelay', 'FRAMES_DELAY', new ParameterValidator.RouteFramesDelayValidator()), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')), new ParamSignature(optional, 'filter', 'FILTER', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'afilter', 'AF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'vfilter', 'VF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'auto', null, new ParameterValidator.BooleanValidatorWithDefaults('AUTO')), new ParamSignature(optional, 'channelLayout', 'CHANNEL_LAYOUT', new ParameterValidator.ChannelLayoutValidator()) ] } /** * */ export class LoadRouteCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'LOAD' static readonly protocolLogic = [ new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(required, 'route', null, new ParameterValidator.RouteValidator()), new ParamSignature(optional, 'mode', null, new ParameterValidator.RouteModeValidator()), new ParamSignature(optional, 'framesDelay', 'FRAMES_DELAY', new ParameterValidator.RouteFramesDelayValidator()), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')), new ParamSignature(optional, 'filter', 'FILTER', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'afilter', 'AF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'vfilter', 'VF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'channelLayout', 'CHANNEL_LAYOUT', new ParameterValidator.ChannelLayoutValidator()) ] } /** * */ export class PlayRouteCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'PLAY' static readonly protocolLogic = [ new Depends('length', 'route'), new Depends('filter', 'route'), new Depends('format', 'route'), new Depends('channelLayout', 'route'), new Depends('transition', 'route'), new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(required, 'route', null, new ParameterValidator.RouteValidator()), new ParamSignature(optional, 'mode', null, new ParameterValidator.RouteModeValidator()), new ParamSignature(optional, 'framesDelay', 'FRAMES_DELAY', new ParameterValidator.RouteFramesDelayValidator()), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')), new ParamSignature(optional, 'filter', 'FILTER', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'afilter', 'AF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'vfilter', 'VF', new ParameterValidator.FilterValidator()), new ParamSignature(optional, 'channelLayout', 'CHANNEL_LAYOUT', new ParameterValidator.ChannelLayoutValidator()) ] } /** * */ export class LoadHtmlPageBgCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'LOADBG' static readonly protocolLogic = [ new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(required, 'url', '[HTML]', new ParameterValidator.URLValidator()), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()), new ParamSignature(optional, 'auto', null, new ParameterValidator.BooleanValidatorWithDefaults('AUTO')) ] } /** * */ export class LoadHtmlPageCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'LOAD' static readonly protocolLogic = [ new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(required, 'url', '[HTML]', new ParameterValidator.URLValidator()), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()) ] } /** * */ export class PlayHtmlPageCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'PLAY' static readonly protocolLogic = [ new Depends('transition', 'url'), new Depends('transitionDuration', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionEasing', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('transitionDirection', 'transition').mustNotBe('transition', Enum.Transition.STING), new Depends('stingTransitionProperties', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingMaskFilename', 'transition').mustBe('transition', Enum.Transition.STING), new Depends('stingDelay', 'stingMaskFilename').mustBe('transition', Enum.Transition.STING), new Depends('stingOverlayFilename', 'stingDelay').mustBe('transition', Enum.Transition.STING) ] paramProtocol = [ new ParamSignature(optional, 'url', '[HTML]', new ParameterValidator.URLValidator()), new ParamSignature(optional, 'transition', null, new ParameterValidator.EnumValidator(Enum.Transition)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'transitionDirection', null, new ParameterValidator.EnumValidator(Enum.Direction)), new ParamSignature(optional, 'stingTransitionProperties', null, new ParameterValidator.StingTransitionPropertiesValidator()), new ParamSignature(optional, 'stingMaskFilename', null, new ParameterValidator.ClipNameValidator()), new ParamSignature(optional, 'stingDelay', null, new ParameterValidator.PositiveNumberValidator()), new ParamSignature(optional, 'stingOverlayFilename', null, new ParameterValidator.ClipNameEmptyStringValidator()) ] } } /** * ICG */ export namespace AMCP { /** * */ export class CGAddCommand extends AbstractLayerWithCgFallbackCommand { static readonly commandString = 'CG' paramProtocol = [ new ParamSignature(required, 'flashLayer', 'ADD', new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(required, 'templateName', null, new ParameterValidator.TemplateNameValidator()), new ParamSignature(required, 'playOnLoad', null, new ParameterValidator.BooleanValidatorWithDefaults(1, 0)), new ParamSignature(optional, 'data', null, new ParameterValidator.TemplateDataValidator()) ] } /** * */ export class CGPlayCommand extends AbstractLayerWithCgFallbackCommand { static readonly commandString = 'CG' paramProtocol = [ new ParamSignature(required, 'flashLayer', 'PLAY', new ParameterValidator.PositiveNumberValidatorBetween()) ] } /** * */ export class CGStopCommand extends AbstractLayerWithCgFallbackCommand { static readonly commandString = 'CG' paramProtocol = [ new ParamSignature(required, 'flashLayer', 'STOP', new ParameterValidator.PositiveNumberValidatorBetween()) ] } /** * */ export class CGNextCommand extends AbstractLayerWithCgFallbackCommand { static readonly commandString = 'CG' paramProtocol = [ new ParamSignature(required, 'flashLayer', 'NEXT', new ParameterValidator.PositiveNumberValidatorBetween()) ] } /** * */ export class CGRemoveCommand extends AbstractLayerWithCgFallbackCommand { static readonly commandString = 'CG' paramProtocol = [ new ParamSignature(required, 'flashLayer', 'REMOVE', new ParameterValidator.PositiveNumberValidatorBetween()) ] } /** * */ export class CGClearCommand extends AbstractLayerWithCgFallbackCommand { static readonly commandString = 'CG' paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CLEAR')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CLEAR' } } /** * */ export class CGUpdateCommand extends AbstractLayerWithCgFallbackCommand { static readonly commandString = 'CG' paramProtocol = [ new ParamSignature(required, 'flashLayer', 'UPDATE', new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(required, 'data', null, new ParameterValidator.TemplateDataValidator()) ] } /** * @todo: 201 response code, parsing??????? */ export class CGInvokeCommand extends AbstractLayerWithCgFallbackCommand { static readonly commandString = 'CG' paramProtocol = [ new ParamSignature(required, 'flashLayer', 'INVOKE', new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(required, 'method', null, new ParameterValidator.StringValidator()) ] responseProtocol = new ResponseSignature(201) } } /** * IMixer * @todo: switch 201/202 based on mode */ export namespace AMCP { /** * */ export class MixerKeyerCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('defer', 'keyer') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('KEYER')), new ParamSignature(optional, 'keyer', null, new ParameterValidator.BooleanValidatorWithDefaults(1, 0)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'KEYER' } } /** * */ export class MixerStatusKeyerCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('KEYER')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusKeyerParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'KEYER' } } /** * @todo Validata/clamp lamp number range? */ export class MixerChromaCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Coupled('threshold', 'softness'), new Depends('keyer', 'threshold').ifNot('keyer', Enum.Chroma.NONE), new Depends('spill', 'threshold'), new Depends('transitionDuration', 'keyer'), new Depends('transitionEasing', 'keyer'), new Depends('defer', 'threshold').ifNot('keyer', Enum.Chroma.NONE) ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CHROMA')), new ParamSignature(optional, 'keyer', null, new ParameterValidator.EnumValidator(Enum.Chroma)), new ParamSignature(optional, 'threshold', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'softness', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'spill', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CHROMA' } } export class MixerStatusChromaCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CHROMA')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusChromaParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CHROMA' } } /** * */ export class MixerBlendCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('defer', 'blendmode') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('BLEND')), new ParamSignature(optional, 'blendmode', null, new ParameterValidator.EnumValidator(Enum.BlendMode)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'BLEND' } } /** * */ export class MixerStatusBlendCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('BLEND')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.StringValidator, ResponseParser.MixerStatusBlendParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'BLEND' } } /** * */ export class MixerOpacityCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('transitionDuration', 'opacity'), new Depends('transitionEasing', 'opacity'), new Depends('defer', 'opacity') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('OPACITY')), new ParamSignature(optional, 'opacity', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'OPACITY' } } /** * */ export class MixerStatusOpacityCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('OPACITY')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusOpacityParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'OPACITY' } } /** * */ export class MixerBrightnessCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('transitionDuration', 'brightness'), new Depends('transitionEasing', 'brightness'), new Depends('defer', 'brightness') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('BRIGHTNESS')), new ParamSignature(optional, 'brightness', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'BRIGHTNESS' } } /** * */ export class MixerStatusBrightnessCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('BRIGHTNESS')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusBrightnessParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'BRIGHTNESS' } } /** * */ export class MixerSaturationCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('transitionDuration', 'saturation'), new Depends('transitionEasing', 'saturation'), new Depends('defer', 'saturation') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('SATURATION')), new ParamSignature(optional, 'saturation', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'SATURATION' } } /** * */ export class MixerStatusSaturationCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('SATURATION')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusSaturationParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'SATURATION' } } /** * */ export class MixerContrastCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('transitionDuration', 'contrast'), new Depends('transitionEasing', 'contrast'), new Depends('defer', 'contrast') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CONTRAST')), new ParamSignature(optional, 'contrast', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CONTRAST' } } /** * */ export class MixerStatusContrastCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CONTRAST')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusContrastParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CONTRAST' } } /** * @todo: verify `gamma` value range */ export class MixerLevelsCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Coupled('minInput', 'maxInput', 'gamma', 'minOutput', 'maxOutput'), new Depends('transitionDuration', 'minInput'), new Depends('transitionEasing', 'minInput'), new Depends('defer', 'minInput') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('LEVELS')), new ParamSignature(optional, 'minInput', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'maxInput', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'gamma', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'minOutput', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'maxOutput', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'LEVELS' } } /** * */ export class MixerStatusLevelsCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('LEVELS')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusLevelsParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'LEVELS' } } /** * */ export class MixerFillCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Coupled('x', 'y', 'xScale', 'yScale'), new Depends('transitionDuration', 'x'), new Depends('transitionEasing', 'x'), new Depends('defer', 'x') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('FILL')), new ParamSignature(optional, 'x', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'y', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'xScale', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'yScale', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'FILL' } } /** * */ export class MixerStatusFillCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('FILL')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusFillParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'FILL' } } /** * */ export class MixerClipCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Coupled('x', 'y', 'width', 'height'), new Depends('transitionDuration', 'x'), new Depends('transitionEasing', 'x'), new Depends('defer', 'x') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CLIP')), new ParamSignature(optional, 'x', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'y', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'width', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'height', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CLIP' } } /** * */ export class MixerStatusClipCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CLIP')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusClipParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CLIP' } } /** * */ export class MixerAnchorCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Coupled('x', 'y'), new Depends('transitionDuration', 'x'), new Depends('transitionEasing', 'x'), new Depends('defer', 'x') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('ANCHOR')), new ParamSignature(optional, 'x', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'y', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'ANCHOR' } } /** * */ export class MixerStatusAnchorCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('ANCHOR')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusAnchorParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'ANCHOR' } } /** * */ export class MixerCropCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Coupled('left', 'top', 'right', 'bottom'), new Depends('transitionDuration', 'left'), new Depends('transitionEasing', 'left'), new Depends('defer', 'left') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CROP')), new ParamSignature(optional, 'left', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'top', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'right', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'bottom', null, new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CROP' } } /** * */ export class MixerStatusCropCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CROP')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusCropParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CROP' } } /** * */ export class MixerRotationCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('transitionDuration', 'rotation'), new Depends('transitionEasing', 'rotation'), new Depends('defer', 'rotation') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('ROTATION')), new ParamSignature(optional, 'rotation', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'ROTATION' } } /** * */ export class MixerStatusRotationCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('ROTATION')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusRotationParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'ROTATION' } } /** * */ export class MixerPerspectiveCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Coupled('topLeftX', 'topLeftY', 'topRightX', 'topRightY', 'bottomRightX', 'bottomRightY', 'bottomLeftX', 'bottomLeftY'), new Depends('transitionDuration', 'topLeftX'), new Depends('transitionEasing', 'topLeftX'), new Depends('defer', 'topLeftX') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('PERSPECTIVE')), new ParamSignature(optional, 'topLeftX', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'topLeftY', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'topRightX', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'topRightY', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'bottomRightX', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'bottomRightY', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'bottomLeftX', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'bottomLeftY', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.NumberValidator()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'PERSPECTIVE' } } /** * */ export class MixerStatusPerspectiveCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('PERSPECTIVE')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusPerspectiveParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'PERSPECTIVE' } } /** * */ export class MixerMipmapCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('defer', 'mipmap') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('MIPMAP')), new ParamSignature(optional, 'mipmap', null, new ParameterValidator.BooleanValidatorWithDefaults(1, 0)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'MIPMAP' } } /** * */ export class MixerStatusMipmapCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('MIPMAP')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusMipmapParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'MIPMAP' } } /** * */ export class MixerVolumeCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('transitionDuration', 'volume'), new Depends('transitionEasing', 'volume'), new Depends('defer', 'volume') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('VOLUME')), new ParamSignature(optional, 'volume', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'VOLUME' } } /** * */ export class MixerStatusVolumeCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('VOLUME')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusVolumeParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'VOLUME' } } /** * */ export class MixerMastervolumeCommand extends AbstractChannelCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('transitionDuration', 'mastervolume'), new Depends('transitionEasing', 'mastervolume'), new Depends('defer', 'mastervolume') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('MASTERVOLUME')), new ParamSignature(optional, 'mastervolume', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'MASTERVOLUME' } } /** * */ export class MixerStatusMastervolumeCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('MASTERVOLUME')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusMastervolumeParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'MASTERVOLUME' } } /** * */ export class MixerStraightAlphaOutputCommand extends AbstractChannelCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [ new Depends('defer', 'straight_alpha_output') ] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('STRAIGHT_ALPHA_OUTPUT')), new ParamSignature(optional, 'straight_alpha_output', null, new ParameterValidator.BooleanValidatorWithDefaults(1, 0)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'STRAIGHT_ALPHA_OUTPUT' } } /** * */ export class MixerStatusStraightAlphaOutputCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'MIXER' static readonly protocolLogic = [] paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('STRAIGHT_ALPHA_OUTPUT')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.MixerStatusValidator, ResponseParser.MixerStatusStraightAlphaOutputParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'STRAIGHT_ALPHA_OUTPUT' } } /** * */ export class MixerGridCommand extends AbstractChannelCommand { static readonly commandString = 'MIXER' paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('GRID')), new ParamSignature(optional, 'resolution', null, new ParameterValidator.PositiveNumberRoundValidatorBetween(1)), new ParamSignature(optional, 'transitionDuration', null, new ParameterValidator.PositiveNumberValidatorBetween()), new ParamSignature(optional, 'transitionEasing', null, new ParameterValidator.EnumValidator(Enum.Ease)), new ParamSignature(optional, 'defer', null, new ParameterValidator.BooleanValidatorWithDefaults('DEFER')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'GRID' } } /** * */ export class MixerCommitCommand extends AbstractChannelCommand { static readonly commandString = 'MIXER' paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('COMMIT')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'COMMIT' } } /** * */ export class MixerClearCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'MIXER' paramProtocol = [ new ParamSignature(required, 'keyword', null, new ParameterValidator.KeywordValidator('CLEAR')) ] /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['keyword'] = 'CLEAR' } } } /** * IChannel */ export namespace AMCP { /** * */ export class ClearCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'CLEAR' } /** * */ export class CallCommand extends AbstractLayerWithFallbackCommand { static readonly commandString = 'CALL' static readonly protocolLogic = [ new OneOf('seek', 'loop', 'in', 'start', 'out', 'length') ] paramProtocol = [ new ParamSignature(optional, 'seek', 'SEEK', new ParameterValidator.FrameValidator('SEEK')), new ParamSignature(optional, 'loop', 'loop', new ParameterValidator.PositiveNumberValidatorBetween(0, 1)), new ParamSignature(optional, 'in', 'IN', new ParameterValidator.FrameValidator('IN')), new ParamSignature(optional, 'start', 'START', new ParameterValidator.FrameValidator('START')), new ParamSignature(optional, 'out', 'OUT', new ParameterValidator.FrameValidator('OUT')), new ParamSignature(optional, 'length', 'LENGTH', new ParameterValidator.FrameValidator('LENGTH')) ] } /** * */ export class SwapCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'SWAP' /** * */ constructor() { super('1-1') // @todo: foo // @todo: custom parameters dual layerOrchannel with 1 optional param // overloading in method } } /** * */ export class AddCommand extends AbstractChannelCommand { static readonly commandString = 'ADD' } /** * */ export class AddDecklinkCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'ADD' paramProtocol = [ new ParamSignature(required, 'device', 'DECKLINK', new ParameterValidator.DecklinkDeviceValidator()) ] } /** * */ export class AddImageCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'ADD' paramProtocol = [ new ParamSignature(required, 'fileName', 'IMAGE', new ParameterValidator.StringValidator()) ] } /** * */ export class AddFileCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'ADD' paramProtocol = [ new ParamSignature(required, 'fileName', 'FILE', new ParameterValidator.StringValidator()) ] } /** * */ export class AddStreamCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'ADD' paramProtocol = [ new ParamSignature(required, 'uri', 'STREAM', new ParameterValidator.StringValidator()), new ParamSignature(required, 'params', null, new ParameterValidator.StringValidator()) ] } /** * */ export class RemoveCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'REMOVE' } export class RemoveDecklinkCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'REMOVE' paramProtocol = [ new ParamSignature(required, 'device', 'DECKLINK', new ParameterValidator.DecklinkDeviceValidator()) ] } /** * */ export class RemoveImageCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'REMOVE' paramProtocol = [ new ParamSignature(required, 'fileName', 'IMAGE', new ParameterValidator.StringValidator()) ] } /** * */ export class RemoveFileCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'REMOVE' paramProtocol = [ new ParamSignature(required, 'fileName', 'FILE', new ParameterValidator.StringValidator()) ] } /** * */ export class RemoveStreamCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'REMOVE' paramProtocol = [ new ParamSignature(required, 'uri', 'STREAM', new ParameterValidator.StringValidator()) ] } /** * */ export class PrintCommand extends AbstractChannelCommand { static readonly commandString = 'PRINT' } /** * */ export class SetCommand extends AbstractChannelCommand { static readonly commandString = 'SET' } /** * */ export class LockCommand extends AbstractChannelCommand { static readonly commandString = 'LOCK' static readonly protocolLogic = [ new Depends('action', 'phrase').ifNot('action', Enum.Lock.RELEASE) ] paramProtocol = [ new ParamSignature(required, 'action', null, new ParameterValidator.EnumValidator(Enum.Lock)), new ParamSignature(optional, 'phrase', null, new ParameterValidator.StringValidator()) ] } /** * */ export class ChannelGridCommand extends AbstractCommand { static readonly commandString = 'CHANNEL_GRID' } /** * */ export class GlGCCommand extends AbstractCommand { static readonly commandString = 'GL GC' } } /** * IData */ export namespace AMCP { /** * */ export class DataStoreCommand extends AbstractCommand { static readonly commandString = 'DATA STORE' paramProtocol = [ new ParamSignature(required, 'fileName', null, new ParameterValidator.DataNameValidator()), new ParamSignature(required, 'data', null, new ParameterValidator.TemplateDataValidator()) ] } /** * */ export class DataRetrieveCommand extends AbstractCommand { static readonly commandString = 'DATA RETRIEVE' paramProtocol = [ new ParamSignature(required, 'fileName', null, new ParameterValidator.DataNameValidator()) ] responseProtocol = new ResponseSignature(201, ResponseValidator.DataValidator, ResponseParser.DataParser) } /** * */ export class DataListCommand extends AbstractCommand { static readonly commandString = 'DATA LIST' responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.DataListParser) } /** * */ export class DataRemoveCommand extends AbstractCommand { static readonly commandString = 'DATA REMOVE' paramProtocol = [ new ParamSignature(required, 'fileName', null, new ParameterValidator.DataNameValidator()) ] } } /** * IThumbnail */ export namespace AMCP { /** * */ export class ThumbnailListCommand extends AbstractCommand { static readonly commandString = 'THUMBNAIL LIST' paramProtocol = [ new ParamSignature(optional, 'subFolder', null, new ParameterValidator.ClipNameValidator()) ] // responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.ThumbnailListParser); responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.ThumbnailListParser) } /** * */ export class ThumbnailRetrieveCommand extends AbstractCommand { static readonly commandString = 'THUMBNAIL RETRIEVE' paramProtocol = [ new ParamSignature(required, 'fileName', null, new ParameterValidator.ClipNameValidator()) ] responseProtocol = new ResponseSignature(201, ResponseValidator.Base64Validator, ResponseParser.ThumbnailParser) } /** * */ export class ThumbnailGenerateCommand extends AbstractCommand { static readonly commandString = 'THUMBNAIL GENERATE' paramProtocol = [ new ParamSignature(required, 'fileName', null, new ParameterValidator.ClipNameValidator()) ] } /** * */ export class ThumbnailGenerateAllCommand extends AbstractCommand { static readonly commandString = 'THUMBNAIL GENERATE_ALL' } } /** * IInfo */ export namespace AMCP { /** * */ export class CinfCommand extends AbstractCommand { static readonly commandString = 'CINF' paramProtocol = [ new ParamSignature(required, 'fileName', null, new ParameterValidator.ClipNameValidator()) ] responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.CinfParser) } /** * */ export class ClsCommand extends AbstractCommand { static readonly commandString = 'CLS' paramProtocol = [ new ParamSignature(optional, 'subFolder', null, new ParameterValidator.ClipNameValidator()) ] responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.ContentParser) } /** * */ export class FlsCommand extends AbstractCommand { static readonly commandString = 'FLS' responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.ContentParser) } /** * */ export class TlsCommand extends AbstractCommand { static readonly commandString = 'TLS' paramProtocol = [ new ParamSignature(optional, 'subFolder', null, new ParameterValidator.ClipNameValidator()) ] responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.ContentParser) } /** * */ export class VersionCommand extends AbstractCommand { static readonly commandString = 'VERSION' paramProtocol = [ new ParamSignature(optional, 'component', null, new ParameterValidator.EnumValidator(Enum.Version)) ] responseProtocol = new ResponseSignature(201, ResponseValidator.StringValidator, ResponseParser.VersionParser) } /** * */ export class InfoCommand extends AbstractOrChannelOrLayerCommand { static readonly commandString = 'INFO' responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.ChannelParser) /** * */ constructor(params?: (string | Param | (string | Param)[])) { super(params) if (this.channel && this.channel > -1) { this.responseProtocol = new ResponseSignature(201, ResponseValidator.XMLValidator, ResponseParser.InfoParser) } } } /** * */ export class InfoTemplateCommand extends AbstractCommand { static readonly commandString = 'INFO TEMPLATE' paramProtocol = [ new ParamSignature(required, 'template', null, new ParameterValidator.TemplateNameValidator()) ] responseProtocol = new ResponseSignature(201, ResponseValidator.XMLValidator, ResponseParser.InfoTemplateParser) } /** * */ export class InfoConfigCommand extends AbstractCommand { static readonly commandString = 'INFO CONFIG' responseProtocol = new ResponseSignature(201, ResponseValidator.XMLValidator, ResponseParser.ConfigParser) /** * */ constructor(params: (string | Param | (string | Param)[]), context?: Object) { super(params, context) } } /** * */ export class InfoPathsCommand extends AbstractCommand { static readonly commandString = 'INFO PATHS' responseProtocol = new ResponseSignature(201, ResponseValidator.XMLValidator, ResponseParser.InfoPathsParser) } /** * */ export class InfoSystemCommand extends AbstractCommand { static readonly commandString = 'INFO SYSTEM' responseProtocol = new ResponseSignature(201, ResponseValidator.XMLValidator, ResponseParser.InfoSystemParser) } /** * */ export class InfoServerCommand extends AbstractCommand { static readonly commandString = 'INFO SERVER' responseProtocol = new ResponseSignature(201, ResponseValidator.XMLValidator, ResponseParser.InfoServerParser) } /** * */ export class InfoQueuesCommand extends AbstractCommand { static readonly commandString = 'INFO QUEUES' responseProtocol = new ResponseSignature(201, ResponseValidator.XMLValidator, ResponseParser.InfoQueuesParser) } /** * */ export class InfoThreadsCommand extends AbstractCommand { static readonly commandString = 'INFO THREADS' responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.InfoThreadsParser) } /** * */ export class InfoDelayCommand extends AbstractChannelOrLayerCommand { static readonly commandString = 'INFO' paramProtocol = [ new ParamSignature(required, 'delay', null, new ParameterValidator.KeywordValidator('DELAY')) ] responseProtocol = new ResponseSignature(201, ResponseValidator.XMLValidator, ResponseParser.InfoDelayParser) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['delay'] = 'DELAY' } } /** * @todo: response validator/parser */ export class CGInfoCommand extends AbstractLayerWithCgFallbackCommand { static readonly commandString = 'CG' paramProtocol = [ new ParamSignature(required, 'info', null, new ParameterValidator.KeywordValidator('INFO')), new ParamSignature(optional, 'flashLayer', null, new ParameterValidator.PositiveNumberValidatorBetween()) ] responseProtocol = new ResponseSignature(201) /** * */ constructor(params: (string | Param | (string | Param)[])) { super(params) this._objectParams['info'] = 'INFO' } } /** * */ export class GlInfoCommand extends AbstractCommand { static readonly commandString = 'GL INFO' responseProtocol = new ResponseSignature(201, ResponseValidator.XMLValidator, ResponseParser.GLParser) } /** * */ export class LogLevelCommand extends AbstractCommand { static readonly commandString = 'LOG LEVEL' paramProtocol = [ new ParamSignature(optional, 'level', null, new ParameterValidator.EnumValidator(Enum.LogLevel)) ] } /** * @protocol Needs either `calltrace` or `communication` parameter. */ export class LogCategoryCommand extends AbstractCommand { static readonly commandString = 'LOG CATEGORY' static readonly protocolLogic = [ new OneOf('calltrace', 'communication') ] paramProtocol = [ new ParamSignature(optional, 'calltrace', Enum.LogCategory.CALLTRACE.value, new ParameterValidator.BooleanValidatorWithDefaults(1, 0)), new ParamSignature(optional, 'communication', Enum.LogCategory.COMMUNICATION.value, new ParameterValidator.BooleanValidatorWithDefaults(1, 0)) ] } /** * */ export class DiagCommand extends AbstractCommand { static readonly commandString = 'DIAG' } /** * @todo: mixed mode!!!! * 202/201 */ export class HelpCommand extends AbstractCommand { static readonly commandString = 'HELP' paramProtocol = [ new ParamSignature(optional, 'command', null, new ParameterValidator.EnumValidator(Enum.Command)) ] responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.HelpParser) } /** * */ export class HelpProducerCommand extends AbstractCommand { static readonly commandString = 'HELP PRODUCER' paramProtocol = [ new ParamSignature(optional, 'producer', null, new ParameterValidator.EnumValidator(Enum.Producer)) ] responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.HelpParser) } /** * */ export class HelpConsumerCommand extends AbstractCommand { static readonly commandString = 'HELP CONSUMER' paramProtocol = [ new ParamSignature(optional, 'consumer', null, new ParameterValidator.EnumValidator(Enum.Consumer)) ] responseProtocol = new ResponseSignature(200, ResponseValidator.ListValidator, ResponseParser.HelpParser) } } /** * IOperation */ export namespace AMCP { /** * @todo: response */ export class ByeCommand extends AbstractCommand { static readonly commandString = 'BYE' } /** * @todo: response */ export class KillCommand extends AbstractCommand { static readonly commandString = 'KILL' } /** * @todo: response */ export class RestartCommand extends AbstractCommand { static readonly commandString = 'RESTART' } export class PingCommand extends AbstractCommand { static readonly commandString = 'PING' } } /** * IScheduling */ export namespace AMCP { export class TimeCommand extends AbstractChannelCommand { static readonly commandString = 'TIME' paramProtocol = [ new ParamSignature(optional, 'timecode', null, new ParameterValidator.TimecodeValidator()) ] responseProtocol = new ResponseSignature(201, ResponseValidator.StringValidator, ResponseParser.InfoParser) } export class ScheduleSetCommand extends AbstractCommand { static readonly commandString = 'SCHEDULE SET' paramProtocol = [ new ParamSignature(required, 'token', null, new ParameterValidator.StringValidator()), new ParamSignature(required, 'timecode', null, new ParameterValidator.TimecodeValidator()), new ParamSignature(required, 'command', null, new ParameterValidator.CommandValidator()) ] } export class ScheduleRemoveCommand extends AbstractCommand { static readonly commandString = 'SCHEDULE REMOVE' paramProtocol = [ new ParamSignature(required, 'token', null, new ParameterValidator.StringValidator()) ] } export class ScheduleClearCommand extends AbstractCommand { static readonly commandString = 'SCHEDULE CLEAR' } export class ScheduleListCommand extends AbstractCommand { static readonly commandString = 'SCHEDULE LIST' paramProtocol = [ new ParamSignature(optional, 'token', null, new ParameterValidator.StringValidator()) ] } } /** * Factory */ export namespace AMCPUtil { /** * */ export function deSerialize(cmd: IAMCPCommandVO, id: string): IAMCPCommand { // errror: commandstatus -1 //invalid command // @todo: error handling much?????? (callback??????) // let command: IAMCPCommand = Object.create((AMCP as any)[cmd._commandName]['prototype']) // command.constructor.call(command, cmd._objectParams) let command: IAMCPCommand = new (AMCP as any)[cmd._commandName](cmd._objectParams) command.populate(cmd, id) return command } /** * */ export class CasparCGSocketResponse { public statusCode: number public token: string | undefined public responseString: string public items: Array<string> = [] /** * */ constructor(responseString: string) { this.token = CasparCGSocketResponse.parseToken(responseString) this.statusCode = CasparCGSocketResponse.evaluateStatusCode(responseString) this.responseString = responseString } /** * */ static evaluateStatusCode(responseString: string): number { let token = CasparCGSocketResponse.parseToken(responseString) let index: number if (token) index = token.length + 5 else index = 0 return parseInt(responseString.substr(index, 3), 10) } /** * */ static parseToken(responseString: string): string | undefined { if (responseString.substr(0, 3) === 'RES') { return responseString.substr(4).split(' ')[0] // RES [token] RESPONSE } else { return undefined } } } }
the_stack
import { Injectable } from '@angular/core'; import { CoreSyncBaseProvider } from '@classes/base-sync'; import { AddonMessagesOffline, AddonMessagesOfflineAnyMessagesFormatted, } from './messages-offline'; import { AddonMessagesProvider, AddonMessages, AddonMessagesGetMessagesWSParams, } from './messages'; import { CoreEvents } from '@singletons/events'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { CoreSites } from '@services/sites'; import { CoreApp } from '@services/app'; import { CoreConstants } from '@/core/constants'; import { CoreUser } from '@features/user/services/user'; import { CoreError } from '@classes/errors/error'; import { CoreTextErrorObject, CoreTextUtils } from '@services/utils/text'; import { CoreSiteWSPreSets } from '@classes/site'; /** * Service to sync messages. */ @Injectable({ providedIn: 'root' }) export class AddonMessagesSyncProvider extends CoreSyncBaseProvider<AddonMessagesSyncEvents> { static readonly AUTO_SYNCED = 'addon_messages_autom_synced'; constructor() { super('AddonMessagesSync'); } /** * Get the ID of a discussion sync. * * @param conversationId Conversation ID. * @param userId User ID talking to (if no conversation ID). * @return Sync ID. */ protected getSyncId(conversationId?: number, userId?: number): string { if (conversationId) { return 'conversationid:' + conversationId; } else if (userId) { return 'userid:' + userId; } else { // Should not happen. throw new CoreError('Incorrect messages sync id.'); } } /** * Try to synchronize all the discussions in a certain site or in all sites. * * @param siteId Site ID to sync. If not defined, sync all sites. * @param onlyDeviceOffline True to only sync discussions that failed because device was offline, * false to sync all. * @return Promise resolved if sync is successful, rejected if sync fails. */ syncAllDiscussions(siteId?: string, onlyDeviceOffline: boolean = false): Promise<void> { const syncFunctionLog = 'all discussions' + (onlyDeviceOffline ? ' (Only offline)' : ''); return this.syncOnSites(syncFunctionLog, this.syncAllDiscussionsFunc.bind(this, onlyDeviceOffline), siteId); } /** * Get all messages pending to be sent in the site. * * @param onlyDeviceOffline True to only sync discussions that failed because device was offline. * @param siteId Site ID to sync. If not defined, sync all sites. * @param Promise resolved if sync is successful, rejected if sync fails. */ protected async syncAllDiscussionsFunc(onlyDeviceOffline: boolean, siteId: string): Promise<void> { const userIds: number[] = []; const conversationIds: number[] = []; const promises: Promise<void>[] = []; const messages = onlyDeviceOffline ? await AddonMessagesOffline.getAllDeviceOfflineMessages(siteId) : await AddonMessagesOffline.getAllMessages(siteId); // Get all the conversations to be synced. messages.forEach((message) => { if ('conversationid' in message) { if (conversationIds.indexOf(message.conversationid) == -1) { conversationIds.push(message.conversationid); } } else if (userIds.indexOf(message.touserid) == -1) { userIds.push(message.touserid); } }); // Sync all conversations. conversationIds.forEach((conversationId) => { promises.push(this.syncDiscussion(conversationId, undefined, siteId).then((result) => { if (typeof result == 'undefined') { return; } // Sync successful, send event. CoreEvents.trigger(AddonMessagesSyncProvider.AUTO_SYNCED, result, siteId); return; })); }); userIds.forEach((userId) => { promises.push(this.syncDiscussion(undefined, userId, siteId).then((result) => { if (typeof result == 'undefined') { return; } // Sync successful, send event. CoreEvents.trigger(AddonMessagesSyncProvider.AUTO_SYNCED, result, siteId); return; })); }); await Promise.all(promises); } /** * Synchronize a discussion. * * @param conversationId Conversation ID. * @param userId User ID talking to (if no conversation ID). * @param siteId Site ID. * @return Promise resolved with the list of warnings if sync is successful, rejected otherwise. */ syncDiscussion(conversationId?: number, userId?: number, siteId?: string): Promise<AddonMessagesSyncEvents> { siteId = siteId || CoreSites.getCurrentSiteId(); const syncId = this.getSyncId(conversationId, userId); if (this.isSyncing(syncId, siteId)) { // There's already a sync ongoing for this conversation, return the promise. return this.getOngoingSync(syncId, siteId)!; } return this.addOngoingSync(syncId, this.performSyncDiscussion(conversationId, userId, siteId), siteId); } /** * Perform the synchronization of a discussion. * * @param conversationId Conversation ID. * @param userId User ID talking to (if no conversation ID). * @param siteId Site ID. * @return Promise resolved with the list of warnings if sync is successful, rejected otherwise. */ protected async performSyncDiscussion( conversationId: number | undefined, userId: number | undefined, siteId: string, ): Promise<AddonMessagesSyncEvents> { const result: AddonMessagesSyncEvents = { warnings: [], userId, conversationId, }; const groupMessagingEnabled = AddonMessages.isGroupMessagingEnabled(); let messages: AddonMessagesOfflineAnyMessagesFormatted[]; const errors: (string | CoreError | CoreTextErrorObject)[] = []; if (conversationId) { this.logger.debug(`Try to sync conversation '${conversationId}'`); messages = await AddonMessagesOffline.getConversationMessages(conversationId, undefined, siteId); } else if (userId) { this.logger.debug(`Try to sync discussion with user '${userId}'`); messages = await AddonMessagesOffline.getMessages(userId, siteId); } else { // Should not happen. throw new CoreError('Incorrect messages sync.'); } if (!messages.length) { // Nothing to sync. return result; } else if (!CoreApp.isOnline()) { // Cannot sync in offline. Mark messages as device offline. AddonMessagesOffline.setMessagesDeviceOffline(messages, true); throw new CoreError('Cannot sync in offline. Mark messages as device offline.'); } // Order message by timecreated. messages = AddonMessages.sortMessages(messages); // Get messages sent by the user after the first offline message was sent. // We subtract some time because the message could've been saved in server before it was in the app. const timeFrom = Math.floor((messages[0].timecreated - CoreConstants.WS_TIMEOUT - 1000) / 1000); const onlineMessages = await this.getMessagesSentAfter(timeFrom, conversationId, userId, siteId); // Send the messages. Send them 1 by 1 to simulate web's behaviour and to make sure we know which message has failed. for (let i = 0; i < messages.length; i++) { const message = messages[i]; const text = ('text' in message ? message.text : message.smallmessage) || ''; const textFieldName = conversationId ? 'text' : 'smallmessage'; const wrappedText = message[textFieldName][0] != '<' ? '<p>' + text + '</p>' : text; try { if (onlineMessages.indexOf(wrappedText) != -1) { // Message already sent, ignore it to prevent duplicates. } else if (conversationId) { await AddonMessages.sendMessageToConversationOnline(conversationId, text, siteId); } else if (userId) { await AddonMessages.sendMessageOnline(userId, text, siteId); } } catch (error) { if (!CoreUtils.isWebServiceError(error)) { // Error sending, stop execution. if (CoreApp.isOnline()) { // App is online, unmark deviceoffline if marked. AddonMessagesOffline.setMessagesDeviceOffline(messages, false); } throw error; } // Error returned by WS. Store the error to show a warning but keep sending messages. if (errors.indexOf(error) == -1) { errors.push(error); } } // Message was sent, delete it from local DB. if (conversationId) { await AddonMessagesOffline.deleteConversationMessage(conversationId, text, message.timecreated, siteId); } else if (userId) { await AddonMessagesOffline.deleteMessage(userId, text, message.timecreated, siteId); } // In some Moodle versions, wait 1 second to make sure timecreated is different. // This is because there was a bug where messages with the same timecreated had a wrong order. if (!groupMessagingEnabled && i < messages.length - 1) { await CoreUtils.wait(1000); } } await this.handleSyncErrors(conversationId, userId, errors, result.warnings); // All done, return the warnings. return result; } /** * Get messages sent by current user after a certain time. * * @param time Time in seconds. * @param conversationId Conversation ID. * @param userId User ID talking to (if no conversation ID). * @param siteId Site ID. * @return Promise resolved with the messages texts. */ protected async getMessagesSentAfter( time: number, conversationId?: number, userId?: number, siteId?: string, ): Promise<string[]> { const site = await CoreSites.getSite(siteId); const siteCurrentUserId = site.getUserId(); if (conversationId) { try { const result = await AddonMessages.getConversationMessages(conversationId, { excludePending: true, ignoreCache: true, timeFrom: time, }); const sentMessages = result.messages.filter((message) => message.useridfrom == siteCurrentUserId); return sentMessages.map((message) => message.text); } catch (error) { if (error && error.errorcode == 'invalidresponse') { // There's a bug in Moodle that causes this error if there are no new messages. Return empty array. return []; } throw error; } } else if (userId) { const params: AddonMessagesGetMessagesWSParams = { useridto: userId, useridfrom: siteCurrentUserId, limitnum: AddonMessagesProvider.LIMIT_MESSAGES, }; const preSets: CoreSiteWSPreSets = { cacheKey: AddonMessages.getCacheKeyForDiscussion(userId), getFromCache: false, emergencyCache: false, }; const messages = await AddonMessages.getRecentMessages(params, preSets, 0, 0, false, siteId); time = time * 1000; // Convert to milliseconds. const messagesAfterTime = messages.filter((message) => message.timecreated >= time); return messagesAfterTime.map((message) => message.text); } else { throw new CoreError('Incorrect messages sync identifier'); } } /** * Handle sync errors. * * @param conversationId Conversation ID. * @param userId User ID talking to (if no conversation ID). * @param errors List of errors. * @param warnings Array where to place the warnings. * @return Promise resolved when done. */ protected async handleSyncErrors( conversationId?: number, userId?: number, errors: (string | CoreError | CoreTextErrorObject)[] = [], warnings: string[] = [], ): Promise<void> { if (!errors || errors.length <= 0) { return; } if (conversationId) { let conversationIdentifier = String(conversationId); try { // Get conversation name and add errors to warnings array. const conversation = await AddonMessages.getConversation(conversationId, false, false); conversationIdentifier = conversation.name || String(conversationId); } catch { // Ignore errors. } errors.forEach((error) => { warnings.push(Translate.instant('addon.messages.warningconversationmessagenotsent', { conversation: conversationIdentifier, error: CoreTextUtils.getErrorMessageFromError(error), })); }); } else if (userId) { // Get user full name and add errors to warnings array. let userIdentifier = String(userId); try { const user = await CoreUser.getProfile(userId, undefined, true); userIdentifier = user.fullname; } catch { // Ignore errors. } errors.forEach((error) => { warnings.push(Translate.instant('addon.messages.warningmessagenotsent', { user: userIdentifier, error: CoreTextUtils.getErrorMessageFromError(error), })); }); } } /** * If there's an ongoing sync for a certain conversation, wait for it to end. * If there's no sync ongoing the promise will be resolved right away. * * @param conversationId Conversation ID. * @param userId User ID talking to (if no conversation ID). * @param siteId Site ID. If not defined, current site. * @return Promise resolved when there's no sync going on for the identifier. */ waitForSyncConversation( conversationId?: number, userId?: number, siteId?: string, ): Promise<AddonMessagesSyncEvents | undefined> { const syncId = this.getSyncId(conversationId, userId); return this.waitForSync(syncId, siteId); } } export const AddonMessagesSync = makeSingleton(AddonMessagesSyncProvider); export type AddonMessagesSyncEvents = { warnings: string[]; conversationId?: number; userId?: number; };
the_stack
// These APIs are currently experimental and may change. import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; import * as awslambda from "aws-lambda"; import { CognitoAuthorizer } from "./cognitoAuthorizer"; import * as utils from "../utils"; export type AuthorizerEvent = awslambda.CustomAuthorizerEvent; export type AuthorizerResponse = awslambda.CustomAuthorizerResult; export type AuthResponseContext = awslambda.AuthResponseContext; /** * LambdaAuthorizer provides the definition for a custom Authorizer for API Gateway. */ export interface LambdaAuthorizer { /** * The name for the Authorizer to be referenced as. This must be unique for each unique * authorizer within the API. If no name if specified, a name will be generated for you. */ authorizerName?: string; /** * parameterName is the name of the header or query parameter containing the authorization * token. Must be "Unused" for multiple identity sources. * */ parameterName: string; /** * Defines where in the request API Gateway should look for identity information. The value must * be "header" or "query". If there are multiple identity sources, the value must be "header". */ parameterLocation: "header" | "query"; /** * Specifies the authorization mechanism for the client. Typical values are "oauth2" or "custom". */ authType: string; /** * The type of the authorizer. This value must be one of the following: * - "token", for an authorizer with the caller identity embedded in an authorization token * - "request", for an authorizer with the caller identity contained in request parameters */ type: "token" | "request"; /** * The authorizerHandler specifies information about the authorizing Lambda. You can either set * up the Lambda separately and just provide the required information or you can define the * Lambda inline using a JavaScript function. */ handler: LambdaAuthorizerInfo | aws.lambda.EventHandler<AuthorizerEvent, AuthorizerResponse>; /** * List of mapping expressions of the request parameters as the identity source. This indicates * where in the request identity information is expected. Applicable for the authorizer of the * "request" type only. Example: ["method.request.header.HeaderAuth1", * "method.request.querystring.QueryString1"] */ identitySource?: string[]; /** * A regular expression for validating the token as the incoming identity. It only invokes the * authorizer's lambda if there is a match, else it will return a 401. This does not apply to * REQUEST Lambda Authorizers. Example: "^x-[a-z]+" */ identityValidationExpression?: string; /** * The number of seconds during which the resulting IAM policy is cached. Default is 300s. You * can set this value to 0 to disable caching. Max value is 3600s. Note - if you are sharing an * authorizer across more than one route you will want to disable the cache or else it will * cause problems for you. */ authorizerResultTtlInSeconds?: number; } export interface LambdaAuthorizerInfo { /** * The Uniform Resource Identifier (URI) of the authorizer Lambda function. The Lambda may also * be passed directly, in which cases the URI will be obtained for you. */ uri: pulumi.Input<string> | aws.lambda.Function; /** * Credentials required for invoking the authorizer in the form of an ARN of an IAM execution role. * For example, "arn:aws:iam::account-id:IAM_role". */ credentials: pulumi.Input<string> | aws.iam.Role; } /** @internal */ export function isLambdaAuthorizer(authorizer: LambdaAuthorizer | CognitoAuthorizer): authorizer is LambdaAuthorizer { return (<LambdaAuthorizer>authorizer).handler !== undefined; } /** @internal */ export function isLambdaAuthorizerInfo(info: LambdaAuthorizerInfo | aws.lambda.EventHandler<AuthorizerEvent, AuthorizerResponse>): info is LambdaAuthorizerInfo { return (<LambdaAuthorizerInfo>info).uri !== undefined; } /** @internal */ export function getIdentitySource(identitySources: string[] | undefined): string { if (identitySources) { return identitySources.join(", "); } return ""; } /** @internal */ export function createRoleWithAuthorizerInvocationPolicy( authorizerName: string, authorizerLambda: aws.lambda.Function, opts: pulumi.CustomResourceOptions): aws.iam.Role { const policy = aws.iam.assumeRolePolicyForPrincipal({ "Service": ["lambda.amazonaws.com", "apigateway.amazonaws.com"] }); // We previously didn't parent the Role or RolePolicy to anything. Now we do. Pass an // appropriate alias to prevent resources from being destroyed/created. const role = new aws.iam.Role(authorizerName + "-authorizer-role", { assumeRolePolicy: JSON.stringify(policy), }, pulumi.mergeOptions(opts, { aliases: [{ parent: pulumi.rootStackResource }] })); // Add invocation policy to lambda role const invocationPolicy = new aws.iam.RolePolicy(authorizerName + "-invocation-policy", { policy: pulumi.interpolate`{ "Version": "2012-10-17", "Statement": [ { "Action": "lambda:InvokeFunction", "Effect": "Allow", "Resource": "${authorizerLambda.arn}" } ] }`, role: role.id, }, pulumi.mergeOptions(opts, { aliases: [{ parent: pulumi.rootStackResource }] })); return role; } /** * Simplifies creating an AuthorizerResponse. * * @param principalId - unique identifier for the user * @param effect - whether to "Allow" or "Deny" the request * @param resource - the API method to be invoked (typically event.methodArn) * @param context - key-value pairs that are passed from the authorizer to the backend Lambda * @param apiKey - if the API uses a usage plan, this must be set to one of the usage plan's API keys */ export function authorizerResponse(principalId: string, effect: Effect, resource: string, context?: AuthResponseContext, apiKey?: string): AuthorizerResponse { const response: AuthorizerResponse = { principalId: principalId, policyDocument: { Version: "2012-10-17", Statement: [{ Action: "execute-api:Invoke", Effect: effect, Resource: resource, }], }, }; response.context = context; response.usageIdentifierKey = apiKey; return response; } export type Effect = "Allow" | "Deny"; /** * The set of arguments for constructing a token LambdaAuthorizer resource. */ export interface TokenAuthorizerArgs { /** * The name for the Authorizer to be referenced as. This must be unique for each unique * authorizer within the API. If no name if specified, a name will be generated for you. */ authorizerName?: string; /** * The request header for the authorization token. If not set, this defaults to * Authorization. */ header?: string; /** * The authorizerHandler specifies information about the authorizing Lambda. You can either set * up the Lambda separately and just provide the required information or you can define the * Lambda inline using a JavaScript function. */ handler: LambdaAuthorizerInfo | aws.lambda.EventHandler<AuthorizerEvent, AuthorizerResponse>; /** * A regular expression for validating the token as the incoming identity. * Example: "^x-[a-z]+" */ identityValidationExpression?: string; /** * The number of seconds during which the resulting IAM policy is cached. Default is 300s. You * can set this value to 0 to disable caching. Max value is 3600s. Note - if you are sharing an * authorizer across more than one route you will want to disable the cache or else it will * cause problems for you. */ authorizerResultTtlInSeconds?: number; } /** * getTokenLambdaAuthorizer is a helper function to generate a token LambdaAuthorizer. * @param name - the name for the authorizer. This must be unique for each unique authorizer in the API. * @param args - configuration information for the token Lambda. */ export function getTokenLambdaAuthorizer(args: TokenAuthorizerArgs): LambdaAuthorizer { return { authorizerName: args.authorizerName, parameterName: args.header || "Authorization", parameterLocation: "header", authType: "oauth2", type: "token", handler: args.handler, identityValidationExpression: args.identityValidationExpression, authorizerResultTtlInSeconds: args.authorizerResultTtlInSeconds, }; } /** * The set of arguments for constructing a request LambdaAuthorizer resource. */ export interface RequestAuthorizerArgs { /** * The name for the Authorizer to be referenced as. This must be unique for each unique authorizer * within the API. If no name if specified, a name will be generated for you. */ authorizerName?: string; /** * queryParameters is an array of the expected query parameter keys used to authorize a request. * While this argument is optional, at least one queryParameter or one header must be defined. * */ queryParameters?: string[]; /** * headers is an array of the expected header keys used to authorize a request. * While this argument is optional, at least one queryParameter or one header must be defined. * */ headers?: string[]; /** * The authorizerHandler specifies information about the authorizing Lambda. You can either set * up the Lambda separately and just provide the required information or you can define the * Lambda inline using a JavaScript function. */ handler: LambdaAuthorizerInfo | aws.lambda.EventHandler<AuthorizerEvent, AuthorizerResponse>; /** * The number of seconds during which the resulting IAM policy is cached. Default is 300s. You * can set this value to 0 to disable caching. Max value is 3600s. Note - if you are sharing an * authorizer across more than one route you will want to disable the cache or else it will * cause problems for you. */ authorizerResultTtlInSeconds?: number; } /** * getRequestLambdaAuthorizer is a helper function to generate a request LambdaAuthorizer. * * @param name - the name for the authorizer. This must be unique for each unique authorizer in the * API. * @param args - configuration information for the token Lambda. */ export function getRequestLambdaAuthorizer(args: RequestAuthorizerArgs): LambdaAuthorizer { let parameterName: string; let location: "header" | "query"; const numQueryParams = getLength(args.queryParameters); const numHeaders = getLength(args.headers); if (numQueryParams === 0 && numHeaders === 0) { throw new Error("[args.queryParameters] and [args.headers] were both empty. At least one query parameter or header must be specified"); } else { location = getLocation(numHeaders, numQueryParams); parameterName = getParameterName(args, numHeaders, numQueryParams); } return { authorizerName: args.authorizerName, parameterName: parameterName, parameterLocation: location, authType: "custom", type: "request", handler: args.handler, identitySource: parametersToIdentitySources(args), authorizerResultTtlInSeconds: args.authorizerResultTtlInSeconds, }; } /** @internal */ function getLength(params: string[] | undefined): number { if (!params) { return 0; } return params.length; } /** @internal */ function getParameterName(args: RequestAuthorizerArgs, numHeaders: number, numQueryParameters: number): string { if (numQueryParameters + numHeaders === 1) { if (args.queryParameters) { return args.queryParameters[0]; } else if (args.headers) { return args.headers[0]; } } return "Unused"; } /** @internal */ function getLocation(numHeaders: number, numQueryParameters: number): "header" | "query" { if (numHeaders > 0) { return "header"; } else if (numQueryParameters > 0) { return "query"; } else { throw new Error("Could not determine parameter location"); } } /** @internal */ function parametersToIdentitySources(args: RequestAuthorizerArgs): string[] { const identitySource: string[] = []; if (args.headers) { for (const header of args.headers) { identitySource.push("method.request.header." + header); } } if (args.queryParameters) { for (const param of args.queryParameters) { identitySource.push("method.request.querystring." + param); } } return identitySource; }
the_stack
import { TSESLint, TSESTree as es, } from "@typescript-eslint/experimental-utils"; import { stripIndent } from "common-tags"; import { getTypeServices, isCallExpression, isIdentifier, isMemberExpression, isThisExpression, } from "eslint-etc"; import { ruleCreator } from "../utils"; const messages = { noDestroy: "`ngOnDestroy` is not implemented.", noTakeUntil: "Forbids calling `subscribe` without an accompanying `takeUntil`.", notCalled: "`{{name}}.{{method}}()` not called.", notDeclared: "Subject `{{name}}` not a class property.", } as const; type MessageIds = keyof typeof messages; const defaultOptions: readonly { alias?: string[]; checkComplete?: boolean; checkDecorators?: string[]; checkDestroy?: boolean; }[] = []; const rule = ruleCreator({ defaultOptions, meta: { docs: { description: "Forbids `subscribe` calls without an accompanying `takeUntil` within Angular components (and, optionally, within services, directives, and pipes).", recommended: false, }, fixable: undefined, hasSuggestions: false, messages, schema: [ { properties: { alias: { type: "array", items: { type: "string" } }, checkComplete: { type: "boolean" }, checkDecorators: { type: "array", items: { type: "string" } }, checkDestroy: { type: "boolean" }, }, type: "object", description: stripIndent` An optional object with optional \`alias\`, \`checkComplete\`, \`checkDecorators\` and \`checkDestroy\` properties. The \`alias\` property is an array containing the names of operators that aliases for \`takeUntil\`. The \`checkComplete\` property is a boolean that determines whether or not \`complete\` must be called after \`next\`. The \`checkDecorators\` property is an array containing the names of the decorators that determine whether or not a class is checked. The \`checkDestroy\` property is a boolean that determines whether or not a \`Subject\`-based \`ngOnDestroy\` must be implemented. `, }, ], type: "problem", }, name: "prefer-takeuntil", create: (context, unused: typeof defaultOptions) => { const { couldBeObservable } = getTypeServices(context); // If an alias is specified, check for the subject-based destroy only if // it's explicitly configured. It's extremely unlikely a subject-based // destroy mechanism will be used in conjunction with an alias. const [config = {}] = context.options; const { alias = [], checkComplete = false, checkDecorators = ["Component"], checkDestroy = alias.length === 0, } = config; type Entry = { classDeclaration: es.ClassDeclaration; propertyDefinitions: es.PropertyDefinition[]; completeCallExpressions: es.CallExpression[]; hasDecorator: boolean; nextCallExpressions: es.CallExpression[]; ngOnDestroyDefinition?: es.MethodDefinition; subscribeCallExpressions: es.CallExpression[]; subscribeCallExpressionsToNames: Map<es.CallExpression, Set<string>>; }; const entries: Entry[] = []; function checkEntry(entry: Entry) { const { subscribeCallExpressions } = entry; subscribeCallExpressions.forEach((callExpression) => { const { callee } = callExpression; if (!isMemberExpression(callee)) { return; } const { object } = callee; if (!couldBeObservable(object)) { return; } checkSubscribe(callExpression, entry); }); if (checkDestroy) { checkNgOnDestroy(entry); } } function checkNgOnDestroy(entry: Entry) { const { classDeclaration, completeCallExpressions, nextCallExpressions, ngOnDestroyDefinition, subscribeCallExpressionsToNames, } = entry; if (subscribeCallExpressionsToNames.size === 0) { return; } if (!ngOnDestroyDefinition) { context.report({ messageId: "noDestroy", node: classDeclaration.id ?? classDeclaration, }); return; } // If a subscription to a .pipe() has at least one takeUntil that has no // failures, the subscribe call is fine. Callers should be able to use // secondary takUntil operators. However, there must be at least one // takeUntil operator that conforms to the pattern that this rule // enforces. type Check = { descriptors: TSESLint.ReportDescriptor<MessageIds>[]; report: boolean; }; const namesToChecks = new Map<string, Check>(); const names = new Set<string>(); subscribeCallExpressionsToNames.forEach((value) => value.forEach((name) => names.add(name)) ); names.forEach((name) => { const check: Check = { descriptors: [], report: false, }; namesToChecks.set(name, check); if (!checkSubjectProperty(name, entry)) { check.descriptors.push({ data: { name }, messageId: "notDeclared", node: classDeclaration.id ?? classDeclaration, }); } if (!checkSubjectCall(name, nextCallExpressions)) { check.descriptors.push({ data: { method: "next", name }, messageId: "notCalled", node: ngOnDestroyDefinition.key, }); } if (checkComplete && !checkSubjectCall(name, completeCallExpressions)) { check.descriptors.push({ data: { method: "complete", name }, messageId: "notCalled", node: ngOnDestroyDefinition.key, }); } }); subscribeCallExpressionsToNames.forEach((names) => { const report = [...names].every( /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */ (name) => namesToChecks.get(name)!.descriptors.length > 0 ); if (report) { names.forEach( /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */ (name) => (namesToChecks.get(name)!.report = true) ); } }); namesToChecks.forEach((check) => { if (check.report) { check.descriptors.forEach((descriptor) => context.report(descriptor)); } }); } function checkOperator(callExpression: es.CallExpression) { const { callee } = callExpression; if (!isIdentifier(callee)) { return { found: false }; } if (callee.name === "takeUntil" || alias.includes(callee.name)) { const [arg] = callExpression.arguments; if (arg) { if ( isMemberExpression(arg) && isThisExpression(arg.object) && isIdentifier(arg.property) ) { return { found: true, name: arg.property.name }; } else if (arg && isIdentifier(arg)) { return { found: true, name: arg.name }; } } if (!checkDestroy) { return { found: true }; } } return { found: false }; } function checkSubjectCall( name: string, callExpressions: es.CallExpression[] ) { const callExpression = callExpressions.find( ({ callee }) => (isMemberExpression(callee) && isIdentifier(callee.object) && callee.object.name === name) || (isMemberExpression(callee) && isMemberExpression(callee.object) && isThisExpression(callee.object.object) && isIdentifier(callee.object.property) && callee.object.property.name === name) ); return Boolean(callExpression); } function checkSubjectProperty(name: string, entry: Entry) { const { propertyDefinitions } = entry; const propertyDefinition = propertyDefinitions.find( (propertyDefinition: any) => propertyDefinition.key.name === name ); return Boolean(propertyDefinition); } function checkSubscribe(callExpression: es.CallExpression, entry: Entry) { const { subscribeCallExpressionsToNames } = entry; /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */ const names = subscribeCallExpressionsToNames.get(callExpression)!; let takeUntilFound = false; const { callee } = callExpression; if (!isMemberExpression(callee)) { return; } const { object, property } = callee; if ( isCallExpression(object) && isMemberExpression(object.callee) && isIdentifier(object.callee.property) && object.callee.property.name === "pipe" ) { const operators = object.arguments; operators.forEach((operator) => { if (isCallExpression(operator)) { const { found, name } = checkOperator(operator); takeUntilFound = takeUntilFound || found; if (name) { names.add(name); } } }); } if (!takeUntilFound) { context.report({ messageId: "noTakeUntil", node: property, }); } } function getEntry() { const { length, [length - 1]: entry } = entries; return entry; } function hasDecorator(node: es.ClassDeclaration) { const { decorators } = node as any; return ( decorators && decorators.some((decorator: any) => { const { expression } = decorator; if (!isCallExpression(expression)) { return false; } if (!isIdentifier(expression.callee)) { return false; } const { name } = expression.callee; return checkDecorators.some((check: string) => name === check); }) ); } return { "CallExpression[callee.property.name='subscribe']": ( node: es.CallExpression ) => { const entry = getEntry(); if (entry && entry.hasDecorator) { entry.subscribeCallExpressions.push(node); entry.subscribeCallExpressionsToNames.set(node, new Set<string>()); } }, ClassDeclaration: (node: es.ClassDeclaration) => { entries.push({ classDeclaration: node, propertyDefinitions: [], completeCallExpressions: [], nextCallExpressions: [], hasDecorator: hasDecorator(node), subscribeCallExpressions: [], subscribeCallExpressionsToNames: new Map< es.CallExpression, Set<string> >(), }); }, "ClassDeclaration:exit": (node: es.ClassDeclaration) => { const entry = entries.pop(); if (entry && entry.hasDecorator) { checkEntry(entry); } }, PropertyDefinition: (node: es.PropertyDefinition) => { const entry = getEntry(); if (entry && entry.hasDecorator) { entry.propertyDefinitions.push(node); } }, "MethodDefinition[key.name='ngOnDestroy'][kind='method']": ( node: es.MethodDefinition ) => { const entry = getEntry(); if (entry && entry.hasDecorator) { entry.ngOnDestroyDefinition = node; } }, "MethodDefinition[key.name='ngOnDestroy'][kind='method'] CallExpression[callee.property.name='next']": (node: es.CallExpression) => { const entry = getEntry(); if (entry && entry.hasDecorator) { entry.nextCallExpressions.push(node); } }, "MethodDefinition[key.name='ngOnDestroy'][kind='method'] CallExpression[callee.property.name='complete']": (node: es.CallExpression) => { const entry = getEntry(); if (entry && entry.hasDecorator) { entry.completeCallExpressions.push(node); } }, }; }, }); export = rule;
the_stack
import test from 'ava'; import * as common from '../../../../../../common'; import {Table} from '../table'; import {Image} from '../../image'; import {Button} from '..'; test('basic complete use case works', t => { const table = new Table({ title: 'title', subtitle: 'subtitle', image: new Image({ url: 'image url', alt: 'alt', }), columns: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: false, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: true, }, ], buttons: [ new Button({ title: 'title', url: 'button url', }), ], }); t.deepEqual(common.clone(table), { title: 'title', subtitle: 'subtitle', image: { url: 'image url', accessibilityText: 'alt', }, rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: false, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: true, }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], buttons: [ { title: 'title', openUrlAction: { url: 'button url', }, }, ], }); }); test('strings as rows work', t => { const table = new Table({ columns: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ ['first', 'second', 'third'], ['first 2', 'second 2', 'third 2'], ], }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('rows work with default dividers true', t => { const table = new Table({ columns: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], dividers: true, }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: true, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: true, }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('rows work with default dividers true and overridden by dividerAfter', t => { const table = new Table({ columns: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: false, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: true, }, ], dividers: true, }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: false, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: true, }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('rows work with default dividers false and overridden by dividerAfter', t => { const table = new Table({ columns: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: false, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: true, }, ], dividers: false, }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: false, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: true, }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('strings as rows work with default dividers true', t => { const table = new Table({ columns: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ ['first', 'second', 'third'], ['first 2', 'second 2', 'third 2'], ], dividers: true, }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: true, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: true, }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('strings as rows work with default dividers false', t => { const table = new Table({ columns: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ ['first', 'second', 'third'], ['first 2', 'second 2', 'third 2'], ], dividers: false, }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: false, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: false, }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('raw columnProperties works with align alias', t => { const table = new Table({ columnProperties: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('raw columnProperties works with raw alignment property', t => { const table = new Table({ columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('columns works with raw alignment property', t => { const table = new Table({ columns: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('columns works with number', t => { const table = new Table({ columns: 3, rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], columnProperties: [{}, {}, {}], }); }); test('columns works with number and columnProperties already set', t => { const table = new Table({ columnProperties: [ { header: 'test', }, ], columns: 3, rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], columnProperties: [ { header: 'test', }, {}, {}, ], }); }); test('a single Button works', t => { const table = new Table({ columns: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], buttons: new Button({ title: 'title', url: 'button url', }), }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], buttons: [ { title: 'title', openUrlAction: { url: 'button url', }, }, ], }); }); test('cells as strings works', t => { const table = new Table({ columns: [ { header: 'column 1', align: 'CENTER', }, { header: 'column 2', align: 'LEADING', }, { header: 'column 2', align: 'TRAILING', }, ], rows: [ { cells: ['first', 'second', 'third'], dividerAfter: false, }, { cells: ['first 2', 'second 2', 'third 2'], dividerAfter: true, }, ], }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], dividerAfter: false, }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], dividerAfter: true, }, ], columnProperties: [ { header: 'column 1', horizontalAlignment: 'CENTER', }, { header: 'column 2', horizontalAlignment: 'LEADING', }, { header: 'column 2', horizontalAlignment: 'TRAILING', }, ], }); }); test('columns as strings work', t => { const table = new Table({ columns: ['column 1', 'column 2', 'column 2'], rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], }); t.deepEqual(common.clone(table), { rows: [ { cells: [ { text: 'first', }, { text: 'second', }, { text: 'third', }, ], }, { cells: [ { text: 'first 2', }, { text: 'second 2', }, { text: 'third 2', }, ], }, ], columnProperties: [ { header: 'column 1', }, { header: 'column 2', }, { header: 'column 2', }, ], }); });
the_stack
import { expect } from "chai"; import { DOM } from "@microsoft/fast-element"; import { fixture } from "../test-utilities/fixture"; import { Button, buttonTemplate as template } from "./index"; const FASTButton = Button.compose({ baseName: "button", template }) async function setup() { const { connect, disconnect, element, parent } = await fixture(FASTButton()); return { connect, disconnect, element, parent }; } describe("Button", () => { it("should set the `autofocus` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); element.autofocus = true; await connect(); expect( element.shadowRoot?.querySelector("button")?.hasAttribute("autofocus") ).to.equal(true); await disconnect(); }); it("should set the `disabled` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); element.disabled = true; await connect(); expect( element.shadowRoot?.querySelector("button")?.hasAttribute("disabled") ).to.equal(true); await disconnect(); }); it("should set the `form` attribute on the internal button when `formId` is provided", async () => { const { element, connect, disconnect } = await setup(); const formId: string = "testId"; element.formId = "testId"; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("form") ).to.equal(formId); await disconnect(); }); it("should set the `formaction` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const formaction: string = "test_action.asp"; element.formaction = formaction; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("formaction") ).to.equal(formaction); await disconnect(); }); it("should set the `formenctype` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const formenctype: string = "text/plain"; element.formenctype = formenctype; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("formenctype") ).to.equal(formenctype); await disconnect(); }); it("should set the `formmethod` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const formmethod: string = "post"; element.formmethod = formmethod; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("formmethod") ).to.equal(formmethod); await disconnect(); }); it("should set the `formnovalidate` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const formnovalidate: boolean = true; element.formnovalidate = formnovalidate; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("formnovalidate") ).to.equal(formnovalidate.toString()); await disconnect(); }); it("should set the `formtarget` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const formtarget = "_blank"; element.formtarget = formtarget; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("formtarget") ).to.equal(formtarget); await disconnect(); }); it("should set the `name` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const name = "testName"; element.name = name; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("name") ).to.equal(name); await disconnect(); }); it("should set the `type` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const type = "submit"; element.type = type; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("type") ).to.equal(type); await disconnect(); }); it("should set the `value` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const value = "Reset"; element.value = value; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("value") ).to.equal(value); await disconnect(); }); describe("Delegates ARIA button", () => { it("should set the `aria-atomic` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaAtomic = "true"; element.ariaAtomic = ariaAtomic; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-atomic") ).to.equal(ariaAtomic); await disconnect(); }); it("should set the `aria-busy` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaBusy = "false"; element.ariaBusy = ariaBusy; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-busy") ).to.equal(ariaBusy); await disconnect(); }); it("should set the `aria-controls` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaControls = "testId"; element.ariaControls = ariaControls; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-controls") ).to.equal(ariaControls); await disconnect(); }); it("should set the `aria-current` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaCurrent = "page"; element.ariaCurrent = ariaCurrent; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-current") ).to.equal(ariaCurrent); await disconnect(); }); it("should set the `aria-describedby` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaDescribedby = "testId"; element.ariaDescribedby = ariaDescribedby; await connect(); expect( element.shadowRoot ?.querySelector("button") ?.getAttribute("aria-describedby") ).to.equal(ariaDescribedby); await disconnect(); }); it("should set the `aria-details` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaDetails = "testId"; element.ariaDetails = ariaDetails; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-details") ).to.equal(ariaDetails); await disconnect(); }); it("should set the `aria-disabled` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaDisabled = "true"; element.ariaDisabled = ariaDisabled; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-disabled") ).to.equal(ariaDisabled); await disconnect(); }); it("should set the `aria-errormessage` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaErrormessage = "test"; element.ariaErrormessage = ariaErrormessage; await connect(); expect( element.shadowRoot ?.querySelector("button") ?.getAttribute("aria-errormessage") ).to.equal(ariaErrormessage); await disconnect(); }); it("should set the `aria-expanded` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaExpanded = "true"; element.ariaExpanded = ariaExpanded; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-expanded") ).to.equal(ariaExpanded); await disconnect(); }); it("should set the `aria-flowto` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaFlowto = "testId"; element.ariaFlowto = ariaFlowto; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-flowto") ).to.equal(ariaFlowto); await disconnect(); }); it("should set the `aria-haspopup` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaHaspopup = "true"; element.ariaHaspopup = ariaHaspopup; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-haspopup") ).to.equal(ariaHaspopup); await disconnect(); }); it("should set the `aria-hidden` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaHidden = "true"; element.ariaHidden = ariaHidden; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-hidden") ).to.equal(ariaHidden); await disconnect(); }); it("should set the `aria-invalid` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaInvalid = "spelling"; element.ariaInvalid = ariaInvalid; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-invalid") ).to.equal(ariaInvalid); await disconnect(); }); it("should set the `aria-keyshortcuts` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaKeyshortcuts = "F4"; element.ariaKeyshortcuts = ariaKeyshortcuts; await connect(); expect( element.shadowRoot ?.querySelector("button") ?.getAttribute("aria-keyshortcuts") ).to.equal(ariaKeyshortcuts); await disconnect(); }); it("should set the `aria-label` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaLabel = "Foo label"; element.ariaLabel = ariaLabel; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-label") ).to.equal(ariaLabel); await disconnect(); }); it("should set the `aria-labelledby` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaLabelledby = "testId"; element.ariaLabelledby = ariaLabelledby; await connect(); expect( element.shadowRoot ?.querySelector("button") ?.getAttribute("aria-labelledby") ).to.equal(ariaLabelledby); await disconnect(); }); it("should set the `aria-live` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaLive = "polite"; element.ariaLive = ariaLive; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-live") ).to.equal(ariaLive); await disconnect(); }); it("should set the `aria-owns` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaOwns = "testId"; element.ariaOwns = ariaOwns; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-owns") ).to.equal(ariaOwns); await disconnect(); }); it("should set the `aria-pressed` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaPressed = "true"; element.ariaPressed = ariaPressed; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-pressed") ).to.equal(ariaPressed); await disconnect(); }); it("should set the `aria-relevant` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaRelevant = "removals"; element.ariaRelevant = ariaRelevant; await connect(); expect( element.shadowRoot?.querySelector("button")?.getAttribute("aria-relevant") ).to.equal(ariaRelevant); await disconnect(); }); it("should set the `aria-roledescription` attribute on the internal button when provided", async () => { const { element, connect, disconnect } = await setup(); const ariaRoledescription = "slide"; element.ariaRoledescription = ariaRoledescription; await connect(); expect( element.shadowRoot ?.querySelector("button") ?.getAttribute("aria-roledescription") ).to.equal(ariaRoledescription); await disconnect(); }); }); describe("of type 'submit'", () => { it("should submit the parent form when clicked", async () => { const { connect, disconnect, element, parent } = await setup(); const form = document.createElement("form"); element.setAttribute("type", "submit"); form.appendChild(element); parent.appendChild(form); await connect(); const wasSumbitted = await new Promise(resolve => { // Resolve as true when the event listener is handled form.addEventListener( "submit", (event: Event & { submitter: HTMLElement }) => { event.preventDefault(); expect(event.submitter).to.equal(element.proxy); resolve(true); } ); element.click(); // Resolve false on the next update in case reset hasn't happened DOM.queueUpdate(() => resolve(false)); }); expect(wasSumbitted).to.equal(true); await disconnect(); }); }); describe("of type 'reset'", () => { it("should reset the parent form when clicked", async () => { const { connect, disconnect, element, parent } = await setup(); const form = document.createElement("form"); element.setAttribute("type", "reset"); form.appendChild(element); parent.appendChild(form); await connect(); const wasReset = await new Promise(resolve => { // Resolve true when the event listener is handled form.addEventListener("reset", () => resolve(true)); element.click(); // Resolve false on the next update in case reset hasn't happened DOM.queueUpdate(() => resolve(false)); }); expect(wasReset).to.equal(true); await disconnect(); }); }); });
the_stack
import { expect } from 'chai'; import { TestScope } from 'cavy'; import notifee, { AndroidChannel, EventType, Event, AndroidImportance, TimestampTrigger, TriggerType, RepeatFrequency, AndroidStyle, } from '@notifee/react-native'; import { Platform } from 'react-native'; export function NotificationSpec(spec: TestScope): void { spec.beforeEach(async () => { const channels: AndroidChannel[] = [ { name: 'High Importance', id: 'high', importance: AndroidImportance.HIGH, }, { name: 'New 🐴 Sound', id: 'new_custom_sound', importance: AndroidImportance.HIGH, sound: 'horse.mp3', }, { name: 'Default Importance', id: 'default', importance: AndroidImportance.DEFAULT, }, { name: 'Low Importance', id: 'low', importance: AndroidImportance.LOW, }, { name: 'Min Importance', id: 'min', importance: AndroidImportance.MIN, }, ]; await notifee.createChannels(channels); // TODO doesn't work in tests as blocks with a UI prompt await notifee.requestPermission(); // Clear notifications between tests await notifee.cancelAllNotifications(); }); spec.describe('displayNotification', function () { spec.it('configures custom sounds correctly', async function () { const customSoundChannel = await notifee.getChannel('new_custom_sound'); console.warn('customSoundChannel looks like: ' + JSON.stringify(customSoundChannel)); if (Platform.OS === 'android') { expect(customSoundChannel.soundURI).contains('horse.mp3'); expect(customSoundChannel.sound).equals('horse.mp3'); } }); spec.it('displays a notification', async function () { return new Promise(async (resolve, reject) => { const unsubscribe = notifee.onForegroundEvent((event: Event) => { try { if (event.type === EventType.DELIVERED) { expect(event.detail.notification).not.equal(undefined); if (event.detail.notification) { expect(event.detail.notification.title).equals('Hello'); expect(event.detail.notification.body).equals('World'); } unsubscribe(); resolve(); } } catch (e) { unsubscribe(); reject(e); } }); return notifee.displayNotification({ title: 'Hello', body: 'World', android: { channelId: 'high', }, }); }); }); spec.it('displays a empty notification', async function () { return new Promise(async (resolve, reject) => { return notifee .displayNotification({ title: undefined, body: undefined, android: { channelId: 'high', }, }) .then(id => { expect(id).equals(id); resolve(); }) .catch(e => { reject(e); }); }); }); spec.it( 'displays a notification with AndroidStyle.BIGPICTURE and largeIcon as null', async function () { const testId = 'test-id'; const testLargeIcon = 'test-large-icon'; const testBigPicture = 'test-picture'; if (Platform.OS === 'ios') { return; } return new Promise(async (resolve, reject) => { const unsubscribe = notifee.onForegroundEvent(async (event: Event) => { try { expect(event.type).equals(EventType.DELIVERED); expect(event.detail.notification?.id).equals(testId); const androidNotification = event.detail.notification?.android; expect(androidNotification.style.type).equals(AndroidStyle.BIGPICTURE); if (androidNotification.style.type === AndroidStyle.BIGPICTURE) { expect(androidNotification.style.picture).equals(testBigPicture); expect(androidNotification.style.largeIcon).null; } unsubscribe(); resolve(); } catch (e) { unsubscribe(); reject(e); } }); await notifee .displayNotification({ id: testId, title: '', body: '', android: { channelId: 'high', largeIcon: testLargeIcon, style: { type: AndroidStyle.BIGPICTURE, largeIcon: null, picture: testBigPicture, }, }, }) .then(id => { expect(id).equals(id); }) .catch(e => { reject(e); }); }); }, ); spec.describe('displayNotification with pressAction', function () { spec.it('displays a notification with a pressAction with id `default`', async function () { return new Promise(async (resolve, reject) => { return notifee .displayNotification({ title: '', body: '', android: { channelId: 'high', pressAction: { id: 'default', }, }, }) .then(id => { expect(id).equals(id); resolve(); }) .catch(e => { reject(e); }); }); }); spec.it('silently fails if `launchActivity` does not exist', async function () { return new Promise(async (resolve, reject) => { return notifee .displayNotification({ title: '', body: '', android: { channelId: 'high', pressAction: { id: 'default', launchActivity: 'com.app.invalid', }, }, }) .then(id => { expect(id).equals(id); resolve(); }) .catch(e => { reject(e); }); }); }); }); spec.describe('displayNotification with quick actions', function () { spec.it( 'displays a notification with a quick action with input set to true', async function () { return new Promise(async (resolve, reject) => { return notifee .displayNotification({ title: '', body: '', android: { channelId: 'high', actions: [ { title: 'First Action', pressAction: { id: 'first_action', }, input: true, }, ], }, }) .then(id => { expect(id).equals(id); resolve(); }) .catch(e => { reject(e); }); }); }, ); }); }); spec.describe('createTriggerNotification', function () { spec.describe('timestampTrigger', function () { spec.describe('alarmManager', function () { spec.it('not repeating', async function () { // FIXME on iOS this has notification parts missing, see #191 if (Platform.OS === 'ios') { return; } return new Promise(async (resolve, reject) => { const timestamp = new Date(Date.now()); timestamp.setSeconds(timestamp.getSeconds() + 1); const trigger: TimestampTrigger = { type: TriggerType.TIMESTAMP, timestamp: timestamp.getTime(), alarmManager: true, }; const notification = { id: `alarm-manger-${timestamp.getTime()}`, title: 'AlarmManager', body: 'Not Repeating', android: { channelId: 'high', }, }; let receivedCreatedEvent = false; const unsubscribe = notifee.onForegroundEvent(async (event: Event) => { try { // We get a trigger created event first on android... if (Platform.OS === 'android' && !receivedCreatedEvent) { expect(event.type).equals(EventType.TRIGGER_NOTIFICATION_CREATED); receivedCreatedEvent = true; return; } // ...then we get the trigger expect(event.type).equals(EventType.DELIVERED); expect(event.detail.notification).not.equal(undefined); if (event.detail.notification) { expect(event.detail.notification.title).equals(notification.title); expect(event.detail.notification.body).equals(notification.body); } // Check next trigger has not been set const triggerNotificationIds = await notifee.getTriggerNotificationIds(); expect(triggerNotificationIds.length).equals(0); unsubscribe(); resolve(); } catch (e) { unsubscribe(); reject(e); } }); await notifee.createTriggerNotification(notification, trigger); }); }); spec.it('repeating', async function () { // FIXME on iOS this has notification parts missing, see #191 if (Platform.OS === 'ios') { return; } return new Promise(async (resolve, reject) => { const timestamp = new Date(Date.now()); timestamp.setSeconds(timestamp.getSeconds() + 1); const trigger: TimestampTrigger = { type: TriggerType.TIMESTAMP, timestamp: timestamp.getTime(), alarmManager: true, repeatFrequency: RepeatFrequency.HOURLY, }; const notification = { id: `alarm-manager-repeating-${timestamp.getTime()}`, title: 'AlarmManager', body: 'Repeating', android: { channelId: 'high', }, }; let receivedCreatedEvent = false; let receivedTriggerEvent = false; const unsubscribe = notifee.onForegroundEvent(async (event: Event) => { try { // We get a trigger created event first on android... if (Platform.OS === 'android' && !receivedCreatedEvent) { expect(event.type).equals(EventType.TRIGGER_NOTIFICATION_CREATED); receivedCreatedEvent = true; return; } // ...then we get the trigger expect(event.type).equals(EventType.DELIVERED); expect(event.detail.notification).not.equal(undefined); if (event.detail.notification) { expect(event.detail.notification.title).equals(notification.title); expect(event.detail.notification.body).equals(notification.body); } receivedTriggerEvent = true; // Check next trigger has been set const triggerNotificationIds = await notifee.getTriggerNotificationIds(); expect(triggerNotificationIds.length).equals(1); expect(triggerNotificationIds.includes(notification.id)).equals(true); unsubscribe(); await notifee.cancelTriggerNotifications(); resolve(); } catch (e) { unsubscribe(); await notifee.cancelTriggerNotifications(); reject(e); } }); notifee.createTriggerNotification(notification, trigger); // Make sure we receive the trigger within a reasonable time setTimeout(async () => { try { expect(receivedTriggerEvent).equals(true); resolve(); } catch (e) { reject(new Error('Did not receive trigger in a reasonable amount of time')); } finally { unsubscribe(); notifee.cancelTriggerNotifications(); } }, 600000); }); }); }); }); }); }
the_stack
import chalk from 'chalk'; import { SetDifference } from 'utility-types'; import { AliasRecord } from '../../util/alias/create-alias'; import { Domain } from '../../types'; import { Output } from '../../util/output'; import * as ERRORS from '../../util/errors-ts'; import assignAlias from '../../util/alias/assign-alias'; import Client from '../../util/client'; import getDeploymentByIdOrHost from '../../util/deploy/get-deployment-by-id-or-host'; import { getDeploymentForAlias } from '../../util/alias/get-deployment-by-alias'; import getScope from '../../util/get-scope'; import setupDomain from '../../util/domains/setup-domain'; import stamp from '../../util/output/stamp'; import { isValidName } from '../../util/is-valid-name'; import handleCertError from '../../util/certs/handle-cert-error'; import isWildcardAlias from '../../util/alias/is-wildcard-alias'; import link from '../../util/output/link'; import { User } from '../../types'; import { getCommandName } from '../../util/pkg-name'; import toHost from '../../util/to-host'; import { VercelConfig } from '../../util/dev/types'; type Options = { '--debug': boolean; '--local-config': string; }; export default async function set( client: Client, opts: Partial<Options>, args: string[] ) { const { output, localConfig } = client; const setStamp = stamp(); let user: User; let contextName: string | null = null; try { ({ contextName, user } = await getScope(client)); } catch (err) { if (err.code === 'NOT_AUTHORIZED' || err.code === 'TEAM_DELETED') { output.error(err.message); return 1; } throw err; } // If there are more than two args we have to error if (args.length > 2) { output.error( `${getCommandName( `alias <deployment> <target>` )} accepts at most two arguments` ); return 1; } if (args.length >= 1 && !isValidName(args[0])) { output.error( `The provided argument "${args[0]}" is not a valid deployment` ); return 1; } if (args.length >= 2 && !isValidName(args[1])) { output.error(`The provided argument "${args[1]}" is not a valid domain`); return 1; } if (args.length === 0) { output.error( `To ship to production, optionally configure your domains (${link( 'https://vercel.link/domain-configuration' )}) and run ${getCommandName(`--prod`)}.` ); return 1; } // For `vercel alias set <argument>` if (args.length === 1) { const deployment = handleCertError( output, await getDeploymentForAlias( client, output, args, opts['--local-config'], user, contextName, localConfig ) ); if (deployment === 1) { return deployment; } if (deployment instanceof Error) { output.error(deployment.message); return 1; } if (!deployment) { output.error( `Couldn't find a deployment to alias. Please provide one as an argument.` ); return 1; } // Find the targets to perform the alias const targets = getTargetsForAlias(args, localConfig); if (targets instanceof Error) { output.prettyError(targets); return 1; } for (const target of targets) { output.log(`Assigning alias ${target} to deployment ${deployment.url}`); const record = await assignAlias( output, client, deployment, target, contextName ); const handleResult = handleSetupDomainError( output, handleCreateAliasError(output, record) ); if (handleResult === 1) { return 1; } console.log( `${chalk.cyan('> Success!')} ${chalk.bold( `${isWildcardAlias(target) ? '' : 'https://'}${handleResult.alias}` )} now points to https://${deployment.url} ${setStamp()}` ); } return 0; } const [deploymentIdOrHost, aliasTarget] = args; const deployment = handleCertError( output, await getDeploymentByIdOrHost(client, contextName, deploymentIdOrHost) ); if (deployment === 1) { return deployment; } if (deployment instanceof ERRORS.DeploymentNotFound) { output.error( `Failed to find deployment "${deployment.meta.id}" under ${chalk.bold( contextName )}` ); return 1; } if (deployment instanceof ERRORS.DeploymentPermissionDenied) { output.error( `No permission to access deployment "${ deployment.meta.id }" under ${chalk.bold(deployment.meta.context)}` ); return 1; } if (deployment instanceof ERRORS.InvalidDeploymentId) { output.error(deployment.message); return 1; } if (deployment === null) { output.error( `Couldn't find a deployment to alias. Please provide one as an argument.` ); return 1; } output.log(`Assigning alias ${aliasTarget} to deployment ${deployment.url}`); const isWildcard = isWildcardAlias(aliasTarget); const record = await assignAlias( output, client, deployment, aliasTarget, contextName ); const handleResult = handleSetupDomainError( output, handleCreateAliasError(output, record) ); if (handleResult === 1) { return 1; } const prefix = isWildcard ? '' : 'https://'; console.log( `${chalk.cyan('> Success!')} ${chalk.bold( `${prefix}${handleResult.alias}` )} now points to https://${deployment.url} ${setStamp()}` ); return 0; } type ThenArg<T> = T extends Promise<infer U> ? U : T; type SetupDomainResolve = ThenArg<ReturnType<typeof setupDomain>>; type SetupDomainError = Exclude<SetupDomainResolve, Domain>; function handleSetupDomainError<T>( output: Output, error: SetupDomainError | T ): T | 1 { if (error instanceof ERRORS.DomainPermissionDenied) { output.error( `You don't have permissions over domain ${chalk.underline( error.meta.domain )} under ${chalk.bold(error.meta.context)}.` ); return 1; } if (error instanceof ERRORS.UserAborted) { output.error(`User aborted`); return 1; } if (error instanceof ERRORS.DomainNotFound) { output.error(`You should buy the domain before aliasing.`); return 1; } if (error instanceof ERRORS.UnsupportedTLD) { output.error( `The TLD for domain name ${error.meta.domain} is not supported.` ); return 1; } if (error instanceof ERRORS.InvalidDomain) { output.error( `The domain ${error.meta.domain} used for the alias is not valid.` ); return 1; } if (error instanceof ERRORS.DomainNotAvailable) { output.error( `The domain ${error.meta.domain} is not available to be purchased.` ); return 1; } if (error instanceof ERRORS.DomainServiceNotAvailable) { output.error( `The domain purchase service is not available. Try again later.` ); return 1; } if (error instanceof ERRORS.UnexpectedDomainPurchaseError) { output.error(`There was an unexpected error while purchasing the domain.`); return 1; } if (error instanceof ERRORS.DomainAlreadyExists) { output.error( `The domain ${error.meta.domain} exists for a different account.` ); return 1; } if (error instanceof ERRORS.DomainPurchasePending) { output.error( `The domain ${error.meta.domain} is processing and will be available once the order is completed.` ); output.print( ` An email will be sent upon completion so you can alias to your new domain.\n` ); return 1; } if (error instanceof ERRORS.SourceNotFound) { output.error( `You can't purchase the domain you're aliasing to since you have no valid payment method.` ); output.print(` Please add a valid payment method and retry.\n`); return 1; } if (error instanceof ERRORS.DomainPaymentError) { output.error( `You can't purchase the domain you're aliasing to since your card was declined.` ); output.print(` Please add a valid payment method and retry.\n`); return 1; } return error; } type AliasResolved = ThenArg<ReturnType<typeof assignAlias>>; type AssignAliasError = Exclude<AliasResolved, AliasRecord>; type RemainingAssignAliasErrors = SetDifference< AssignAliasError, SetupDomainError >; function handleCreateAliasError<T>( output: Output, errorOrResult: RemainingAssignAliasErrors | T ): 1 | T { const error = handleCertError(output, errorOrResult); if (error === 1) { return error; } if (error instanceof ERRORS.AliasInUse) { output.error( `The alias ${chalk.dim( error.meta.alias )} is a deployment URL or it's in use by a different team.` ); return 1; } if (error instanceof ERRORS.DeploymentNotFound) { output.error( `Failed to find deployment ${chalk.dim(error.meta.id)} under ${chalk.bold( error.meta.context )}` ); return 1; } if (error instanceof ERRORS.InvalidAlias) { output.error( `Invalid alias. Please confirm that the alias you provided is a valid hostname. Note: For \`vercel.app\`, only sub and sub-sub domains are supported.` ); return 1; } if (error instanceof ERRORS.DeploymentPermissionDenied) { output.error( `No permission to access deployment ${chalk.dim( error.meta.id )} under ${chalk.bold(error.meta.context)}` ); return 1; } if (error instanceof ERRORS.CertMissing) { output.error( `There is no certificate for the domain ${error.meta.domain} and it could not be created.` ); output.log( `Please generate a new certificate manually with ${getCommandName( `certs issue ${error.meta.domain}` )}` ); return 1; } if (error instanceof ERRORS.InvalidDomain) { output.error( `The domain ${error.meta.domain} used for the alias is not valid.` ); return 1; } if ( error instanceof ERRORS.DomainPermissionDenied || error instanceof ERRORS.DeploymentFailedAliasImpossible || error instanceof ERRORS.InvalidDeploymentId ) { output.error(error.message); return 1; } if (error instanceof ERRORS.DeploymentNotReady) { output.error(error.message); return 1; } return error; } function getTargetsForAlias(args: string[], { alias }: VercelConfig = {}) { if (args.length) { return [args[args.length - 1]] .map(target => (target.indexOf('.') !== -1 ? toHost(target) : target)) .filter((x): x is string => !!x && typeof x === 'string'); } if (!alias) { return new ERRORS.NoAliasInConfig(); } // Check the type for the option aliases if (typeof alias !== 'string' && !Array.isArray(alias)) { return new ERRORS.InvalidAliasInConfig(alias); } return typeof alias === 'string' ? [alias] : alias; }
the_stack
import { Injectable, Injector } from "@angular/core"; import { ListNode, AjaxResult, AjaxResultType, AuthConfig, VerifyCode, FilterOperate, FilterOperateEntry } from "@shared/osharp/osharp.model"; import { NzMessageService, NzMessageDataOptions } from "ng-zorro-antd"; import { Router } from "@angular/router"; import { Buffer } from "buffer"; import { Observable, of } from "rxjs"; import { List } from "linqts"; import { _HttpClient } from "@delon/theme"; import { ACLService } from "@delon/acl"; import { ErrorData } from "@delon/form"; @Injectable({ providedIn: "root" }) export class OsharpService { constructor(private injector: Injector, public msgSrv: NzMessageService, public http: _HttpClient, private aclSrv: ACLService) {} public get router(): Router { return this.injector.get(Router); } //#region 远程验证 private timeout1; private timeout2; // #endregion // #region 消息方法 private msgOptions: NzMessageDataOptions = { nzDuration: 1000 * 3, nzAnimate: true, nzPauseOnHover: true }; // #endregion // #region 静态数据 data = { accessType: [ { id: 0, text: "匿名访问" }, { id: 1, text: "登录访问" }, { id: 2, text: "角色访问" } ], stringFilterable: { operators: { string: { contains: "包含", eq: "等于", neq: "不等于", startswith: "开始于", endswith: "结束于", doesnotcontain: "不包含" } } }, dataAuthOperations: [ { id: 0, text: "读取" }, { id: 1, text: "更新" }, { id: 2, text: "删除" } ], operateType: [ { id: 1, text: "新增" }, { id: 2, text: "更新" }, { id: 3, text: "删除" } ], ajaxResultType: [ { id: 200, text: "成功" }, { id: 203, text: "消息" }, { id: 401, text: "未登录" }, { id: 403, text: "无权操作" }, { id: 404, text: "不存在" }, { id: 423, text: "锁定" }, { id: 500, text: "错误" } ], packLevel: [ { id: 1, text: "Core" }, { id: 10, text: "Framework" }, { id: 20, text: "Application" }, { id: 30, text: "Business" } ] }; // #region 工具方法 /** * URL编码 * @param url 待编码的URL */ urlEncode(url: string): string { return encodeURIComponent(url); } /** * URL解码 * @param url 待解码的URL */ urlDecode(url: string): string { return decodeURIComponent(url); } /** * Base64字符串解码 * @param base64 待编码的字符串 */ fromBase64(base64: string): string { return new Buffer(base64, "base64").toString(); } /** * Base64字符串编码 * @param str 待解码的Base64字符串 */ toBase64(str: string): string { return new Buffer(str).toString("base64"); } /** * 获取URL中Hash串中的查询参数值 * @param url URL字符串 * @param name 参数名 */ getHashURLSearchParams(url: string, name: string): string { if (url.indexOf("#") >= 0) { url = this.subStr(url, "#"); } if (url.indexOf("?") >= 0) { url = this.subStr(url, "?"); } const params = new URLSearchParams(url); return params.get(name); } /** * 提供首尾字符串截取中间的字符串 * @param str 待截取的字符串 * @param start 起始的字符串 * @param end 结束的字符串 */ subStr(str: string, start: string = null, end: string = null): string { let startIndex = 0; let endIndex = str.length; if (start) { startIndex = str.indexOf(start) + start.length; } if (end) { endIndex = str.indexOf(end); } return str.substr(startIndex, endIndex - startIndex); } /** * 从集合中删除符合条件的项 * @param items 集合 * @param exp 删除项查询表达式 */ remove<T>(items: Array<T>, exp: (value: T, index: number, obj: T[]) => boolean) { const index = items.findIndex(exp); items.splice(index, 1); return items; } /** * 值转文字 * @param id 待转换的值 * @param array 数据节点集合 * @param defaultText 转换失败时的默认文字 */ valueToText(id: number, array: { id: number; text: string }[] | ListNode[], defaultText: string = null) { let text = defaultText == null ? id.toString() : defaultText; array.forEach((item) => { if (item.id === id) { text = item.text; return false; } return true; }); return text; } /** * 展开集合拼接字符串 * @param array 待展开的集合 * @param separator 分隔符 */ expandAndToString(array: Array<any>, separator: string = ",") { let result = ""; if (!array || !array.length) { return result; } array.forEach((item) => { result = result + item.toString() + separator; }); return result.substr(0, result.length - separator.length); } /** * 下载数据 * @param filename 存储的文件名 * @param content 下载得到的内容 */ download(filename: string, content: string) { const urlObject = window.URL; const blob = new Blob([ content ]); const saveLink = document.createElement("a"); saveLink.href = urlObject.createObjectURL(blob); saveLink.download = filename; const ev = document.createEvent("MouseEvents"); ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); saveLink.dispatchEvent(ev); } /** * 打开Email的网站 * @param email Email地址 */ openMailSite(email: string) { const host = this.subStr(email, "@"); const url = `http://mail.${host}`; window.open(url); } goto(url: string) { setTimeout(() => this.router.navigateByUrl(url)); } /** * 处理Ajax结果 * @param res HTTP响应 * @param onSuccess 成功后的调用 * @param onFail 失败后的调用 */ ajaxResult(res, onSuccess?, onFail?) { if (!res || !res.Type) { return; } const result = res as AjaxResult; const type = result.Type; const content = result.Content; switch (type) { case AjaxResultType.Info: this.info(content); break; case AjaxResultType.NoFound: this.router.navigateByUrl("/nofound"); break; case AjaxResultType.UnAuth: this.warning("用户未登录或登录已失效"); this.router.navigateByUrl("/passport/login"); break; case AjaxResultType.Success: this.success(content); if (onSuccess && typeof onSuccess === "function") { onSuccess(); } break; default: this.error(content); if (onFail && typeof onFail === "function") { onFail(); } break; } } /** * 处理Ajax错误 * @param xhr 错误响应 */ ajaxError(xhr) { switch (xhr.status) { case 401: this.warning("用户未登录或登录已失效"); this.router.navigateByUrl("/identity/login"); break; case 404: this.router.navigateByUrl("/nofound"); break; default: this.error(`发生错误:${xhr.status}: ${xhr.statusText}`); break; } } remoteSFValidator(url: string, error: ErrorData): ErrorData[] | Observable<ErrorData[]> { clearTimeout(this.timeout1); return new Observable((observer) => { this.timeout1 = setTimeout(() => { this.http.get(url).subscribe((res) => { if (res !== true) { observer.next([]); } else { observer.next([ error ]); } }); }, 800); }); } remoteInverseSFValidator(url: string, error: ErrorData): ErrorData[] | Observable<ErrorData[]> { clearTimeout(this.timeout2); return new Observable((observer) => { this.timeout2 = setTimeout(() => { this.http.get(url).subscribe((res) => { if (res !== true) { observer.next([ error ]); } else { observer.next([]); } }); }, 800); }); } //#endregion //#region 验证码处理 /** * 获取验证码 */ refreshVerifyCode(): Observable<VerifyCode> { const url = "api/common/verifycode"; return this.http.get(url, null, { responseType: "text" }).map((res) => { const str = this.fromBase64(res.toString()); const strs: string[] = str.split("#$#"); const code: VerifyCode = new VerifyCode(); code.image = strs[0]; code.id = strs[1]; return code; }); } //#endregion /** * 获取树节点集合 * @param root 根节点 * @param array 节点集合 */ getTreeNodes(root: any, array: Array<any>) { array.push(root); if (root.hasChildren) { for (const item of root.Items) { this.getTreeNodes(item, array); } } } /** * 检查URL的功能权限 * @param url 要检查权限的后端URL */ checkUrlAuth(url: string): Promise<boolean> { if (!url.startsWith("https:") && !url.startsWith("http") && !url.startsWith("/")) { url = `/${url}`; } url = this.urlEncode(url); return this.http.get<boolean>("api/auth/CheckUrlAuth?url=" + url).toPromise(); } /** * 获取当前用户的权限点数据(string[]),如本地 ACLServer 中不存在,则从远程获取,并更新到 ACLServer 中 */ getAuthInfo(refresh?: boolean): Observable<string[]> { if (!refresh && this.aclSrv.data.abilities && this.aclSrv.data.abilities.length) { const authInfo: string[] = this.aclSrv.data.abilities as string[]; return of(authInfo); } const url = "api/auth/getauthinfo"; return this.http.get<string[]>(url).map((auth) => { this.aclSrv.setAbility(auth); return auth; }); } getOperateEntries(operates: FilterOperate[]): FilterOperateEntry[] { return new List(operates).Select((m) => new FilterOperateEntry(m)).ToArray(); } /** * 消息加载中 * @param msg 消息字符串 */ loading(msg) { return this.msgSrv.loading(msg, this.msgOptions); } /** * 成功的消息 * @param msg 消息字符串 */ success(msg) { return this.msgSrv.success(msg, this.msgOptions); } /** * 消息的消息 * @param msg 消息字符串 */ info(msg) { return this.msgSrv.info(msg, this.msgOptions); } /** * 警告的消息 * @param msg 消息字符串 */ warning(msg) { return this.msgSrv.warning(msg, this.msgOptions); } /** * 错误的消息 * @param msg 消息字符串 */ error(msg) { return this.msgSrv.error(msg, { nzDuration: 1000 * 6, nzAnimate: true, nzPauseOnHover: true }); } // #endregion } //#region 组件基类 /** * 组件基类,实现了权限控制 */ export abstract class ComponentBase { protected osharp: OsharpService; /** * 权限字典,以模块代码为键,是否有权限为值 */ public auth: any | { [key: string]: boolean } = {}; private authConfig: AuthConfig = null; constructor(injector: Injector) { this.osharp = injector.get(OsharpService); } /** * 重写以返回权限控制配置信息 */ protected abstract AuthConfig(): AuthConfig; /** * 初始化并执行权限检查,检查结果存储到 this.auth 中 */ async checkAuth() { if (this.authConfig == null) { this.authConfig = this.AuthConfig(); this.authConfig.funcs.forEach((key) => (this.auth[key] = true)); } const position = this.authConfig.position; const codes = await this.osharp.getAuthInfo().toPromise(); if (!codes) { return this.auth; } const list = new List(codes); for (const key in this.auth) { if (this.auth.hasOwnProperty(key)) { let path = key; if (!path.startsWith("Root.")) { path = `${position}.${path}`; } this.auth[key] = list.Contains(path); } } return this.auth; } } //#endregion
the_stack
import {classNames, SlotProvider, unwrapDOMRef, useDOMRef, useStyleProps} from '@react-spectrum/utils'; import {DOMProps, DOMRef, Node, Orientation} from '@react-types/shared'; import {filterDOMProps, useValueEffect} from '@react-aria/utils'; import {FocusRing} from '@react-aria/focus'; import {Item, Picker} from '@react-spectrum/picker'; import {ListCollection, SingleSelectListState} from '@react-stately/list'; import {mergeProps, useId, useLayoutEffect} from '@react-aria/utils'; import React, {Key, MutableRefObject, ReactElement, useCallback, useContext, useEffect, useRef, useState} from 'react'; import {SpectrumPickerProps} from '@react-types/select'; import {SpectrumTabListProps, SpectrumTabPanelsProps, SpectrumTabsProps} from '@react-types/tabs'; import styles from '@adobe/spectrum-css-temp/components/tabs/vars.css'; import {TabListState, useTabListState} from '@react-stately/tabs'; import {Text} from '@react-spectrum/text'; import {useCollection} from '@react-stately/collections'; import {useHover} from '@react-aria/interactions'; import {useLocale} from '@react-aria/i18n'; import {useProvider, useProviderProps} from '@react-spectrum/provider'; import {useResizeObserver} from '@react-aria/utils'; import {useTab, useTabList, useTabPanel} from '@react-aria/tabs'; interface TabsContext<T> { tabProps: SpectrumTabsProps<T>, tabState: { tabListState: TabListState<T>, setTabListState: (state: TabListState<T>) => void, selectedTab: HTMLElement, collapse: boolean }, refs: { wrapperRef: MutableRefObject<HTMLDivElement>, tablistRef: MutableRefObject<HTMLDivElement> }, tabPanelProps: { 'aria-labelledby': string } } const TabContext = React.createContext<TabsContext<any>>(null); function Tabs<T extends object>(props: SpectrumTabsProps<T>, ref: DOMRef<HTMLDivElement>) { props = useProviderProps(props); let { orientation = 'horizontal' as Orientation, density = 'regular', children, ...otherProps } = props; let domRef = useDOMRef(ref); let tablistRef = useRef<HTMLDivElement>(); let wrapperRef = useRef<HTMLDivElement>(); let {direction} = useLocale(); let {styleProps} = useStyleProps(otherProps); let [collapse, setCollapse] = useValueEffect(false); let [selectedTab, setSelectedTab] = useState<HTMLElement>(); const [tabListState, setTabListState] = useState<TabListState<T>>(null); useEffect(() => { if (tablistRef.current) { let selectedTab: HTMLElement = tablistRef.current.querySelector(`[data-key="${tabListState?.selectedKey}"]`); if (selectedTab != null) { setSelectedTab(selectedTab); } } // collapse is in the dep array so selectedTab can be updated for TabLine positioning }, [children, tabListState?.selectedKey, collapse, tablistRef]); let checkShouldCollapse = useCallback(() => { let computeShouldCollapse = () => { if (wrapperRef.current) { let tabsComponent = wrapperRef.current; let tabs = tablistRef.current.querySelectorAll('[role="tab"]'); let lastTab = tabs[tabs.length - 1]; let end = direction === 'rtl' ? 'left' : 'right'; let farEdgeTabList = tabsComponent.getBoundingClientRect()[end]; let farEdgeLastTab = lastTab?.getBoundingClientRect()[end]; let shouldCollapse = direction === 'rtl' ? farEdgeLastTab < farEdgeTabList : farEdgeTabList < farEdgeLastTab; return shouldCollapse; } }; if (orientation !== 'vertical') { setCollapse(function* () { // Make Tabs render in non-collapsed state yield false; // Compute if Tabs should collapse and update yield computeShouldCollapse(); }); } }, [tablistRef, wrapperRef, direction, orientation, setCollapse]); useEffect(() => { checkShouldCollapse(); }, [children, checkShouldCollapse]); useResizeObserver({ref: wrapperRef, onResize: checkShouldCollapse}); let tabPanelProps = { 'aria-labelledby': undefined }; // When the tabs are collapsed, the tabPanel should be labelled by the Picker button element. let collapsibleTabListId = useId(); if (collapse && orientation !== 'vertical') { tabPanelProps['aria-labelledby'] = collapsibleTabListId; } return ( <TabContext.Provider value={{ tabProps: {...props, orientation, density}, tabState: {tabListState, setTabListState, selectedTab, collapse}, refs: {tablistRef, wrapperRef}, tabPanelProps }}> <div {...filterDOMProps(otherProps)} {...styleProps} ref={domRef} className={classNames( styles, 'spectrum-TabsPanel', `spectrum-TabsPanel--${orientation}`, styleProps.className )}> {props.children} </div> </TabContext.Provider> ); } interface TabProps<T> extends DOMProps { item: Node<T>, state: SingleSelectListState<T>, isDisabled?: boolean, orientation?: Orientation } // @private function Tab<T>(props: TabProps<T>) { let {item, state, isDisabled: propsDisabled} = props; let {key, rendered} = item; let isDisabled = propsDisabled || state.disabledKeys.has(key); let ref = useRef<HTMLDivElement>(); let {tabProps} = useTab({key, isDisabled}, state, ref); let {hoverProps, isHovered} = useHover({ ...props }); let isSelected = state.selectedKey === key; let domProps = filterDOMProps(item.props); delete domProps.id; return ( <FocusRing focusRingClass={classNames(styles, 'focus-ring')}> <div {...mergeProps(tabProps, hoverProps, domProps)} ref={ref} className={classNames( styles, 'spectrum-Tabs-item', { 'is-selected': isSelected, 'is-disabled': isDisabled, 'is-hovered': isHovered } )}> <SlotProvider slots={{ icon: { size: 'S', UNSAFE_className: classNames(styles, 'spectrum-Icon') }, text: { UNSAFE_className: classNames(styles, 'spectrum-Tabs-itemLabel') } }}> {typeof rendered === 'string' ? <Text>{rendered}</Text> : rendered} </SlotProvider> </div> </FocusRing> ); } interface TabLineProps { orientation?: Orientation, selectedTab?: HTMLElement, selectedKey?: Key } // @private function TabLine(props: TabLineProps) { let { orientation, // Is either the tab node (non-collapsed) or the picker node (collapsed) selectedTab, // selectedKey is provided so that the TabLine styles are updated when the TabPicker's width updates from a selection change selectedKey } = props; let {direction} = useLocale(); let {scale} = useProvider(); let [style, setStyle] = useState({ width: undefined, height: undefined }); useLayoutEffect(() => { if (selectedTab) { let styleObj = {transform: undefined, width: undefined, height: undefined}; // In RTL, calculate the transform from the right edge of the tablist so that resizing the window doesn't break the Tabline position due to offsetLeft changes let offset = direction === 'rtl' ? -1 * ((selectedTab.offsetParent as HTMLElement)?.offsetWidth - selectedTab.offsetWidth - selectedTab.offsetLeft) : selectedTab.offsetLeft; styleObj.transform = orientation === 'vertical' ? `translateY(${selectedTab.offsetTop}px)` : `translateX(${offset}px)`; if (orientation === 'horizontal') { styleObj.width = `${selectedTab.offsetWidth}px`; } else { styleObj.height = `${selectedTab.offsetHeight}px`; } setStyle(styleObj); } }, [direction, setStyle, selectedTab, orientation, scale, selectedKey]); return <div className={classNames(styles, 'spectrum-Tabs-selectionIndicator')} role="presentation" style={style} />; } /** * A TabList is used within Tabs to group tabs that a user can switch between. * The keys of the items within the <TabList> must match up with a corresponding item inside the <TabPanels>. */ export function TabList<T>(props: SpectrumTabListProps<T>) { const tabContext = useContext(TabContext); const {refs, tabState, tabProps, tabPanelProps} = tabContext; const {isQuiet, density, isDisabled, orientation} = tabProps; const {selectedTab, collapse, setTabListState} = tabState; const {tablistRef, wrapperRef} = refs; // Pass original Tab props but override children to create the collection. const state = useTabListState({...tabProps, children: props.children}); let {styleProps} = useStyleProps(props); const {tabListProps} = useTabList({...tabProps, ...props}, state, tablistRef); useEffect(() => { // Passing back to root as useTabPanel needs the TabListState setTabListState(state); // eslint-disable-next-line react-hooks/exhaustive-deps }, [state.disabledKeys, state.selectedItem, state.selectedKey, props.children]); let stylePropsForVertical = orientation === 'vertical' ? styleProps : {}; let tabListclassName = classNames(styles, 'spectrum-TabsPanel-tabs'); const tabContent = ( <div {...stylePropsForVertical} {...tabListProps} ref={tablistRef} className={classNames( styles, 'spectrum-Tabs', `spectrum-Tabs--${orientation}`, tabListclassName, { 'spectrum-Tabs--quiet': isQuiet, ['spectrum-Tabs--compact']: density === 'compact' }, orientation === 'vertical' && styleProps.className ) }> {[...state.collection].map((item) => ( <Tab key={item.key} item={item} state={state} isDisabled={isDisabled} orientation={orientation} /> ))} <TabLine orientation={orientation} selectedTab={selectedTab} /> </div> ); if (orientation === 'vertical') { return tabContent; } else { return ( <div {...styleProps} ref={wrapperRef} className={classNames( styles, 'spectrum-TabsPanel-collapseWrapper', styleProps.className )}> {collapse ? <TabPicker {...props} {...tabProps} id={tabPanelProps['aria-labelledby']} state={state} className={tabListclassName} /> : tabContent} </div> ); } } /** * TabPanels is used within Tabs as a container for the content of each tab. * The keys of the items within the <TabPanels> must match up with a corresponding item inside the <TabList>. */ export function TabPanels<T>(props: SpectrumTabPanelsProps<T>) { const {tabState, tabProps} = useContext(TabContext); const {tabListState} = tabState; const factory = nodes => new ListCollection(nodes); const collection = useCollection({items: tabProps.items, ...props}, factory, {suppressTextValueWarning: true}); const selectedItem = tabListState ? collection.getItem(tabListState.selectedKey) : null; return ( <TabPanel {...props} key={tabListState?.selectedKey}> {selectedItem && selectedItem.props.children} </TabPanel> ); } // @private function TabPanel<T>(props: SpectrumTabPanelsProps<T>) { const {tabState, tabPanelProps: ctxTabPanelProps} = useContext(TabContext); const {tabListState} = tabState; let ref = useRef(); const {tabPanelProps} = useTabPanel(props, tabListState, ref); let {styleProps} = useStyleProps(props); if (ctxTabPanelProps['aria-labelledby']) { tabPanelProps['aria-labelledby'] = ctxTabPanelProps['aria-labelledby']; } return ( <FocusRing focusRingClass={classNames(styles, 'focus-ring')}> <div {...styleProps} {...tabPanelProps} ref={ref} className={classNames(styles, 'spectrum-TabsPanel-tabpanel', styleProps.className)}> {props.children} </div> </FocusRing> ); } interface TabPickerProps<T> extends Omit<SpectrumPickerProps<T>, 'children'> { density?: 'compact' | 'regular', state: SingleSelectListState<T>, className?: string } function TabPicker<T>(props: TabPickerProps<T>) { let { isDisabled, isQuiet, state, 'aria-labelledby': ariaLabeledBy, 'aria-label': ariaLabel, density, className, id } = props; let ref = useRef(); let [pickerNode, setPickerNode] = useState(null); useEffect(() => { let node = unwrapDOMRef(ref); setPickerNode(node.current); }, [ref]); let items = [...state.collection].map((item) => ({ rendered: item.rendered, textValue: item.textValue, id: item.key })); let pickerProps = { 'aria-labelledby': ariaLabeledBy, 'aria-label': ariaLabel }; // TODO: Figure out if tabListProps should go onto the div here, v2 doesn't do it return ( <div className={classNames( styles, 'spectrum-Tabs', 'spectrum-Tabs--horizontal', 'spectrum-Tabs--isCollapsed', { 'spectrum-Tabs--quiet': isQuiet, ['spectrum-Tabs--compact']: density === 'compact' }, className )}> <SlotProvider slots={{ icon: { size: 'S', UNSAFE_className: classNames(styles, 'spectrum-Icon') }, button: { focusRingClass: classNames(styles, 'focus-ring') } }}> <Picker {...pickerProps} id={id} items={items} ref={ref} isQuiet isDisabled={isDisabled} selectedKey={state.selectedKey} disabledKeys={state.disabledKeys} onSelectionChange={state.setSelectedKey}> {item => <Item textValue={item.textValue}>{item.rendered}</Item>} </Picker> {pickerNode && <TabLine orientation="horizontal" selectedTab={pickerNode} selectedKey={state.selectedKey} />} </SlotProvider> </div> ); } /** * Tabs organize content into multiple sections and allow users to navigate between them. The content under the set of tabs should be related and form a coherent unit. */ // forwardRef doesn't support generic parameters, so cast the result to the correct type // https://stackoverflow.com/questions/58469229/react-with-typescript-generics-while-using-react-forwardref const _Tabs = React.forwardRef(Tabs) as <T>(props: SpectrumTabsProps<T> & {ref?: DOMRef<HTMLDivElement>}) => ReactElement; export {_Tabs as Tabs};
the_stack
module VORLON { export class UWPClient extends ClientPlugin { monitorInterval: any; constructor() { super("sample"); // Name this.monitorInterval = null; this._ready = true; // No need to wait //this.debug = true; } //Return unique id for your plugin public getID(): string { return "UWP"; } public refresh(): void { //override this method with cleanup work that needs to happen //as the user switches between clients on the dashboard //we don't really need to do anything in this sample } // This code will run on the client ////////////////////// // Start the clientside code public startClientSide(): void { //don't actually need to do anything at startup } // Handle messages from the dashboard, on the client public onRealtimeMessageReceivedFromDashboardSide(receivedObject: any): void { } public checkMetadata() { var res = <IUWPMetadata>{ metadataDate: new Date(), winRTAvailable: false, isRunning: this.monitorInterval != null }; var global = <any>window; if (global.Windows) { res.winRTAvailable = true; var context = new global.Windows.ApplicationModel.Resources.Core.ResourceContext(); res.language = window.navigator.language; res.region = context.qualifierValues.homeRegion; res.deviceType = context.qualifierValues.deviceFamily; res.name = global.Windows.ApplicationModel.Package.current.displayName; res.appversion = global.Windows.ApplicationModel.Package.current.id.version; if (global.Windows.Security && global.Windows.Security.ExchangeActiveSyncProvisioning && global.Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation) { var deviceInfo = new global.Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation() res.systemManufacturer = deviceInfo.systemManufacturer; res.systemProductName = deviceInfo.systemProductName; } } this.sendCommandToDashboard('showMetadata', res); return res; } public checkStatus() { try { var res = <IUWPStatus>{ statusDate: new Date(), winRTAvailable: false, isRunning: this.monitorInterval != null }; var global = <any>window; if (global.Windows) { res.winRTAvailable = true; this.getWinRTStatus(res); if (global.Windows.Phone) { this.getPhoneStatus(res); } } this.sendCommandToDashboard('showStatus', res); return res; } catch (exception) { console.error(exception); } } public getPhoneStatus(status: IUWPStatus) { var global = <any>window; status.phone = { memory: { commitedBytes: global.Windows.Phone.System.Memory.MemoryManager.processCommittedBytes, commitedLimit: global.Windows.Phone.System.Memory.MemoryManager.processCommittedLimit, } } } public getWinRTStatus(status: IUWPStatus) { var global = <any>window; //see https://msdn.microsoft.com/fr-fr/library/windows/apps/windows.system.diagnostics.processdiagnosticinfo.aspx var winrtstatus = global.Windows.System.Diagnostics.ProcessDiagnosticInfo.getForCurrentProcess(); var memory = winrtstatus.memoryUsage.getReport(); if (memory) { status.memory = { nonPagedPool: memory.nonPagedPoolSizeInBytes, pagedPool: memory.pagedPoolSizeInBytes, pageFaultCount: memory.pageFaultCount, pageFile: memory.pageFileSizeInBytes, peakNonPagedPool: memory.peakNonPagedPoolSizeInBytes, peakPagedPool: memory.peakPagedPoolSizeInBytes, peakPageFile: memory.peakPageFileSizeInBytes, peakVirtualMemory: memory.peakVirtualMemorySizeInBytes, peakWorkingSet: memory.peakWorkingSetSizeInBytes, privatePageCount: memory.privatePageCount, virtualMemory: memory.virtualMemorySizeInBytes, workingSet: memory.workingSetSizeInBytes, }; } var cpu = winrtstatus.cpuUsage.getReport(); if (cpu) { status.cpu = { user: cpu.userTime, kernel: cpu.kernelTime }; } var disk = winrtstatus.diskUsage.getReport(); if (disk) { status.disk = { bytesRead: disk.bytesReadCount, bytesWritten: disk.bytesWrittenCount, otherBytes: disk.otherBytesCount, otherCount: disk.otherOperationCount, readCount: disk.readOperationCount, writeCount: disk.writeOperationCount, }; } if (global.Windows.System.Power) { var powerManager = global.Windows.System.Power.PowerManager; if (powerManager) { status.power = { batteryStatus: powerManager.batteryStatus, energySaverStatus: powerManager.energySaverStatus, powerSupplyStatus: powerManager.powerSupplyStatus, remainingChargePercent: powerManager.remainingChargePercent, remainingDischargeTime: powerManager.remainingDischargeTime } } var foregroundEnergyManager = global.Windows.System.Power.ForegroundEnergyManager; if (foregroundEnergyManager) { status.energy = status.energy || {}; status.energy.foregroundEnergy = { excessiveUsageLevel: foregroundEnergyManager.excessiveUsageLevel, lowUsageLevel: foregroundEnergyManager.lowUsageLevel, maxAcceptableUsageLevel: foregroundEnergyManager.maxAcceptableUsageLevel, nearMaxAcceptableUsageLevel: foregroundEnergyManager.nearMaxAcceptableUsageLevel, recentEnergyUsage: foregroundEnergyManager.recentEnergyUsage, recentEnergyUsageLevel: foregroundEnergyManager.recentEnergyUsageLevel }; } var backgroundEnergyManager = global.Windows.System.Power.BackgroundEnergyManager; if (backgroundEnergyManager) { status.energy = status.energy || {}; status.energy.backgroundEnergy = { excessiveUsageLevel: backgroundEnergyManager.excessiveUsageLevel, lowUsageLevel: backgroundEnergyManager.lowUsageLevel, maxAcceptableUsageLevel: backgroundEnergyManager.maxAcceptableUsageLevel, nearMaxAcceptableUsageLevel: backgroundEnergyManager.nearMaxAcceptableUsageLevel, nearTerminationUsageLevel: backgroundEnergyManager.nearTerminationUsageLevel, recentEnergyUsage: backgroundEnergyManager.recentEnergyUsage, recentEnergyUsageLevel: backgroundEnergyManager.recentEnergyUsageLevel, terminationUsageLevel: backgroundEnergyManager.terminationUsageLevel }; } } if (global.Windows.Networking && global.Windows.Networking.Connectivity && global.Windows.Networking.Connectivity.NetworkInformation) { //TODO improvements using https://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectionprofile.aspx var connectionProfile = global.Windows.Networking.Connectivity.NetworkInformation.getInternetConnectionProfile(); var na = connectionProfile.networkAdapter; status.network = { ianaInterfaceType: connectionProfile.networkAdapter.ianaInterfaceType.toString(), signal: connectionProfile.getSignalBars(), } } } public startMonitor(data: IUWPMonitorOptions) { if (this.monitorInterval) { clearInterval(this.monitorInterval); } this.monitorInterval = setInterval(() => { this.checkStatus(); }, data.interval); this.checkStatus(); } public stopMonitor() { if (this.monitorInterval) { clearInterval(this.monitorInterval); this.monitorInterval = null; } this.checkMetadata(); } } UWPClient.prototype.ClientCommands = { startMonitor: function(data: IUWPMonitorOptions) { var plugin = <UWPClient>this; plugin.startMonitor(data); }, stopMonitor: function() { var plugin = <UWPClient>this; plugin.stopMonitor(); }, getStatus: function() { var plugin = <UWPClient>this; plugin.checkStatus(); }, getMetadata: function() { var plugin = <UWPClient>this; plugin.checkMetadata(); } } //Register the plugin with vorlon core Core.RegisterClientPlugin(new UWPClient()); }
the_stack
import * as i18n from "i18next"; import * as moment from "moment"; import "pubsub-js"; import { Logger, LogLevel, Site, storage, Util } from "sp-pnp-js"; import ITaxonomyNavigationNode from "../../models/ITaxonomyNavigationNode"; import TaxonomyModule from "../../modules/TaxonomyModule"; import UtilityModule from "../../modules/UtilityModule"; import NavigationViewModel from "../NavigationViewModel"; class TopNavViewModel extends NavigationViewModel { public taxonomyModule: TaxonomyModule; public utilityModule: UtilityModule; public errorMessage: KnockoutObservable<string>; public utilityNavigationLabel: KnockoutObservable<string>; public localStorageKey: string; public wait: KnockoutObservable<boolean>; public mainMenuCollapseElementId: KnockoutObservable<string>; public mainMenuCollapseElementIdSelector: KnockoutComputed<string>; public utilityMenuCollapseElementId: KnockoutObservable<string>; public utilityMenuCollapseElementIdSelector: KnockoutComputed<string>; constructor() { super(); this.taxonomyModule = new TaxonomyModule(); this.utilityModule = new UtilityModule(); this.errorMessage = ko.observable(""); this.utilityNavigationLabel = ko.observable(i18n.t("utilityNavigation")); this.wait = ko.observable(true); // Because we could use the top nav component twice in the DOM (in the welcome overlay control), the Bootstrap collapse id's can't be the same. // That's why we use a dynamic id to avoid conflicts this.mainMenuCollapseElementId = ko.observable("navbar-collapse-" + this.utilityModule.getNewGuid()); this.mainMenuCollapseElementIdSelector = ko.computed(() => { return ("#" + this.mainMenuCollapseElementId()); }); this.utilityMenuCollapseElementId = ko.observable("utility-collapse-" + this.utilityModule.getNewGuid()); this.utilityMenuCollapseElementIdSelector = ko.computed(() => { return ("#" + this.utilityMenuCollapseElementId()); }); // We set the current site collection URL as unique identifier prefix for local storage key // By this way, we are able to browse multiple versions of the PnP Starter Intranet solution within the same browser and without navigation conficts. this.localStorageKey = String.format("{0}_{1}", _spPageContextInfo.siteServerRelativeUrl, i18n.t("siteMapLocalStorageKey")); // The current language is determined at the entry point of the application // Instead of making a second call to get the current langauge, we get the corresponding resource value according to the current context (like we already do for LCID) const currentLanguage = i18n.t("languageLabel"); // Yamm3! MegaMenu $(document).on("click", ".yamm .dropdown-menu", (e) => { e.stopPropagation(); }); $(document).ready(() => { $(this.mainMenuCollapseElementIdSelector()).on("collapse", () => { const elt = $("button.navbar-toggle i"); if (elt.hasClass("fa-times")) { elt.removeClass("fa-times"); elt.addClass("fa-bars"); } else { if (elt.hasClass("fa-bars")) { elt.removeClass("fa-bars"); elt.addClass("fa-times"); } } }); // Ovveride the collapse default behavior to get a slide transition (R to L) $('[data-target="' + this.mainMenuCollapseElementIdSelector() + '"]').on("click", (elt) => { const navMenuCont = $($(elt.currentTarget).data("target")); navMenuCont.animate( { width: "toggle", }, { complete: () => { navMenuCont.trigger("collapse"); }, duration: 200, specialEasing: { height: "easeOutBounce", width: "linear", }, }); }); }); // jQuery event for the collapsible menu in the mobile view for header links and language switcher $("#navigation-panel").on("hide.bs.collapse", () => { $("#utility-collapse i").removeClass("fa-angle-up"); $("#utility-collapse i").addClass("fa-angle-down"); }); $("#navigation-panel").on("show.bs.collapse", () => { $("#utility-collapse i").removeClass("fa-angle-down"); $("#utility-collapse i").addClass("fa-angle-up"); }); // Read the configuration value from the configuration list and for the current language. // We use a list item instead of a term set property to improve performances (SOD loading is slow compared to a simple REST call). // We also use caching to improve performances this.utilityModule.getConfigurationListValuesForLanguage(currentLanguage).then((item) => { if (item) { // Get the boolean value const noCache: boolean = item.ForceCacheRefresh; // Get the term set id const termSetId = item.SiteMapTermSetId; const navigationTree = this.utilityModule.isCacheValueValid(this.localStorageKey); // Check if the local storage value is still valid (i.e not null) if (navigationTree) { // We first initialize with the value from cache to avoid the waiting time. // Reason: In some cases, the waiting time was too long for the user to get the new nodes. // We do prefer display the menu first from cache and then make updates behind the scenes. // It is less frustrating and nearly seamless for users especially if your intranet links change often (i.e in the early stages of deployment). this.initialize(navigationTree); this.wait(false); // Publish the data to all subscribers (contextual menu and breadcrumb) PubSub.publish("navigationNodes", { nodes: navigationTree }); if (noCache) { // Get the new navigation nodes this.getNavigationNodes(termSetId); } } else { this.getNavigationNodes(termSetId); } } }).catch((errorMesssage) => { this.errorMessage(errorMesssage); this.wait(false); Logger.write("[TopNav.readConfigItem]: " + errorMesssage, LogLevel.Error); }); } public selectNode = (data, event) => { const nodes = this.nodes().map((node) => { if (node.id === data.id) { // Select current node node.isSelected(!node.isSelected()); return node; } else { // Unselect all other nodes node.isSelected(false); return node; } }); this.nodes(nodes); } public unselectNode = (elt) => { if ($(elt).parent("li").hasClass("open")) { const nodes = this.nodes().map((node) => { // Unselect all other nodes node.isSelected(false); return node; }); this.nodes(nodes); } } private getNavigationNodes(termSetId: string): void { if (!termSetId) { const errorMesssage = "The term set id for the site map is null. Please specify a valid term set id in the configuration list"; Logger.write("[TopNav.getNavigationNodes]: " + errorMesssage, LogLevel.Error); this.errorMessage(errorMesssage); this.wait(false); } else { // Ensure all SP dependencies are loaded before retrieving navigation nodes this.taxonomyModule.init().then(() => { // Initialize the main menu with taxonomy terms this.taxonomyModule.getNavigationTaxonomyNodes(new SP.Guid(termSetId)).then((navigationTree: ITaxonomyNavigationNode[]) => { // Initialize the mainMenu view model this.initialize(navigationTree); this.wait(false); // Publish the data to all subscribers (contextual menu and breadcrumb) PubSub.publish("navigationNodes", { nodes: navigationTree }); const now: Date = new Date(); // Clear the local storage value storage.local.delete(this.localStorageKey); // Set the navigation tree in the local storage of the browser storage.local.put(this.localStorageKey, this.utilityModule.stringifyTreeObject(navigationTree), new Date(now.setDate(now.getDate() + 7))); }).catch((errorMesssage) => { this.errorMessage(errorMesssage + ". Empty the localStorage values in the browser for the configuration list and try again."); // Clear the local storage value storage.local.delete(this.localStorageKey); this.wait(false); this.initialize([]); Logger.write("[TopNav.getNavigationNodes]: " + errorMesssage, LogLevel.Error); }); }).catch((errorMesssage) => { this.errorMessage(errorMesssage + ". Empty the localStorage values in the browser for the configuration list and try again."); // Clear the local storage value storage.local.delete(this.localStorageKey); this.wait(false); this.initialize([]); Logger.write("[TopNav.getNavigationNodes]: " + errorMesssage, LogLevel.Error); }); } } } export default TopNavViewModel;
the_stack
import assert from 'assert'; import * as events from 'events'; import * as child_process from 'child_process'; import * as Tp from 'thingpedia'; import JsonDatagramSocket from '../utils/json_datagram_socket'; const DEFAULT_QUESTION = 'translate from english to thingtalk'; export interface RawPredictionCandidate { answer : string; score : Record<string, number>; } interface Request { resolve(data : RawPredictionCandidate[][]) : void; reject(err : Error) : void; } const DEFAULT_MINIBATCH_SIZE = 30; const DEFAULT_MAX_LATENCY = 50; // milliseconds interface Example { context : string; question : string; answer ?: string; example_id ?: string; resolve(data : RawPredictionCandidate[]) : void; reject(err : Error) : void; } class LocalWorker extends events.EventEmitter { private _child : child_process.ChildProcess|null; private _stream : JsonDatagramSocket|null; private _nextId : 0; private _requests : Map<number, Request>; private _modeldir : string; constructor(modeldir : string) { super(); this._child = null; this._stream = null; this._nextId = 0; this._requests = new Map; this._modeldir = modeldir; } stop() { if (this._child) this._child.kill(); this._child = null; } start() { const args = [ 'server', '--stdin', '--path', this._modeldir, ]; if (process.env.GENIENLP_EMBEDDINGS) args.push('--embeddings', process.env.GENIENLP_EMBEDDINGS); if (process.env.GENIENLP_DATABASE_DIR) args.push('--database_dir', process.env.GENIENLP_DATABASE_DIR); if (process.env.GENIENLP_NUM_BEAMS) { const numBeams = parseInt(process.env.GENIENLP_NUM_BEAMS); // Count the greedy output as one of the results if (numBeams > 1) args.push('--num_beams', '1', (numBeams-1).toString(), '--num_outputs', '1', (numBeams-1).toString()); else args.push('--num_beams', '1', '--num_outputs', '1'); } this._child = child_process.spawn('genienlp', args, { stdio: ['pipe', 'pipe', 'inherit'] }); this._child.on('error', (e) => { this._failAll(e); this.emit('error', e); }); this._child.on('exit', (code, signal) => { //console.error(`Child exited with code ${code}, signal ${signal}`); const err = new Error(`Worker died`); this._failAll(err); this.emit('error', err); this._child = null; this.emit('exit'); }); this._stream = new JsonDatagramSocket(this._child.stdout!, this._child.stdin!, 'utf8'); this._stream.on('error', (e) => { this._failAll(e); this.emit('error', e); }); this._stream.on('data', (msg) => { const req = this._requests.get(msg.id); if (!req) // ignore bogus request return; if (msg.error) { req.reject(new Error(msg.error)); } else { req.resolve(msg.instances.map((instance : any) : RawPredictionCandidate[] => { if (instance.candidates) { return instance.candidates.map((c : any) => { return { answer: c.answer, score: c.score || {} }; }); } else { // no beam search, hence only one candidate // the score might present or not, depending on whether // we calibrate or not return [{ answer: instance.answer, score: instance.score || {} }]; } })); } this._requests.delete(msg.id); }); } private _failAll(error : Error) { for (const { reject } of this._requests.values()) reject(error); this._requests.clear(); } request(task : string, minibatch : Example[]) : Promise<RawPredictionCandidate[][]> { const id = this._nextId ++; return new Promise((resolve, reject) => { this._requests.set(id, { resolve, reject }); //console.error(`${this._requests.size} pending requests`); this._stream!.write({ id, task, instances: minibatch }, (err : Error | undefined | null) => { if (err) { console.error(err); reject(err); } }); }); } } class RemoteWorker extends events.EventEmitter { private _url : string; constructor(url : string) { super(); this._url = url; } start() {} stop() {} async request(task : string, minibatch : Example[]) : Promise<RawPredictionCandidate[][]> { const response = await Tp.Helpers.Http.post(this._url, JSON.stringify({ task, instances: minibatch }), { dataContentType: 'application/json', accept: 'application/json' }); return JSON.parse(response).predictions.map((instance : any) : RawPredictionCandidate[] => { if (instance.candidates) { return instance.candidates; } else { // no beam search, hence only one candidate // the score might present or not, depending on whether // we calibrate or not return [{ answer: instance.answer, score: instance.score || {} }]; } }); } } export default class Predictor { private _modelurl : string; private _worker : LocalWorker|RemoteWorker|null; private _stopped : boolean; private _minibatchSize : number; private _maxLatency : number; private _minibatchTask = ''; private _minibatch : Example[] = []; private _minibatchStartTime = 0; constructor(modelurl : string, { minibatchSize = DEFAULT_MINIBATCH_SIZE, maxLatency = DEFAULT_MAX_LATENCY }) { this._modelurl = modelurl; this._worker = null; this._minibatchSize = minibatchSize; this._maxLatency = maxLatency; this._stopped = false; } private _flushRequest() { const minibatch = this._minibatch; const task = this._minibatchTask; this._minibatch = []; this._minibatchTask = ''; this._minibatchStartTime = 0; //console.error(`minibatch: ${minibatch.length} instances`); this._worker!.request(task, minibatch).then((candidates) => { assert(candidates.length === minibatch.length); for (let i = 0; i < minibatch.length; i++) minibatch[i].resolve(candidates[i]); }, (err : Error) => { for (let i = 0; i < minibatch.length; i++) minibatch[i].reject(err); }); } private _startRequest(ex : Example, task : string, now : number) { assert(this._minibatch.length === 0); this._minibatch.push(ex); this._minibatchTask = task; this._minibatchStartTime = now; setTimeout(() => { if (this._minibatch.length > 0) this._flushRequest(); }, this._maxLatency); } private _addRequest(ex : Example, task : string) { const now = Date.now(); if (this._minibatch.length === 0) { this._startRequest(ex, task, now); } else if (this._minibatchTask === task && (now - this._minibatchStartTime < this._maxLatency) && this._minibatch.length < this._minibatchSize) { this._minibatch.push(ex); } else { this._flushRequest(); this._startRequest(ex, task, now); } } predict(context : string, question = DEFAULT_QUESTION, answer ?: string, task = 'almond', example_id ?: string) : Promise<RawPredictionCandidate[]> { assert(typeof context === 'string'); assert(typeof question === 'string'); // ensure we have a worker, in case it recently died if (!this._worker) this.start(); let resolve ! : (data : RawPredictionCandidate[]) => void, reject ! : (err : Error) => void; const promise = new Promise<RawPredictionCandidate[]>((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); this._addRequest({ context, question, answer, resolve, reject }, task); return promise; } start() { let worker : RemoteWorker|LocalWorker; if (/^kf\+https?:/.test(this._modelurl)) { worker = new RemoteWorker(this._modelurl.substring('kf+'.length)); } else { assert(this._modelurl.startsWith('file://')); worker = new LocalWorker(this._modelurl.substring('file://'.length)); } worker.on('error', (error : Error) => { if (!this._stopped) console.error(`Prediction worker had an error: ${error.message}`); this._worker = null; // fail all the requests in the minibatch if the worker is hosed for (const ex of this._minibatch) ex.reject(error); this._minibatch = []; this._minibatchStartTime = 0; this._minibatchTask = ''; worker.stop(); }); worker.start(); this._worker = worker; } stop() { this._stopped = true; if (this._worker) this._worker.stop(); } reload() { // stop the worker, if any if (this._worker) this._worker.stop(); // start again this.start(); } }
the_stack
import { DeepPartial, Omit } from 'utility-types' import { Size, KeyValue } from '../types' import { Registry } from '../registry' import { Point, Rectangle, Angle } from '../geometry' import { StringExt, ObjectExt, NumberExt } from '../util' import { Markup } from '../view/markup' import { Cell } from './cell' import { Edge } from './edge' import { Store } from './store' import { ShareRegistry } from './registry' import { PortManager } from './port' import { Animation } from './animation' import { Interp } from '../common' export class Node< Properties extends Node.Properties = Node.Properties, > extends Cell<Properties> { protected static defaults: Node.Defaults = { angle: 0, position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, } protected readonly store: Store<Node.Properties> protected port: PortManager protected get [Symbol.toStringTag]() { return Node.toStringTag } constructor(metadata: Node.Metadata = {}) { super(metadata) this.initPorts() } protected preprocess( metadata: Node.Metadata, ignoreIdCheck?: boolean, ): Properties { const { x, y, width, height, ...others } = metadata if (x != null || y != null) { const position = others.position others.position = { ...position, x: x != null ? x : position ? position.x : 0, y: y != null ? y : position ? position.y : 0, } } if (width != null || height != null) { const size = others.size others.size = { ...size, width: width != null ? width : size ? size.width : 0, height: height != null ? height : size ? size.height : 0, } } return super.preprocess(others, ignoreIdCheck) } isNode(): this is Node { return true } // #region size size(): Size size(size: Size, options?: Node.ResizeOptions): this size(width: number, height: number, options?: Node.ResizeOptions): this size( width?: number | Size, height?: number | Node.ResizeOptions, options?: Node.ResizeOptions, ) { if (width === undefined) { return this.getSize() } if (typeof width === 'number') { return this.setSize(width, height as number, options) } return this.setSize(width, height as Node.ResizeOptions) } getSize() { const size = this.store.get('size') return size ? { ...size } : { width: 1, height: 1 } } setSize(size: Size, options?: Node.ResizeOptions): this setSize(width: number, height: number, options?: Node.ResizeOptions): this setSize( width: number | Size, height?: number | Node.ResizeOptions, options?: Node.ResizeOptions, ) { if (typeof width === 'object') { this.resize(width.width, width.height, height as Node.ResizeOptions) } else { this.resize(width, height as number, options) } return this } resize(width: number, height: number, options: Node.ResizeOptions = {}) { this.startBatch('resize', options) const direction = options.direction if (direction) { const currentSize = this.getSize() switch (direction) { case 'left': case 'right': // Don't change height when resizing horizontally. height = currentSize.height // eslint-disable-line break case 'top': case 'bottom': // Don't change width when resizing vertically. width = currentSize.width // eslint-disable-line break default: break } const map: { [direction: string]: number } = { right: 0, 'top-right': 0, top: 1, 'top-left': 1, left: 2, 'bottom-left': 2, bottom: 3, 'bottom-right': 3, } let quadrant = map[direction] const angle = Angle.normalize(this.getAngle() || 0) if (options.absolute) { // We are taking the node's rotation into account quadrant += Math.floor((angle + 45) / 90) quadrant %= 4 } // This is a rectangle in size of the un-rotated node. const bbox = this.getBBox() // Pick the corner point on the node, which meant to stay on its // place before and after the rotation. let fixedPoint: Point if (quadrant === 0) { fixedPoint = bbox.getBottomLeft() } else if (quadrant === 1) { fixedPoint = bbox.getCorner() } else if (quadrant === 2) { fixedPoint = bbox.getTopRight() } else { fixedPoint = bbox.getOrigin() } // Find an image of the previous indent point. This is the position, // where is the point actually located on the screen. const imageFixedPoint = fixedPoint .clone() .rotate(-angle, bbox.getCenter()) // Every point on the element rotates around a circle with the centre of // rotation in the middle of the element while the whole element is being // rotated. That means that the distance from a point in the corner of // the element (supposed its always rect) to the center of the element // doesn't change during the rotation and therefore it equals to a // distance on un-rotated element. // We can find the distance as DISTANCE = (ELEMENTWIDTH/2)^2 + (ELEMENTHEIGHT/2)^2)^0.5. const radius = Math.sqrt(width * width + height * height) / 2 // Now we are looking for an angle between x-axis and the line starting // at image of fixed point and ending at the center of the element. // We call this angle `alpha`. // The image of a fixed point is located in n-th quadrant. For each // quadrant passed going anti-clockwise we have to add 90 degrees. // Note that the first quadrant has index 0. // // 3 | 2 // --c-- Quadrant positions around the element's center `c` // 0 | 1 // let alpha = (quadrant * Math.PI) / 2 // Add an angle between the beginning of the current quadrant (line // parallel with x-axis or y-axis going through the center of the // element) and line crossing the indent of the fixed point and the // center of the element. This is the angle we need but on the // un-rotated element. alpha += Math.atan(quadrant % 2 === 0 ? height / width : width / height) // Lastly we have to deduct the original angle the element was rotated // by and that's it. alpha -= Angle.toRad(angle) // With this angle and distance we can easily calculate the centre of // the un-rotated element. // Note that fromPolar constructor accepts an angle in radians. const center = Point.fromPolar(radius, alpha, imageFixedPoint) // The top left corner on the un-rotated element has to be half a width // on the left and half a height to the top from the center. This will // be the origin of rectangle we were looking for. const origin = center.clone().translate(width / -2, height / -2) this.store.set('size', { width, height }, options) this.setPosition(origin.x, origin.y, options) } else { this.store.set('size', { width, height }, options) } this.stopBatch('resize', options) return this } scale( sx: number, sy: number, origin?: Point.PointLike | null, options: Node.SetOptions = {}, ) { const scaledBBox = this.getBBox().scale( sx, sy, origin == null ? undefined : origin, ) this.startBatch('scale', options) this.setPosition(scaledBBox.x, scaledBBox.y, options) this.resize(scaledBBox.width, scaledBBox.height, options) this.stopBatch('scale') return this } // #endregion // #region position position(x: number, y: number, options?: Node.SetPositionOptions): this position(options?: Node.GetPositionOptions): Point.PointLike position( arg0?: number | Node.GetPositionOptions, arg1?: number, arg2?: Node.SetPositionOptions, ) { if (typeof arg0 === 'number') { return this.setPosition(arg0, arg1 as number, arg2) } return this.getPosition(arg0) } getPosition(options: Node.GetPositionOptions = {}): Point.PointLike { if (options.relative) { const parent = this.getParent() if (parent != null && parent.isNode()) { const currentPosition = this.getPosition() const parentPosition = parent.getPosition() return { x: currentPosition.x - parentPosition.x, y: currentPosition.y - parentPosition.y, } } } const pos = this.store.get('position') return pos ? { ...pos } : { x: 0, y: 0 } } setPosition( p: Point | Point.PointLike, options?: Node.SetPositionOptions, ): this setPosition(x: number, y: number, options?: Node.SetPositionOptions): this setPosition( arg0: number | Point | Point.PointLike, arg1?: number | Node.SetPositionOptions, arg2: Node.SetPositionOptions = {}, ) { let x: number let y: number let options: Node.SetPositionOptions if (typeof arg0 === 'object') { x = arg0.x y = arg0.y options = (arg1 as Node.SetPositionOptions) || {} } else { x = arg0 y = arg1 as number options = arg2 || {} } if (options.relative) { const parent = this.getParent() as Node if (parent != null && parent.isNode()) { const parentPosition = parent.getPosition() x += parentPosition.x y += parentPosition.y } } if (options.deep) { const currentPosition = this.getPosition() this.translate(x - currentPosition.x, y - currentPosition.y, options) } else { this.store.set('position', { x, y }, options) } return this } translate(tx = 0, ty = 0, options: Node.TranslateOptions = {}) { if (tx === 0 && ty === 0) { return this } // Pass the initiator of the translation. options.translateBy = options.translateBy || this.id const position = this.getPosition() if (options.restrict != null && options.translateBy === this.id) { // We are restricting the translation for the element itself only. We get // the bounding box of the element including all its embeds. // All embeds have to be translated the exact same way as the element. const bbox = this.getBBox({ deep: true }) const ra = options.restrict // - - - - - - - - - - - - -> ra.x + ra.width // - - - -> position.x | // -> bbox.x // ▓▓▓▓▓▓▓ | // ░░░░░░░▓▓▓▓▓▓▓ // ░░░░░░░░░ | // ▓▓▓▓▓▓▓▓░░░░░░░ // ▓▓▓▓▓▓▓▓ | // <-dx-> | restricted area right border // <-width-> | ░ translated element // <- - bbox.width - -> ▓ embedded element const dx = position.x - bbox.x const dy = position.y - bbox.y // Find the maximal/minimal coordinates that the element can be translated // while complies the restrictions. const x = Math.max( ra.x + dx, Math.min(ra.x + ra.width + dx - bbox.width, position.x + tx), ) const y = Math.max( ra.y + dy, Math.min(ra.y + ra.height + dy - bbox.height, position.y + ty), ) // recalculate the translation taking the restrictions into account. tx = x - position.x // eslint-disable-line ty = y - position.y // eslint-disable-line } const translatedPosition = { x: position.x + tx, y: position.y + ty, } // To find out by how much an element was translated in event // 'change:position' handlers. options.tx = tx options.ty = ty if (options.transition) { if (typeof options.transition !== 'object') { options.transition = {} } this.transition('position', translatedPosition, { ...options.transition, interp: Interp.object, }) this.eachChild((child) => { const excluded = options.exclude?.includes(child) if (!excluded) { child.translate(tx, ty, options) } }) } else { this.startBatch('translate', options) this.store.set('position', translatedPosition, options) this.eachChild((child) => { const excluded = options.exclude?.includes(child) if (!excluded) { child.translate(tx, ty, options) } }) this.stopBatch('translate', options) } return this } // #endregion // #region angle angle(): number angle(val: number, options?: Node.RotateOptions): this angle(val?: number, options?: Node.RotateOptions) { if (val == null) { return this.getAngle() } return this.rotate(val, options) } getAngle() { return this.store.get('angle', 0) } rotate(angle: number, options: Node.RotateOptions = {}) { const currentAngle = this.getAngle() if (options.center) { const size = this.getSize() const position = this.getPosition() const center = this.getBBox().getCenter() center.rotate(currentAngle - angle, options.center) const dx = center.x - size.width / 2 - position.x const dy = center.y - size.height / 2 - position.y this.startBatch('rotate', { angle, options }) this.setPosition(position.x + dx, position.y + dy, options) this.rotate(angle, { ...options, center: null }) this.stopBatch('rotate') } else { this.store.set( 'angle', options.absolute ? angle : (currentAngle + angle) % 360, options, ) } return this } // #endregion // #region common getBBox(options: { deep?: boolean } = {}) { if (options.deep) { const cells = this.getDescendants({ deep: true, breadthFirst: true }) cells.push(this) return Cell.getCellsBBox(cells)! } return Rectangle.fromPositionAndSize(this.getPosition(), this.getSize()) } getConnectionPoint(edge: Edge, type: Edge.TerminalType) { const bbox = this.getBBox() const center = bbox.getCenter() const terminal = edge.getTerminal(type) as Edge.TerminalCellData if (terminal == null) { return center } const portId = terminal.port if (!portId || !this.hasPort(portId)) { return center } const port = this.getPort(portId) if (!port || !port.group) { return center } const layouts = this.getPortsPosition(port.group) const position = layouts[portId].position const portCenter = Point.create(position).translate(bbox.getOrigin()) const angle = this.getAngle() if (angle) { portCenter.rotate(-angle, center) } return portCenter } /** * Sets cell's size and position based on the children bbox and given padding. */ fit(options: Node.FitEmbedsOptions = {}) { const children = this.getChildren() || [] const embeds = children.filter((cell) => cell.isNode()) as Node[] if (embeds.length === 0) { return this } this.startBatch('fit-embeds', options) if (options.deep) { embeds.forEach((cell) => cell.fit(options)) } let { x, y, width, height } = Cell.getCellsBBox(embeds)! const padding = NumberExt.normalizeSides(options.padding) x -= padding.left y -= padding.top width += padding.left + padding.right height += padding.bottom + padding.top this.store.set( { position: { x, y }, size: { width, height }, }, options, ) this.stopBatch('fit-embeds') return this } // #endregion // #region ports get portContainerMarkup() { return this.getPortContainerMarkup() } set portContainerMarkup(markup: Markup) { this.setPortContainerMarkup(markup) } getDefaultPortContainerMarkup() { return ( this.store.get('defaultPortContainerMarkup') || Markup.getPortContainerMarkup() ) } getPortContainerMarkup() { return ( this.store.get('portContainerMarkup') || this.getDefaultPortContainerMarkup() ) } setPortContainerMarkup(markup?: Markup, options: Node.SetOptions = {}) { this.store.set('portContainerMarkup', Markup.clone(markup), options) return this } get portMarkup() { return this.getPortMarkup() } set portMarkup(markup: Markup) { this.setPortMarkup(markup) } getDefaultPortMarkup() { return this.store.get('defaultPortMarkup') || Markup.getPortMarkup() } getPortMarkup() { return this.store.get('portMarkup') || this.getDefaultPortMarkup() } setPortMarkup(markup?: Markup, options: Node.SetOptions = {}) { this.store.set('portMarkup', Markup.clone(markup), options) return this } get portLabelMarkup() { return this.getPortLabelMarkup() } set portLabelMarkup(markup: Markup) { this.setPortLabelMarkup(markup) } getDefaultPortLabelMarkup() { return ( this.store.get('defaultPortLabelMarkup') || Markup.getPortLabelMarkup() ) } getPortLabelMarkup() { return this.store.get('portLabelMarkup') || this.getDefaultPortLabelMarkup() } setPortLabelMarkup(markup?: Markup, options: Node.SetOptions = {}) { this.store.set('portLabelMarkup', Markup.clone(markup), options) return this } get ports() { const res = this.store.get<PortManager.Metadata>('ports', { items: [] }) if (res.items == null) { res.items = [] } return res } getPorts() { return ObjectExt.cloneDeep(this.ports.items) } getPortsByGroup(groupName: string) { return this.getPorts().filter((port) => port.group === groupName) } getPort(portId: string) { return ObjectExt.cloneDeep( this.ports.items.find((port) => port.id && port.id === portId), ) } getPortAt(index: number) { return this.ports.items[index] || null } hasPorts() { return this.ports.items.length > 0 } hasPort(portId: string) { return this.getPortIndex(portId) !== -1 } getPortIndex(port: PortManager.PortMetadata | string) { const portId = typeof port === 'string' ? port : port.id return portId != null ? this.ports.items.findIndex((item) => item.id === portId) : -1 } getPortsPosition(groupName: string) { const size = this.getSize() const layouts = this.port.getPortsLayoutByGroup( groupName, new Rectangle(0, 0, size.width, size.height), ) return layouts.reduce< KeyValue<{ position: Point.PointLike angle: number }> >((memo, item) => { const layout = item.portLayout memo[item.portId] = { position: { ...layout.position }, angle: layout.angle || 0, } return memo }, {}) } getPortProp(portId: string): PortManager.PortMetadata getPortProp<T>(portId: string, path: string | string[]): T getPortProp(portId: string, path?: string | string[]) { return this.getPropByPath(this.prefixPortPath(portId, path)) } setPortProp( portId: string, path: string | string[], value: any, options?: Node.SetOptions, ): this setPortProp( portId: string, value: DeepPartial<PortManager.PortMetadata>, options?: Node.SetOptions, ): this setPortProp( portId: string, arg1: string | string[] | DeepPartial<PortManager.PortMetadata>, arg2: any | Node.SetOptions, arg3?: Node.SetOptions, ) { if (typeof arg1 === 'string' || Array.isArray(arg1)) { const path = this.prefixPortPath(portId, arg1) const value = arg2 return this.setPropByPath(path, value, arg3) } const path = this.prefixPortPath(portId) const value = arg1 as DeepPartial<PortManager.PortMetadata> return this.setPropByPath(path, value, arg2 as Node.SetOptions) } removePortProp(portId: string, options?: Node.SetOptions): this removePortProp( portId: string, path: string | string[], options?: Node.SetOptions, ): this removePortProp( portId: string, path?: string | string[] | Node.SetOptions, options?: Node.SetOptions, ) { if (typeof path === 'string' || Array.isArray(path)) { return this.removePropByPath(this.prefixPortPath(portId, path), options) } return this.removePropByPath(this.prefixPortPath(portId), path) } portProp(portId: string): PortManager.PortMetadata portProp<T>(portId: string, path: string | string[]): T portProp( portId: string, path: string | string[], value: any, options?: Node.SetOptions, ): this portProp( portId: string, value: DeepPartial<PortManager.PortMetadata>, options?: Node.SetOptions, ): this portProp( portId: string, path?: string | string[] | DeepPartial<PortManager.PortMetadata>, value?: any | Node.SetOptions, options?: Node.SetOptions, ) { if (path == null) { return this.getPortProp(portId) } if (typeof path === 'string' || Array.isArray(path)) { if (arguments.length === 2) { return this.getPortProp(portId, path) } if (value == null) { return this.removePortProp(portId, path, options) } return this.setPortProp( portId, path, value as DeepPartial<PortManager.PortMetadata>, options, ) } return this.setPortProp( portId, path as DeepPartial<PortManager.PortMetadata>, value as Node.SetOptions, ) } protected prefixPortPath(portId: string, path?: string | string[]) { const index = this.getPortIndex(portId) if (index === -1) { throw new Error(`Unable to find port with id: "${portId}"`) } if (path == null || path === '') { return ['ports', 'items', `${index}`] } if (Array.isArray(path)) { return ['ports', 'items', `${index}`, ...path] } return `ports/items/${index}/${path}` } addPort(port: PortManager.PortMetadata, options?: Node.SetOptions) { const ports = [...this.ports.items] ports.push(port) this.setPropByPath('ports/items', ports, options) return this } addPorts(ports: PortManager.PortMetadata[], options?: Node.SetOptions) { this.setPropByPath('ports/items', [...this.ports.items, ...ports], options) return this } insertPort( index: number, port: PortManager.PortMetadata, options?: Node.SetOptions, ) { const ports = [...this.ports.items] ports.splice(index, 0, port) this.setPropByPath('ports/items', ports, options) return this } removePort( port: PortManager.PortMetadata | string, options: Node.SetOptions = {}, ) { return this.removePortAt(this.getPortIndex(port), options) } removePortAt(index: number, options: Node.SetOptions = {}) { if (index >= 0) { const ports = [...this.ports.items] ports.splice(index, 1) options.rewrite = true this.setPropByPath('ports/items', ports, options) } return this } removePorts(options?: Node.SetOptions): this removePorts( portsForRemoval: (PortManager.PortMetadata | string)[], options?: Node.SetOptions, ): this removePorts( portsForRemoval?: (PortManager.PortMetadata | string)[] | Node.SetOptions, opt?: Node.SetOptions, ) { let options if (Array.isArray(portsForRemoval)) { options = opt || {} if (portsForRemoval.length) { options.rewrite = true const currentPorts = [...this.ports.items] const remainingPorts = currentPorts.filter( (cp) => !portsForRemoval.some((p) => { const id = typeof p === 'string' ? p : p.id return cp.id === id }), ) this.setPropByPath('ports/items', remainingPorts, options) } } else { options = portsForRemoval || {} options.rewrite = true this.setPropByPath('ports/items', [], options) } return this } getParsedPorts() { return this.port.getPorts() } getParsedGroups() { return this.port.groups } getPortsLayoutByGroup(groupName: string | undefined, bbox: Rectangle) { return this.port.getPortsLayoutByGroup(groupName, bbox) } protected initPorts() { this.updatePortData() this.on('change:ports', () => { this.processRemovedPort() this.updatePortData() }) } protected processRemovedPort() { const current = this.ports const currentItemsMap: { [id: string]: boolean } = {} current.items.forEach((item) => { if (item.id) { currentItemsMap[item.id] = true } }) const removed: { [id: string]: boolean } = {} const previous = this.store.getPrevious<PortManager.Metadata>('ports') || { items: [], } previous.items.forEach((item) => { if (item.id && !currentItemsMap[item.id]) { removed[item.id] = true } }) const model = this.model if (model && !ObjectExt.isEmpty(removed)) { const incomings = model.getConnectedEdges(this, { incoming: true }) incomings.forEach((edge) => { const portId = edge.getTargetPortId() if (portId && removed[portId]) { edge.remove() } }) const outgoings = model.getConnectedEdges(this, { outgoing: true }) outgoings.forEach((edge) => { const portId = edge.getSourcePortId() if (portId && removed[portId]) { edge.remove() } }) } } protected validatePorts() { const ids: { [id: string]: boolean } = {} const errors: string[] = [] this.ports.items.forEach((p) => { if (typeof p !== 'object') { errors.push(`Invalid port ${p}.`) } if (p.id == null) { p.id = this.generatePortId() } if (ids[p.id]) { errors.push('Duplicitied port id.') } ids[p.id] = true }) return errors } protected generatePortId() { return StringExt.uuid() } protected updatePortData() { const err = this.validatePorts() if (err.length > 0) { this.store.set( 'ports', this.store.getPrevious<PortManager.Metadata>('ports'), ) throw new Error(err.join(' ')) } const prev = this.port ? this.port.getPorts() : null this.port = new PortManager(this.ports) const curr = this.port.getPorts() const added = prev ? curr.filter((item) => { if (!prev.find((prevPort) => prevPort.id === item.id)) { return item } return null }) : [...curr] const removed = prev ? prev.filter((item) => { if (!curr.find((curPort) => curPort.id === item.id)) { return item } return null }) : [] if (added.length > 0) { this.notify('ports:added', { added, cell: this, node: this }) } if (removed.length > 0) { this.notify('ports:removed', { removed, cell: this, node: this }) } } // #endregion } export namespace Node { interface Common extends Cell.Common { size?: { width: number; height: number } position?: { x: number; y: number } angle?: number ports?: Partial<PortManager.Metadata> | PortManager.PortMetadata[] portContainerMarkup?: Markup portMarkup?: Markup portLabelMarkup?: Markup defaultPortMarkup?: Markup defaultPortLabelMarkup?: Markup defaultPortContainerMarkup?: Markup } interface Boundary { x?: number y?: number width?: number height?: number } export interface Defaults extends Common, Cell.Defaults {} export interface Metadata extends Common, Cell.Metadata, Boundary {} export interface Properties extends Common, Omit<Cell.Metadata, 'tools'>, Cell.Properties {} export interface Config extends Defaults, Boundary, Cell.Config<Metadata, Node> {} } export namespace Node { export interface SetOptions extends Cell.SetOptions {} export interface GetPositionOptions { relative?: boolean } export interface SetPositionOptions extends SetOptions { deep?: boolean relative?: boolean } export interface TranslateOptions extends Cell.TranslateOptions { transition?: boolean | Animation.StartOptions<Point.PointLike> restrict?: Rectangle.RectangleLike | null exclude?: Cell[] } export interface RotateOptions extends SetOptions { absolute?: boolean center?: Point.PointLike | null } export type ResizeDirection = | 'left' | 'top' | 'right' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' export interface ResizeOptions extends SetOptions { absolute?: boolean direction?: ResizeDirection } export interface FitEmbedsOptions extends SetOptions { deep?: boolean padding?: NumberExt.SideOptions } } export namespace Node { export const toStringTag = `X6.${Node.name}` export function isNode(instance: any): instance is Node { if (instance == null) { return false } if (instance instanceof Node) { return true } const tag = instance[Symbol.toStringTag] const node = instance as Node if ( (tag == null || tag === toStringTag) && typeof node.isNode === 'function' && typeof node.isEdge === 'function' && typeof node.prop === 'function' && typeof node.attr === 'function' && typeof node.size === 'function' && typeof node.position === 'function' ) { return true } return false } } export namespace Node { Node.config<Node.Config>({ propHooks({ ports, ...metadata }) { if (ports) { metadata.ports = Array.isArray(ports) ? { items: ports } : ports } return metadata }, }) } export namespace Node { export const registry = Registry.create< Definition, never, Config & { inherit?: string | Definition } >({ type: 'node', process(shape, options) { if (ShareRegistry.exist(shape, true)) { throw new Error( `Node with name '${shape}' was registered by anthor Edge`, ) } if (typeof options === 'function') { options.config({ shape }) return options } let parent = Node const { inherit, ...config } = options if (inherit) { if (typeof inherit === 'string') { const base = this.get(inherit) if (base == null) { this.onNotFound(inherit, 'inherited') } else { parent = base } } else { parent = inherit } } if (config.constructorName == null) { config.constructorName = shape } const ctor: Definition = parent.define.call(parent, config) ctor.config({ shape }) return ctor as any }, }) ShareRegistry.setNodeRegistry(registry) } export namespace Node { type NodeClass = typeof Node export interface Definition extends NodeClass { new <T extends Properties = Properties>(metadata: T): Node } let counter = 0 function getClassName(name?: string) { if (name) { return StringExt.pascalCase(name) } counter += 1 return `CustomNode${counter}` } export function define(config: Config) { const { constructorName, overwrite, ...others } = config const ctor = ObjectExt.createClass<NodeClass>( getClassName(constructorName || others.shape), this as NodeClass, ) ctor.config(others) if (others.shape) { registry.register(others.shape, ctor, overwrite) } return ctor } export function create(options: Metadata) { const shape = options.shape || 'rect' const Ctor = registry.get(shape) if (Ctor) { return new Ctor(options) } return registry.onNotFound(shape) } }
the_stack
namespace eui.sys { /** * @private */ export const enum RangeKeys{ maximum, maxChanged, minimum, minChanged, value, changedValue, valueChanged, snapInterval, snapIntervalChanged, explicitSnapInterval } } namespace eui { /** * The Range class holds a value and an allowed range for that * value, defined by <code>minimum</code> and <code>maximum</code> properties. * * The <code>value</code> property * is always constrained to be between the current <code>minimum</code> and * <code>maximum</code>, and the <code>minimum</code>, * and <code>maximum</code> are always constrained * to be in the proper numerical order, such that * <code>(minimum <= value <= maximum)</code> is <code>true</code>. * * If the value of the <code>snapInterval</code> property is not 0, * then the <code>value</code> property is also constrained to be a multiple of * <code>snapInterval</code>. * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @includeExample extension/eui/components/supportClasses/RangeExample.ts * @language en_US */ /** * 范围选取组件,该组件包含一个值和这个值所允许的最大最小约束范围。 * * <code>value</code>属性的值永远被限制于当前的<code>minimum</code>和 * <code>maximum</code>之间,并且<code>minimum</code>和 <code>maximum</code>永远按照固定的顺序排列, * 即<code>(minimum <= value <= maximum)</code> 为真。 * * 如果<code>snapInterval</code>属性的值不是0,那么<code>value</code>的值也会被<code>snapInterval</code>所约束。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @includeExample extension/eui/components/supportClasses/RangeExample.ts * @language zh_CN */ export class Range extends Component { /** * Constructor. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 创建一个 Range 实例。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public constructor() { super(); this.$Range = { 0: 100, //maximum 1: false, //maxChanged 2: 0, //minimum 3: false, //minChanged 4: 0, //value 5: 0, //changedValue 6: false, //valueChanged 7: 1, //snapInterval 8: false, //snapIntervalChanged 9: false, //explicitSnapInterval }; } /** * @private */ $Range:Object; /** * The maximum valid <code>value</code>.<p/> * * Changes to the value property are constrained * by <code>commitProperties()</code> to be less than or equal to * maximum with the <code>nearestValidValue()</code> method. * * @default 100 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 最大有效值。<p/> * * 规定<code>value</code>属性的值不能够超过的最大值。该修正过程 * 将在<code>nearestValidValue()</code>方法中进行。 * * @default 100 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get maximum():number { return this.$Range[sys.RangeKeys.maximum]; } public set maximum(value:number) { value = +value || 0; let values = this.$Range; if (value === values[sys.RangeKeys.maximum]) return; values[sys.RangeKeys.maximum] = value; values[sys.RangeKeys.maxChanged] = true; this.invalidateProperties(); this.invalidateDisplayList(); } /** * The minimum valid <code>value</code>.<p/> * * Changes to the value property are constrained * by <code>commitProperties()</code> to be greater than or equal to * minimum with the <code>nearestValidValue()</code> method. * * @default 0 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 最小有效值<p/> * * 规定<code>value</code>属性的值不能够低于的最小值。该修正过程 * 将在<code>nearestValidValue()</code>方法中进行。 * * @default 0 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get minimum():number { return this.$Range[sys.RangeKeys.minimum]; } public set minimum(value:number) { value = +value || 0; let values = this.$Range; if (value === values[sys.RangeKeys.minimum]) return; values[sys.RangeKeys.minimum] = value; values[sys.RangeKeys.minChanged] = true; this.invalidateProperties(); this.invalidateDisplayList(); } /** * The current value for this range.<p/> * * Changes to the value property are constrained * by <code>commitProperties()</code> to be greater than or equal to * the <code>minimum</code> property, less than or equal to the <code>maximum</code> property, and a * multiple of <code>snapInterval</code> with the <code>nearestValidValue()</code> * method. * * @default 0 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 此范围的当前值。<p/> * * 改变的<code>value</code>属性将在<code>commitProperties()</code>方法中被<code>minimum</code>属性 * 和<code>minimum</code>属性所限制。此修正过程将在<code>nearestValidValue()</code>方法中进行。 * * @default 0 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get value():number { let values = this.$Range; return values[sys.RangeKeys.valueChanged] ? values[sys.RangeKeys.changedValue] : values[sys.RangeKeys.value]; } public set value(newValue:number) { newValue = +newValue || 0; this.$setValue(newValue); } /** * @private * * @param newValue */ $setValue(newValue:number):boolean { if (newValue === this.value) return false; let values = this.$Range; values[sys.RangeKeys.changedValue] = newValue; values[sys.RangeKeys.valueChanged] = true; this.invalidateProperties(); return true; } /** * The snapInterval property controls the valid values of the <code>value</code> property. * * If nonzero, valid values are the sum of the <code>minimum</code> and integer multiples * of this property, for all sums that are less than or equal to the <code>maximum</code>.<p/> * * For example, if <code>minimum</code> is 10, <code>maximum</code> is 20, and this property is 3, then the * valid values of this Range are 10, 13, 16, 19, and 20.<p/> * * If the value of this property is zero, then valid values are only constrained * to be between minimum and maximum inclusive. * * @default 1 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * snapInterval 属性定义 value 属性的有效值。 * 如果为非零,则有效值为 minimum 与此属性的整数倍数之和,且小于或等于 maximum。</p> * * 例如,如果 minimum 为 10,maximum 为 20,而此属性为 3,则可能的有效值为 10、13、16、19 和 20.</p> * * 如果此属性的值为零,则仅会将有效值约束到介于 minimum 和 maximum 之间(包括两者)。 * * @default 1 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get snapInterval():number { return this.$Range[sys.RangeKeys.snapInterval]; } public set snapInterval(value:number) { let values = this.$Range; values[sys.RangeKeys.explicitSnapInterval] = true; value = +value || 0; if (value === values[sys.RangeKeys.snapInterval]) return; if (isNaN(value)) { values[sys.RangeKeys.snapInterval] = 1; values[sys.RangeKeys.explicitSnapInterval] = false; } else { values[sys.RangeKeys.snapInterval] = value; } values[sys.RangeKeys.snapIntervalChanged] = true; this.invalidateProperties(); } /** * Processes the properties set on the component. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 处理对组件设置的属性 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected commitProperties():void { super.commitProperties(); let values = this.$Range; if (values[sys.RangeKeys.minimum] > values[sys.RangeKeys.maximum]) { if (!values[sys.RangeKeys.maxChanged]) values[sys.RangeKeys.minimum] = values[sys.RangeKeys.maximum]; else values[sys.RangeKeys.maximum] = values[sys.RangeKeys.minimum]; } if (values[sys.RangeKeys.valueChanged] || values[sys.RangeKeys.maxChanged] || values[sys.RangeKeys.minChanged] || values[sys.RangeKeys.snapIntervalChanged]) { let currentValue = values[sys.RangeKeys.valueChanged] ? values[sys.RangeKeys.changedValue] : values[sys.RangeKeys.value]; values[sys.RangeKeys.valueChanged] = false; values[sys.RangeKeys.maxChanged] = false; values[sys.RangeKeys.minChanged] = false; values[sys.RangeKeys.snapIntervalChanged] = false; this.setValue(this.nearestValidValue(currentValue, values[sys.RangeKeys.snapInterval])); } } /** * @private * 修正size到最接近snapInterval的整数倍 */ private nearestValidSize(size:number):number { let interval:number = this.snapInterval; if (interval == 0) return size; let validSize:number = Math.round(size / interval) * interval; return (Math.abs(validSize) < interval) ? interval : validSize; } /** * Returns the sum of the minimum with an integer multiple of <code>interval</code> that's * closest to <code>value</code>, unless <code>value</code> is closer to the maximum limit, * in which case the maximum is returned.<p/> * * If <code>interval</code> is equal to 0, the value is clipped to the minimum and maximum * limits.<p/> * * The valid values for a range are defined by the sum of the <code>minimum</code> property * with multiples of the <code>interval</code> and also defined to be less than or equal to the * <code>maximum</code> property. * The maximum need not be a multiple of <code>snapInterval</code>.<p/> * * For example, if <code>minimum</code> is equal to 1, <code>maximum</code> is equal to 6, * and <code>snapInterval</code> is equal to 2, the valid * values for the Range are 1, 3, 5, 6. * * Similarly, if <code>minimum</code> is equal to 2, <code>maximum</code> is equal to 9, * and <code>snapInterval</code> is equal to 1.5, the valid * values for the Range are 2, 3.5, 5, 6.5, 8, and 9. * * @param value The input value. * @param interval The value of snapInterval or an integer multiple of snapInterval. * @return The valid value that's closest to the input. * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 返回 <code>minimum</code> 与最接近 <code>value</code> 的 <code>interval</code> 的整数倍数之和, * 除非 <code>value</code> 接近最大值限制的时候会返回 maximum。<p/> * * 如果 <code>interval</code> 等于 0,则会将该值剪裁到限制的最小值和最大值。<p/> * * 范围的有效值由 <code>minimum</code> 属性与 <code>interval</code> 的倍数之和决定, * 与此同时也要小于等于 <code>maximum</code> 属性。 * 最大值不能是 <code>snapInterval</code> 属性的倍数。<p/> * * 例如,如果 <code>minimum</code> 等于 1,<code>maximum</code> 等于 6,且 <code>snapInterval</code> 等于 3, * 则 Range 的有效值有 1、2、5、6。 * * 类似地,如果 <code>minimum</code> 等于 2,<code>maximum</code> 等于 9, * 且 <code>snapInterval</code> 等于 1.5,则 Range 的有效值有 2、3.5、5、6.5、8 和 9。 * * * @param value 输入值。 * @param interval snapInterval 的值,或 snapInterval 的整数倍数。 * @return 最近接输入值的有效值。 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected nearestValidValue(value:number, interval:number):number { let values = this.$Range; if (interval == 0) return Math.max(values[sys.RangeKeys.minimum], Math.min(values[sys.RangeKeys.maximum], value)); let maxValue = values[sys.RangeKeys.maximum] - values[sys.RangeKeys.minimum]; let scale = 1; value -= values[sys.RangeKeys.minimum]; if (interval != Math.round(interval)) { let parts = ((1 + interval).toString()).split("."); scale = Math.pow(10, parts[1].length); maxValue *= scale; value = Math.round(value * scale); interval = Math.round(interval * scale); } let lower = Math.max(0, Math.floor(value / interval) * interval); let upper = Math.min(maxValue, Math.floor((value + interval) / interval) * interval); let validValue = ((value - lower) >= ((upper - lower) / 2)) ? upper : lower; return (validValue / scale) + values[sys.RangeKeys.minimum]; } /** * Sets the current value for the <code>value</code> property.<p/> * * This method assumes that the caller has already used the <code>nearestValidValue()</code> method * to constrain the value parameter * * @param value The new value of the <code>value</code> property. * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 设置当前值。<p/> * * 此方法假定调用者已经使用了 nearestValidValue() 方法来约束 value 参数。 * * @param value value属性的新值 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected setValue(value:number):void { let values = this.$Range; if (values[sys.RangeKeys.value] === value) return; if (values[sys.RangeKeys.maximum] > values[sys.RangeKeys.minimum]) values[sys.RangeKeys.value] = Math.min(values[sys.RangeKeys.maximum], Math.max(values[sys.RangeKeys.minimum], value)); else values[sys.RangeKeys.value] = value; values[sys.RangeKeys.valueChanged] = false; this.invalidateDisplayList(); PropertyEvent.dispatchPropertyEvent(this,PropertyEvent.PROPERTY_CHANGE,"value"); } /** * Draws the object and/or sizes and positions its children. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 绘制对象和/或设置其子项的大小和位置 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected updateDisplayList(w:number, h:number):void { super.updateDisplayList(w, h); this.updateSkinDisplayList(); } /** * Update size and visible of skin parts.<p/> * Subclasses override this method to update skin parts display based on <code>minimum</code>, <code>maximum</code> * and <code>value</code> properties. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 更新皮肤部件(通常为滑块)的大小和可见性。<p/> * 子类覆盖此方法以基于 minimum、maximum 和 value 属性更新滑块的大小、位置和可见性。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected updateSkinDisplayList():void { } } registerBindable(Range.prototype,"value"); }
the_stack
import { assertEquals, assertRejects } from "../testing/asserts.ts"; import { Column, DataItem, NEWLINE, stringify, StringifyError, StringifyOptions, } from "./csv_stringify.ts"; type StringifyTestCaseBase = { columns: Column[]; data: DataItem[]; name: string; options?: StringifyOptions; }; type StringifyTestCaseError = StringifyTestCaseBase & { errorMessage?: string; // deno-lint-ignore no-explicit-any throwsError: new (...args: any[]) => Error; }; type StringifyTestCase = StringifyTestCaseBase & { expected: string }; const stringifyTestCases: (StringifyTestCase | StringifyTestCaseError)[] = [ { columns: ["a"], data: [["foo"], ["bar"]], errorMessage: 'Property accessor is not of type "number"', name: "[CSV_stringify] Access array index using string", throwsError: StringifyError, }, { columns: [0], data: [["foo"], ["bar"]], errorMessage: [ "Separator cannot include the following strings:", ' - U+0022: Quotation mark (")', " - U+000D U+000A: Carriage Return + Line Feed (\\r\\n)", ].join("\n"), name: "[CSV_stringify] Double quote in separator", options: { separator: '"' }, throwsError: StringifyError, }, { columns: [0], data: [["foo"], ["bar"]], errorMessage: [ "Separator cannot include the following strings:", ' - U+0022: Quotation mark (")', " - U+000D U+000A: Carriage Return + Line Feed (\\r\\n)", ].join("\n"), name: "[CSV_stringify] CRLF in separator", options: { separator: "\r\n" }, throwsError: StringifyError, }, { columns: [ { fn: (obj) => obj.toUpperCase(), prop: "msg", }, ], data: [{ msg: { value: "foo" } }, { msg: { value: "bar" } }], name: "[CSV_stringify] Transform function", throwsError: TypeError, }, { columns: [], data: [], expected: NEWLINE, name: "[CSV_stringify] No data, no columns", }, { columns: [], data: [], expected: ``, name: "[CSV_stringify] No data, no columns, no headers", options: { headers: false }, }, { columns: ["a"], data: [], expected: `a${NEWLINE}`, name: "[CSV_stringify] No data, columns", }, { columns: ["a"], data: [], expected: ``, name: "[CSV_stringify] No data, columns, no headers", options: { headers: false }, }, { columns: [], data: [{ a: 1 }, { a: 2 }], expected: `${NEWLINE}${NEWLINE}${NEWLINE}`, name: "[CSV_stringify] Data, no columns", }, { columns: [0, 1], data: [["foo", "bar"], ["baz", "qux"]], expected: `0\r1${NEWLINE}foo\rbar${NEWLINE}baz\rqux${NEWLINE}`, name: "[CSV_stringify] Separator: CR", options: { separator: "\r" }, }, { columns: [0, 1], data: [["foo", "bar"], ["baz", "qux"]], expected: `0\n1${NEWLINE}foo\nbar${NEWLINE}baz\nqux${NEWLINE}`, name: "[CSV_stringify] Separator: LF", options: { separator: "\n" }, }, { columns: [1], data: [{ 1: 1 }, { 1: 2 }], expected: `1${NEWLINE}1${NEWLINE}2${NEWLINE}`, name: "[CSV_stringify] Column: number accessor, Data: object", }, { columns: [{ header: "Value", prop: "value" }], data: [{ value: "foo" }, { value: "bar" }], expected: `foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Explicit header value, no headers", options: { headers: false }, }, { columns: [1], data: [["key", "foo"], ["key", "bar"]], expected: `1${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Column: number accessor, Data: array", }, { columns: [[1]], data: [{ 1: 1 }, { 1: 2 }], expected: `1${NEWLINE}1${NEWLINE}2${NEWLINE}`, name: "[CSV_stringify] Column: array number accessor, Data: object", }, { columns: [[1]], data: [["key", "foo"], ["key", "bar"]], expected: `1${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Column: array number accessor, Data: array", }, { columns: [[1, 1]], data: [["key", ["key", "foo"]], ["key", ["key", "bar"]]], expected: `1${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Column: array number accessor, Data: array", }, { columns: ["value"], data: [{ value: "foo" }, { value: "bar" }], expected: `value${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Column: string accessor, Data: object", }, { columns: [["value"]], data: [{ value: "foo" }, { value: "bar" }], expected: `value${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Column: array string accessor, Data: object", }, { columns: [["msg", "value"]], data: [{ msg: { value: "foo" } }, { msg: { value: "bar" } }], expected: `value${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Column: array string accessor, Data: object", }, { columns: [ { header: "Value", prop: ["msg", "value"], }, ], data: [{ msg: { value: "foo" } }, { msg: { value: "bar" } }], expected: `Value${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Explicit header", }, { columns: [ { fn: (str: string) => str.toUpperCase(), prop: ["msg", "value"], }, ], data: [{ msg: { value: "foo" } }, { msg: { value: "bar" } }], expected: `value${NEWLINE}FOO${NEWLINE}BAR${NEWLINE}`, name: "[CSV_stringify] Transform function 1", }, { columns: [ { fn: (str: string) => Promise.resolve(str.toUpperCase()), prop: ["msg", "value"], }, ], data: [{ msg: { value: "foo" } }, { msg: { value: "bar" } }], expected: `value${NEWLINE}FOO${NEWLINE}BAR${NEWLINE}`, name: "[CSV_stringify] Transform function 1 async", }, { columns: [ { fn: (obj: { value: string }) => obj.value, prop: "msg", }, ], data: [{ msg: { value: "foo" } }, { msg: { value: "bar" } }], expected: `msg${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Transform function 2", }, { columns: [ { fn: (obj: { value: string }) => obj.value, header: "Value", prop: "msg", }, ], data: [{ msg: { value: "foo" } }, { msg: { value: "bar" } }], expected: `Value${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Transform function 2, explicit header", }, { columns: [0], data: [[{ value: "foo" }], [{ value: "bar" }]], expected: `0${NEWLINE}"{""value"":""foo""}"${NEWLINE}"{""value"":""bar""}"${NEWLINE}`, name: "[CSV_stringify] Targeted value: object", }, { columns: [0], data: [ [[{ value: "foo" }, { value: "bar" }]], [[{ value: "baz" }, { value: "qux" }]], ], expected: `0${NEWLINE}"[{""value"":""foo""},{""value"":""bar""}]"${NEWLINE}"[{""value"":""baz""},{""value"":""qux""}]"${NEWLINE}`, name: "[CSV_stringify] Targeted value: arary of objects", }, { columns: [0], data: [[["foo", "bar"]], [["baz", "qux"]]], expected: `0${NEWLINE}"[""foo"",""bar""]"${NEWLINE}"[""baz"",""qux""]"${NEWLINE}`, name: "[CSV_stringify] Targeted value: array", }, { columns: [0], data: [[["foo", "bar"]], [["baz", "qux"]]], expected: `0${NEWLINE}"[""foo"",""bar""]"${NEWLINE}"[""baz"",""qux""]"${NEWLINE}`, name: "[CSV_stringify] Targeted value: array, separator: tab", options: { separator: "\t" }, }, { columns: [0], data: [[], []], expected: `0${NEWLINE}${NEWLINE}${NEWLINE}`, name: "[CSV_stringify] Targeted value: undefined", }, { columns: [0], data: [[null], [null]], expected: `0${NEWLINE}${NEWLINE}${NEWLINE}`, name: "[CSV_stringify] Targeted value: null", }, { columns: [0], data: [[0xa], [0xb]], expected: `0${NEWLINE}10${NEWLINE}11${NEWLINE}`, name: "[CSV_stringify] Targeted value: hex number", }, { columns: [0], data: [[BigInt("1")], [BigInt("2")]], expected: `0${NEWLINE}1${NEWLINE}2${NEWLINE}`, name: "[CSV_stringify] Targeted value: BigInt", }, { columns: [0], data: [[true], [false]], expected: `0${NEWLINE}true${NEWLINE}false${NEWLINE}`, name: "[CSV_stringify] Targeted value: boolean", }, { columns: [0], data: [["foo"], ["bar"]], expected: `0${NEWLINE}foo${NEWLINE}bar${NEWLINE}`, name: "[CSV_stringify] Targeted value: string", }, { columns: [0], data: [[Symbol("foo")], [Symbol("bar")]], expected: `0${NEWLINE}Symbol(foo)${NEWLINE}Symbol(bar)${NEWLINE}`, name: "[CSV_stringify] Targeted value: symbol", }, { columns: [0], data: [[(n: number) => n]], expected: `0${NEWLINE}(n) => n${NEWLINE}`, name: "[CSV_stringify] Targeted value: function", }, { columns: [0], data: [['foo"']], expected: `0${NEWLINE}"foo"""${NEWLINE}`, name: "[CSV_stringify] Value with double quote", }, { columns: [0], data: [["foo\r\n"]], expected: `0${NEWLINE}"foo\r\n"${NEWLINE}`, name: "[CSV_stringify] Value with CRLF", }, { columns: [0], data: [["foo\r"]], expected: `0${NEWLINE}foo\r${NEWLINE}`, name: "[CSV_stringify] Value with CR", }, { columns: [0], data: [["foo\n"]], expected: `0${NEWLINE}foo\n${NEWLINE}`, name: "[CSV_stringify] Value with LF", }, { columns: [0], data: [["foo,"]], expected: `0${NEWLINE}"foo,"${NEWLINE}`, name: "[CSV_stringify] Value with comma", }, { columns: [0], data: [["foo,"]], expected: `0${NEWLINE}foo,${NEWLINE}`, name: "[CSV_stringify] Value with comma, tab separator", options: { separator: "\t" }, }, ]; for (const tc of stringifyTestCases) { if ((tc as StringifyTestCaseError).throwsError) { const t = tc as StringifyTestCaseError; Deno.test({ async fn() { await assertRejects( async () => { await stringify(t.data, t.columns, t.options); }, t.throwsError, t.errorMessage, ); }, name: t.name, }); } else { const t = tc as StringifyTestCase; Deno.test({ async fn() { const actual = await stringify(t.data, t.columns, t.options); assertEquals(actual, t.expected); }, name: t.name, }); } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_projectapproval_Information { interface Header extends DevKit.Controls.IHeader { /** Shows the name of the approver. */ msdyn_ApprovedBy: DevKit.Controls.Lookup; /** Shows the resource that the entry is submitted for. */ msdyn_bookableresource: DevKit.Controls.Lookup; /** Shows the stage of the record. */ msdyn_recordstage: DevKit.Controls.OptionSet; } interface tab__6D5860C6_AEB2_4D17_9DB3_226A9D6466F5_Sections { _column_2_section_1: DevKit.Controls.Section; _D55B3080_93D0_497A_A1C6_823D788E066A: DevKit.Controls.Section; } interface tab__6D5860C6_AEB2_4D17_9DB3_226A9D6466F5 extends DevKit.Controls.ITab { Section: tab__6D5860C6_AEB2_4D17_9DB3_226A9D6466F5_Sections; } interface Tabs { _6D5860C6_AEB2_4D17_9DB3_226A9D6466F5: tab__6D5860C6_AEB2_4D17_9DB3_226A9D6466F5; } interface Body { Tab: Tabs; /** Billing type for the project approval line. */ msdyn_BillingType: DevKit.Controls.OptionSet; /** Shows the hours submitted for the transaction. */ msdyn_CostQuantity: DevKit.Controls.Decimal; /** Expense Entry Id. */ msdyn_ExpenseEntry: DevKit.Controls.Lookup; /** Shows the external comments entered for the transaction. */ msdyn_ExternalComments: DevKit.Controls.String; /** Shows whether the transaction has a receipt. */ msdyn_hasreceipt: DevKit.Controls.Boolean; /** Shows the sales price of the transaction. */ msdyn_SalesPrice: DevKit.Controls.Money; /** Shows the billable hours for the transaction. */ msdyn_SalesQuantity: DevKit.Controls.Decimal; /** Resource that has submitted the entry for approval. */ msdyn_SubmittedBy: DevKit.Controls.Lookup; /** Time Entry Id. */ msdyn_TimeEntry: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface quickForm_ExpenseEntryDetail_Body { msdyn_Amount: DevKit.Controls.QuickView; msdyn_ExpenseCategory: DevKit.Controls.QuickView; msdyn_externaldescription: DevKit.Controls.QuickView; msdyn_Price: DevKit.Controls.QuickView; msdyn_Project: DevKit.Controls.QuickView; msdyn_Quantity: DevKit.Controls.QuickView; msdyn_Salestaxamount: DevKit.Controls.QuickView; msdyn_totalamount: DevKit.Controls.QuickView; msdyn_TransactionDate: DevKit.Controls.QuickView; msdyn_Unit: DevKit.Controls.QuickView; msdyn_UnitGroup: DevKit.Controls.QuickView; TransactionCurrencyId: DevKit.Controls.QuickView; } interface quickForm_TimeEntryDetail_Body { msdyn_date: DevKit.Controls.QuickView; msdyn_description: DevKit.Controls.QuickView; msdyn_duration: DevKit.Controls.QuickView; msdyn_project: DevKit.Controls.QuickView; msdyn_projectTask: DevKit.Controls.QuickView; msdyn_resourceCategory: DevKit.Controls.QuickView; msdyn_type: DevKit.Controls.QuickView; } interface quickForm_ExpenseEntryDetail extends DevKit.Controls.IQuickView { Body: quickForm_ExpenseEntryDetail_Body; } interface quickForm_TimeEntryDetail extends DevKit.Controls.IQuickView { Body: quickForm_TimeEntryDetail_Body; } interface QuickForm { ExpenseEntryDetail: quickForm_ExpenseEntryDetail; TimeEntryDetail: quickForm_TimeEntryDetail; } } class Formmsdyn_projectapproval_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_projectapproval_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_projectapproval_Information */ Body: DevKit.Formmsdyn_projectapproval_Information.Body; /** The Header section of form msdyn_projectapproval_Information */ Header: DevKit.Formmsdyn_projectapproval_Information.Header; /** The QuickForm of form msdyn_projectapproval_Information */ QuickForm: DevKit.Formmsdyn_projectapproval_Information.QuickForm; } class msdyn_projectapprovalApi { /** * DynamicsCrm.DevKit msdyn_projectapprovalApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows the name of the approver. */ msdyn_ApprovedBy: DevKit.WebApi.LookupValue; /** Shows the date of the approval. */ msdyn_ApprovedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Billing type for the project approval line. */ msdyn_BillingType: DevKit.WebApi.OptionSetValue; /** Shows the resource that the entry is submitted for. */ msdyn_bookableresource: DevKit.WebApi.LookupValue; /** Shows the cost amount of the transaction. */ msdyn_costamount: DevKit.WebApi.MoneyValueReadonly; /** Value of the Cost Amount in base currency. */ msdyn_costamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the cost price of the transaction. */ msdyn_CostPrice: DevKit.WebApi.MoneyValue; /** Value of the Cost Price in base currency. */ msdyn_costprice_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the hours submitted for the transaction. */ msdyn_CostQuantity: DevKit.WebApi.DecimalValue; /** Shows the date of the transaction. */ msdyn_date_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the entry type of the transaction. */ msdyn_EntryType: DevKit.WebApi.OptionSetValue; /** Shows the expense category of the transaction. */ msdyn_ExpenseCategory: DevKit.WebApi.LookupValue; /** Expense Entry Id. */ msdyn_ExpenseEntry: DevKit.WebApi.LookupValue; /** Shows the external comments entered for the transaction. */ msdyn_ExternalComments: DevKit.WebApi.StringValue; /** Shows whether the transaction has a receipt. */ msdyn_hasreceipt: DevKit.WebApi.BooleanValue; /** Shows the internal comments entered for the transaction. */ msdyn_InternalComments: DevKit.WebApi.StringValue; /** Shows whether the transaction was entered by a journal. */ msdyn_JournalTransaction: DevKit.WebApi.StringValue; /** Shows the manager of the person who submitted the transaction. */ msdyn_Manager: DevKit.WebApi.LookupValue; /** The name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; /** Shows the project for the transaction. */ msdyn_Project: DevKit.WebApi.LookupValue; /** Unique identifier for entity instances */ msdyn_projectapprovalId: DevKit.WebApi.GuidValue; /** Shows the project task for the transaction. */ msdyn_ProjectTask: DevKit.WebApi.LookupValue; /** Shows the stage of the record. */ msdyn_recordstage: DevKit.WebApi.OptionSetValue; /** Shows the reference ID for the expense entry. */ msdyn_referenceexpenseid: DevKit.WebApi.StringValue; /** Shows the journal line ID for the journal transaction. */ msdyn_referencejournalline: DevKit.WebApi.LookupValue; msdyn_referencetimeid: DevKit.WebApi.StringValue; /** Shows the role for the resource for this transaction. */ msdyn_ResourceCategory: DevKit.WebApi.LookupValue; /** Shows the sales amount of the transaction. */ msdyn_salesamount: DevKit.WebApi.MoneyValueReadonly; /** Value of the Sales Amount in base currency. */ msdyn_salesamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the sales price of the transaction. */ msdyn_SalesPrice: DevKit.WebApi.MoneyValue; /** Value of the Sales Price in base currency. */ msdyn_salesprice_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the billable hours for the transaction. */ msdyn_SalesQuantity: DevKit.WebApi.DecimalValue; /** Resource that has submitted the entry for approval. */ msdyn_SubmittedBy: DevKit.WebApi.LookupValue; /** Time Entry Id. */ msdyn_TimeEntry: DevKit.WebApi.LookupValue; /** Shows the transaction category. */ msdyn_TransactionCategory: DevKit.WebApi.LookupValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the ApprovalsTable */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the ApprovalsTable */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Shows the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_projectapproval { enum msdyn_BillingType { /** 192350001 */ Chargeable, /** 192350002 */ Complimentary, /** 192350000 */ Non_Chargeable, /** 192350003 */ Not_Available } enum msdyn_EntryType { /** 1 */ Expense, /** 0 */ Time } enum msdyn_recordstage { /** 2 */ Approved, /** 3 */ Pending, /** 5 */ Recall_Request_Approved, /** 6 */ Recall_Request_Rejected, /** 4 */ Recall_Requested, /** 1 */ Rejected, /** 0 */ Submitted } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import React from 'react'; import { mount } from 'enzyme'; import mountTest from '../../../tests/mountTest'; import Tree from '..'; import { IconHeartFill } from '../../../icon'; import { NodeProps } from '../interface'; import componentConfigTest from '../../../tests/componentConfigTest'; componentConfigTest(Tree, 'Tree'); mountTest(Tree); const TreeNode = Tree.Node; const prefixCls = '.arco-tree'; const data = [ { key: 'node1', title: '拉尼斯特家族', children: [ { key: 'node1-1', title: '小恶魔', children: [ { key: 'node1-1-1', title: '小小恶魔', }, ], }, ], }, { key: 'node2', title: '史塔克家族', children: [ { key: 'node2-1', title: '二丫', }, { key: 'node2-2', title: '三傻', }, ], }, ]; const defaultSelectedKeys = ['node2']; const defaultExpandedKeys = ['node1']; // 从treedata 生成 treenode const generatorTreeNodes = (treeData) => { return treeData.map((item) => { const { children, key, ...rest } = item; return ( <Tree.Node key={key} {...rest} dataRef={item}> {children ? generatorTreeNodes(item.children) : null} </Tree.Node> ); }); }; const getTreeNodesLength = (treeData) => { let results = treeData.length; for (let i = 0; i < treeData.length; i++) { const item = treeData[i]; const { children } = item; if (children) { results += getTreeNodesLength(children); } else { continue; } } return results; }; // const getLeafLength = (treeData) => { // const obj = Array.isArray(treeData) ? { children: treeData } : treeData; // if (!obj.children || obj.children.length === 0) { // return 1; // } // let leafCount = 0; // for (let i = 0; i < obj.children.length; i++) { // leafCount += getLeafLength(obj.children[i]); // } // return leafCount; // }; describe('Tree', () => { beforeEach(() => { jest.useFakeTimers(); }); afterEach(() => { jest.runAllTimers(); }); it('tree render basic', () => { const wrapper = mount(<Tree>{generatorTreeNodes(data)}</Tree>); const summaryNodeLength = getTreeNodesLength(data); expect(wrapper.find(`${prefixCls}-node`)).toHaveLength(summaryNodeLength); }); it('tree render treedata', () => { const wrapper = mount(<Tree treeData={data} />); const wrapper2 = mount(<Tree>{generatorTreeNodes(data)}</Tree>); expect(wrapper.html()).toEqual(wrapper2.html()); }); it('should be expanded and collapsed', () => { const mockExpand = jest.fn(); const wrapper = mount( <Tree defaultExpandedKeys={defaultExpandedKeys} onExpand={mockExpand}> {generatorTreeNodes(data)} </Tree> ); expect(wrapper.state('expandedKeys')).toEqual(defaultExpandedKeys); wrapper .find(`${prefixCls}-node-expanded`) .first() .find(`${prefixCls}-node-switcher-icon`) .first() .simulate('click'); expect(wrapper.state('expandedKeys')).toEqual([]); // onExpand无法触发的bug expect(mockExpand.mock.calls.length).toBe(1); wrapper .find(`${prefixCls}-node`) .last() .find(`${prefixCls}-node-switcher-icon`) .first() .simulate('click'); expect(wrapper.state('expandedKeys')).toHaveLength(1); }); it('should be expanded and collapsed when expandedKeys in props', () => { let keys = []; const wrapper = mount( <Tree expandedKeys={['node1-1-1']} onExpand={(v) => (keys = v)}> {generatorTreeNodes(data)} </Tree> ); // 子节点展开,子节点的父节点也需要都展开 expect(wrapper.state('expandedKeys')).toEqual(['node1-1-1', 'node1', 'node1-1']); wrapper.find(`${prefixCls}-node-switcher-icon`).at(1).simulate('click'); // 父节点关闭,子节点保持展开 expect(keys).toEqual(['node1-1-1', 'node1']); wrapper.setProps({ expandedKeys: keys, }); wrapper.setProps({ expandedKeys: ['node2-1'], }); wrapper.update(); expect(wrapper.state('expandedKeys')).toEqual(['node2-1']); }); it('should be selected correctly', () => { const mockSelected = jest.fn(); const wrapper = mount( <Tree defaultSelectedKeys={defaultSelectedKeys} onSelect={mockSelected}> {generatorTreeNodes(data)} </Tree> ); expect(wrapper.state('selectedKeys')).toEqual(defaultSelectedKeys); wrapper .find(`${prefixCls}-node`) .first() .find(`${prefixCls}-node-title`) .first() .simulate('click'); expect(mockSelected.mock.calls).toHaveLength(1); const selectedKeys = wrapper.state('selectedKeys'); expect(selectedKeys).toHaveLength(1); expect(selectedKeys).toEqual(['node1']); }); it('should be selected correctly when multiple', () => { const mockSelected = jest.fn(); const wrapper = mount( <Tree multiple defaultSelectedKeys={defaultSelectedKeys} onSelect={mockSelected}> {generatorTreeNodes(data)} </Tree> ); expect(wrapper.state('selectedKeys')).toEqual(defaultSelectedKeys); wrapper .find(`${prefixCls}-node`) .first() .find(`${prefixCls}-node-title`) .first() .simulate('click'); expect(mockSelected.mock.calls).toHaveLength(1); const selectedKeys = wrapper.state('selectedKeys'); expect(selectedKeys).toHaveLength(2); expect(selectedKeys).toEqual(['node2', 'node1']); }); it('should checked correctly', () => { const defaultCheckedKeys = ['node1']; let checkedKeys = []; const wrapper = mount( <Tree checkable onCheck={(keys) => { checkedKeys = keys; }} defaultCheckedKeys={defaultCheckedKeys} > {generatorTreeNodes(data)} </Tree> ); expect(wrapper.state('checkedKeys')).toEqual(['node1', 'node1-1', 'node1-1-1']); wrapper .find(`${prefixCls}-node`) .at(3) .find(`.arco-checkbox > input`) .first() .simulate('change', { target: { checked: true, }, }); expect(checkedKeys).toEqual(['node1', 'node1-1', 'node1-1-1', 'node2', 'node2-1', 'node2-2']); expect(wrapper.state('selectedKeys')).toEqual([]); }); it('should checkStrictly correctly', () => { const mockChecked = jest.fn(); const defaultCheckedKeys = ['node1']; const wrapper = mount( <Tree checkable checkStrictly onCheck={mockChecked} defaultCheckedKeys={defaultCheckedKeys}> {generatorTreeNodes(data)} </Tree> ); // 目前通过 expect(wrapper.state('checkedKeys')).toEqual(['node1']); wrapper .find(`${prefixCls}-node`) .at(3) .find(`.arco-checkbox > input`) .first() .simulate('change', { target: { checked: true, }, }); expect(wrapper.state('checkedKeys')).toEqual(['node1', 'node2']); expect(mockChecked.mock.calls).toHaveLength(1); }); it('should render empty correctly', () => { const wrapper = mount(<Tree>{generatorTreeNodes([])}</Tree>); expect(wrapper.find('Tree')).toHaveLength(1); expect(wrapper.find(`${prefixCls}-node`)).toHaveLength(0); }); it('should loadMore correctly', () => { const loadMore = jest.fn(); const wrapper = mount(<Tree loadMore={loadMore}>{generatorTreeNodes(data)}</Tree>); const iconLength = wrapper.find(`${prefixCls}-node-switcher-icon`).length; expect(wrapper.find(`${prefixCls}-node`).length).toEqual(iconLength); wrapper .find(`${prefixCls}-node`) .last() .find(`${prefixCls}-node-switcher-icon`) .simulate('click'); expect(loadMore.mock.calls).toHaveLength(1); }); it('selected correctly when disabled', () => { const mockSelected = jest.fn(); const wrapper = mount( <Tree onSelect={mockSelected}> <TreeNode key="node1" title="拉尼斯特家族" disabled> <TreeNode key="node2" title="小恶魔"> <TreeNode key="node21" title="小恶魔aaa" /> </TreeNode> </TreeNode> <TreeNode key="node3" title="史塔克家族"> <TreeNode key="node4" title="二丫" /> <TreeNode key="node5" title="三傻" /> </TreeNode> </Tree> ); const disabledItem = wrapper.find(`${prefixCls}-node-disabled`); expect(disabledItem).toHaveLength(1); disabledItem.find(`${prefixCls}-node-title`).first().simulate('click'); expect(mockSelected.mock.calls).toHaveLength(0); }); it('self icon render correctly', () => { const wrapper = mount( <Tree> <TreeNode key="node1" title="拉尼斯特家族" icon={<IconHeartFill />} /> <TreeNode key="node2" title="史塔克家族" /> </Tree> ); expect(wrapper.find('IconHeartFill')).toHaveLength(1); // expect(wrapper.find(`${prefixCls}-node-switcher-icon`)).toHaveLength(1); }); it('should selectable, disableCheckbox correctly', () => { const mockSelected = jest.fn(); const mockChecked = jest.fn(); const wrapper = mount( <Tree checkable defaultSelectedKeys={defaultSelectedKeys} onSelect={mockSelected} onCheck={mockChecked} treeData={[ ...data, // TODO: 移除`as`语句 { key: 'disbaled', label: 'disablde', selectable: false, disableCheckbox: true, } as NodeProps, ]} /> ); expect(wrapper.state('selectedKeys')).toEqual(defaultSelectedKeys); wrapper .find(`${prefixCls}-node`) .last() .find(`${prefixCls}-node-title`) .first() .simulate('click'); wrapper .find(`${prefixCls}-node`) .last() .find(`.arco-checkbox > input`) .first() .simulate('change', { target: { checked: true, }, }); expect(mockSelected.mock.calls).toHaveLength(0); expect(mockChecked.mock.calls).toHaveLength(0); const selectedKeys = wrapper.state('selectedKeys'); expect(selectedKeys).toHaveLength(1); expect(selectedKeys).toEqual(['node2']); }); it('should checkedStrategy correctly', () => { let checkedKeys = ['node1']; const wrapper = mount( <Tree checkable checkedStrategy={Tree.SHOW_PARENT} onCheck={(value) => { checkedKeys = value; }} checkedKeys={checkedKeys} > {generatorTreeNodes(data)} </Tree> ); expect(wrapper.state('checkedKeys')).toEqual(['node1', 'node1-1', 'node1-1-1']); const lastChild = wrapper .find(`${prefixCls}-node`) .at(3) .find(`.arco-checkbox > input`) .first(); lastChild.simulate('change', { target: { checked: true, }, }); expect(checkedKeys).toEqual(['node1', 'node2']); wrapper.setProps({ checkedKeys: ['node1', 'node2'] }); expect(wrapper.state('checkedKeys')).toEqual([ 'node1', 'node2', 'node1-1', 'node1-1-1', 'node2-1', 'node2-2', ]); wrapper.setProps({ checkedStrategy: Tree.SHOW_CHILD }); lastChild.simulate('change', { target: { checked: false } }); expect(checkedKeys).toEqual(['node1-1-1']); wrapper.setProps({ checkedKeys }); expect(wrapper.state('checkedKeys')).toEqual(['node1-1-1', 'node1-1', 'node1']); wrapper.setProps({ checkStrictly: true }); lastChild.simulate('change', { target: { checked: true } }); wrapper.setProps({ checkedKeys }); expect(checkedKeys).toEqual(['node1-1-1', 'node2']); expect(wrapper.state('checkedKeys')).toEqual(checkedKeys); wrapper.update(); expect(wrapper.find('.arco-checkbox.arco-checkbox-checked')).toHaveLength(2); }); it('should halfchecked correctly', () => { const defaultCheckedKeys = ['node1']; const wrapper = mount( <Tree checkStrictly checkable halfCheckedKeys={defaultCheckedKeys}> {generatorTreeNodes(data)} </Tree> ); wrapper .find(`${prefixCls}-node`) .at(1) .find(`.arco-checkbox`) .hasClass('arco-checkbox-indeterminate'); }); it('should be expanded when click node', () => { const mockExpand = jest.fn(); const mockSelected = jest.fn(); const wrapper = mount( <Tree defaultExpandedKeys={[]} actionOnClick="expand" onSelect={mockSelected} onExpand={mockExpand} > {generatorTreeNodes(data)} </Tree> ); expect(wrapper.find('.arco-tree-node-title-text').at(1).text()).toBe('史塔克家族'); wrapper .find(`${prefixCls}-node`) .first() .find(`${prefixCls}-node-title`) .first() .simulate('click'); expect(mockExpand.mock.calls).toHaveLength(1); expect(mockSelected.mock.calls).toHaveLength(0); expect(wrapper.find('.arco-tree-node-title-text').at(1).text()).toBe('小恶魔'); }); it('should be checked and expand when click node', () => { let checkedKeys; const wrapper = mount( <Tree defaultExpandedKeys={[]} checkable onCheck={(keys) => (checkedKeys = keys)} actionOnClick={['check', 'expand']} > {generatorTreeNodes(data)} </Tree> ); expect(wrapper.find('.arco-tree-node-title-text').at(1).text()).toBe('史塔克家族'); wrapper .find(`${prefixCls}-node`) .first() .find(`${prefixCls}-node-title`) .first() .simulate('click'); expect(wrapper.find('.arco-tree-node-title-text').at(1).text()).toBe('小恶魔'); expect(wrapper.find('.arco-checkbox-checked')).toHaveLength(2); expect(checkedKeys).toEqual(['node1', 'node1-1', 'node1-1-1']); }); });
the_stack
import * as path from 'path'; import * as tl from 'azure-pipelines-task-lib/task'; import * as tr from 'azure-pipelines-task-lib/toolrunner'; import * as utils from './helpers'; import * as constants from './constants'; import * as ci from './cieventlogger'; import { AreaCodes, DistributionTypes } from './constants'; import * as idc from './inputdatacontract'; import * as Q from "q"; import * as isUncPath from 'is-unc-path'; const regedit = require('regedit'); let serverBasedRun = false; let enableDiagnosticsSettings = false; // TODO: refactor all log messages to a separate function // replace else if ladders with switch if possible // unravel long else if chains export function parseInputsForDistributedTestRun() : idc.InputDataContract { let inputDataContract = {} as idc.InputDataContract; inputDataContract = getTestSelectionInputs(inputDataContract); inputDataContract = getTfsSpecificSettings(inputDataContract); inputDataContract = getTargetBinariesSettings(inputDataContract); inputDataContract = getTestReportingSettings(inputDataContract); inputDataContract = getTestPlatformSettings(inputDataContract); inputDataContract = getLoggingSettings(inputDataContract); inputDataContract = getProxySettings(inputDataContract); inputDataContract = getDistributionSettings(inputDataContract); inputDataContract = getExecutionSettings(inputDataContract); inputDataContract.TeamProject = tl.getVariable('System.TeamProject'); inputDataContract.CollectionUri = tl.getVariable('System.TeamFoundationCollectionUri'); inputDataContract.AgentName = tl.getVariable('Agent.MachineName') + '-' + tl.getVariable('Agent.Name') + '-' + tl.getVariable('Agent.Id'); inputDataContract.AccessTokenType = 'jwt'; inputDataContract.RunIdentifier = getRunIdentifier(); inputDataContract.SourcesDirectory = tl.getVariable('Build.SourcesDirectory'); inputDataContract.ServerType = tl.getVariable('System.ServerType'); logWarningForWER(tl.getBoolInput('uiTests')); ci.publishEvent({ 'UiTestsOptionSelected': tl.getBoolInput('uiTests')} ); return inputDataContract; } export function parseInputsForNonDistributedTestRun() : idc.InputDataContract { let inputDataContract = {} as idc.InputDataContract; // hydra: should i create a separate function since testplan and testrun are never scenarios for local test? inputDataContract = getTestSelectionInputs(inputDataContract); inputDataContract = getTfsSpecificSettings(inputDataContract); inputDataContract = getTargetBinariesSettings(inputDataContract); inputDataContract = getTestReportingSettings(inputDataContract); inputDataContract = getTestPlatformSettings(inputDataContract); inputDataContract = getLoggingSettings(inputDataContract); inputDataContract = getProxySettings(inputDataContract); inputDataContract = getExecutionSettings(inputDataContract); inputDataContract.TeamProject = tl.getVariable('System.TeamProject'); inputDataContract.CollectionUri = tl.getVariable('System.TeamFoundationCollectionUri'); inputDataContract.AccessToken = tl.getEndpointAuthorization('SystemVssConnection', true).parameters.AccessToken; inputDataContract.AccessTokenType = 'jwt'; inputDataContract.AgentName = tl.getVariable('Agent.MachineName') + '-' + tl.getVariable('Agent.Name') + '-' + tl.getVariable('Agent.Id'); inputDataContract.RunIdentifier = getRunIdentifier(); inputDataContract.EnableSingleAgentAPIFlow = utils.Helper.stringToBool(tl.getVariable('Hydra.EnableApiFlow')); inputDataContract.SourcesDirectory = tl.getVariable('Build.SourcesDirectory'); inputDataContract.ServerType = tl.getVariable('System.ServerType'); logWarningForWER(tl.getBoolInput('uiTests')); return inputDataContract; } function getTestSelectionInputs(inputDataContract : idc.InputDataContract) : idc.InputDataContract { inputDataContract.TestSelectionSettings = <idc.TestSelectionSettings>{}; inputDataContract.TestSelectionSettings.TestSelectionType = tl.getInput('testSelector').toLowerCase(); switch (inputDataContract.TestSelectionSettings.TestSelectionType) { case 'testplan': inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings = <idc.TestPlanTestSuiteSettings>{}; console.log(tl.loc('testSelectorInput', tl.loc('testPlanSelector'))); inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.Testplan = parseInt(tl.getInput('testPlan')); console.log(tl.loc('testPlanInput', inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.Testplan)); inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.TestPlanConfigId = parseInt(tl.getInput('testConfiguration')); console.log(tl.loc('testplanConfigInput', inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.TestPlanConfigId)); const testSuiteStrings = tl.getDelimitedInput('testSuite', ',', true); inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.TestSuites = new Array<number>(); testSuiteStrings.forEach(element => { const testSuiteId = parseInt(element); console.log(tl.loc('testSuiteSelected', testSuiteId)); inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.TestSuites.push(testSuiteId); }); break; case 'testassemblies': console.log(tl.loc('testSelectorInput', tl.loc('testAssembliesSelector'))); inputDataContract.TestSelectionSettings.TestCaseFilter = tl.getInput('testFiltercriteria'); console.log(tl.loc('testFilterCriteriaInput', inputDataContract.TestSelectionSettings.TestCaseFilter)); break; case 'testrun': inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings = <idc.TestPlanTestSuiteSettings>{}; console.log(tl.loc('testSelectorInput', tl.loc('testRunSelector'))); inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.OnDemandTestRunId = parseInt(tl.getInput('tcmTestRun')); if (inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.OnDemandTestRunId <= 0) { throw new Error(tl.loc('testRunIdInvalid', inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.OnDemandTestRunId)); } console.log(tl.loc('testRunIdInput', inputDataContract.TestSelectionSettings.TestPlanTestSuiteSettings.OnDemandTestRunId)); break; } inputDataContract.TestSelectionSettings.SearchFolder = tl.getInput('searchFolder'); if (!utils.Helper.isNullOrWhitespace(inputDataContract.TestSelectionSettings.SearchFolder)) { inputDataContract.TestSelectionSettings.SearchFolder = path.resolve(inputDataContract.TestSelectionSettings.SearchFolder); } if (inputDataContract.TestSelectionSettings.SearchFolder && !utils.Helper.pathExistsAsDirectory(inputDataContract.TestSelectionSettings.SearchFolder)) { throw new Error(tl.loc('searchLocationNotDirectory', inputDataContract.TestSelectionSettings.SearchFolder)); } if (isUncPath(inputDataContract.TestSelectionSettings.SearchFolder)) { throw new Error(tl.loc('UncPathNotSupported')); } console.log(tl.loc('searchFolderInput', inputDataContract.TestSelectionSettings.SearchFolder)); return inputDataContract; } function getTfsSpecificSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { inputDataContract.TfsSpecificSettings = <idc.TfsSpecificSettings>{}; inputDataContract.TfsSpecificSettings.BuildDefinitionId = utils.Helper.isNullEmptyOrUndefined(tl.getVariable('Release.DefinitionId')) ? Number(tl.getVariable('System.DefinitionId')) : Number(tl.getVariable('Build.DefinitionId')); inputDataContract.TfsSpecificSettings.ReleaseDefinitionId = utils.Helper.isNullEmptyOrUndefined(tl.getVariable('Release.DefinitionId')) ? null : Number(tl.getVariable('Release.DefinitionId')); inputDataContract.TfsSpecificSettings.BuildId = utils.Helper.isNullEmptyOrUndefined(tl.getVariable('Build.Buildid')) ? null : Number(tl.getVariable('Build.Buildid')); inputDataContract.TfsSpecificSettings.BuildUri = tl.getVariable('Build.BuildUri'); inputDataContract.TfsSpecificSettings.ReleaseId = utils.Helper.isNullEmptyOrUndefined(tl.getVariable('Release.ReleaseId')) ? null : Number(tl.getVariable('Release.ReleaseId')); inputDataContract.TfsSpecificSettings.ReleaseUri = tl.getVariable('Release.ReleaseUri'); inputDataContract.TfsSpecificSettings.ReleaseEnvironmentUri = tl.getVariable('Release.EnvironmentUri'); inputDataContract.TfsSpecificSettings.WorkFolder = tl.getVariable('System.DefaultWorkingDirectory'); inputDataContract.TfsSpecificSettings.PhaseName = tl.getVariable('System.PhaseName'); inputDataContract.TfsSpecificSettings.PhaseAttempt = utils.Helper.isNullEmptyOrUndefined(tl.getVariable('System.PhaseAttempt')) ? null : Number(tl.getVariable('System.PhaseAttempt')); inputDataContract.TfsSpecificSettings.StageName = tl.getVariable('System.StageName'); inputDataContract.TfsSpecificSettings.StageAttempt = utils.Helper.isNullEmptyOrUndefined(tl.getVariable('System.StageAttempt')) ? null : Number(tl.getVariable('System.StageAttempt')); inputDataContract.TfsSpecificSettings.JobName = tl.getVariable('System.JobName'); inputDataContract.TfsSpecificSettings.JobAttempt = utils.Helper.isNullEmptyOrUndefined(tl.getVariable('System.JobAttempt')) ? null : Number(tl.getVariable('System.JobAttempt')); return inputDataContract; } function getTargetBinariesSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { inputDataContract.TargetBinariesSettings = <idc.TargetBinariesSettings>{}; inputDataContract.TargetBinariesSettings.BuildConfig = tl.getInput('configuration'); inputDataContract.TargetBinariesSettings.BuildPlatform = tl.getInput('platform'); return inputDataContract; } function getTestReportingSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { inputDataContract.TestReportingSettings = <idc.TestReportingSettings>{}; inputDataContract.TestReportingSettings.TestRunTitle = tl.getInput('testRunTitle'); inputDataContract.TestReportingSettings.TestRunSystem = 'VSTS - vstest'; const resultsDir = path.resolve(tl.getVariable('Agent.TempDirectory'), tl.getInput('resultsFolder')); inputDataContract.TestReportingSettings.TestResultsDirectory = resultsDir; tl.debug("TestResultsFolder: " + resultsDir); addResultsDirectoryToTelemetry(resultsDir); inputDataContract.TestReportingSettings.TestSourceSettings = <idc.TestSourceSettings>{}; inputDataContract.TestReportingSettings.TestSourceSettings.PullRequestTargetBranchName = tl.getVariable('System.PullRequest.TargetBranch'); inputDataContract.TestReportingSettings.ExecutionStatusSettings = <idc.ExecutionStatusSettings>{}; inputDataContract.TestReportingSettings.ExecutionStatusSettings.MinimumExecutedTestsExpected = 0; inputDataContract.TestReportingSettings.ExecutionStatusSettings.ActionOnThresholdNotMet = "donothing"; inputDataContract.TestReportingSettings.ExecutionStatusSettings.IgnoreTestFailures = utils.Helper.stringToBool(tl.getVariable('vstest.ignoretestfailures')); if (utils.Helper.isNullEmptyOrUndefined(inputDataContract.TestReportingSettings.TestRunTitle)) { let definitionName = tl.getVariable('BUILD_DEFINITIONNAME'); let buildOrReleaseName = tl.getVariable('BUILD_BUILDNUMBER'); if (inputDataContract.TfsSpecificSettings.ReleaseUri) { definitionName = tl.getVariable('RELEASE_DEFINITIONNAME'); buildOrReleaseName = tl.getVariable('RELEASE_RELEASENAME'); } inputDataContract.TestReportingSettings.TestRunTitle = `TestRun_${definitionName}_${buildOrReleaseName}`; } const actionOnThresholdNotMet = tl.getBoolInput('failOnMinTestsNotRun'); if (actionOnThresholdNotMet) { inputDataContract.TestReportingSettings.ExecutionStatusSettings.ActionOnThresholdNotMet = "fail"; const minimumExpectedTests = parseInt(tl.getInput('minimumExpectedTests')); if (!isNaN(minimumExpectedTests)) { inputDataContract.TestReportingSettings.ExecutionStatusSettings.MinimumExecutedTestsExpected = minimumExpectedTests; } else { throw new Error(tl.loc('invalidMinimumExpectedTests :' + tl.getInput('minimumExpectedTests'))); } } console.log(tl.loc('actionOnThresholdNotMet', inputDataContract.TestReportingSettings.ExecutionStatusSettings.ActionOnThresholdNotMet)) console.log(tl.loc('minimumExpectedTests', inputDataContract.TestReportingSettings.ExecutionStatusSettings.MinimumExecutedTestsExpected)); return inputDataContract; } function getTestPlatformSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { const vsTestLocationMethod = tl.getInput('vstestLocationMethod'); if (vsTestLocationMethod === utils.Constants.vsTestVersionString) { const vsTestVersion = tl.getInput('vsTestVersion'); if (utils.Helper.isNullEmptyOrUndefined(vsTestVersion)) { console.log(tl.loc('VsTestVersionEmpty')); throw new Error(tl.loc('VsTestVersionEmpty')); } else if (vsTestVersion.toLowerCase() === 'toolsinstaller') { tl.debug('Trying VsTest installed by tools installer.'); ci.publishEvent({ subFeature: 'ToolsInstallerSelected', isToolsInstallerPackageLocationSet: !utils.Helper.isNullEmptyOrUndefined(tl.getVariable(constants.VsTestToolsInstaller.PathToVsTestToolVariable)) }); inputDataContract.UsingXCopyTestPlatformPackage = true; const vsTestPackageLocation = tl.getVariable(constants.VsTestToolsInstaller.PathToVsTestToolVariable); tl.debug('Path to VsTest from tools installer: ' + vsTestPackageLocation); // get path to vstest.console.exe const matches = tl.findMatch(vsTestPackageLocation, '**\\vstest.console.exe'); if (matches && matches.length !== 0) { inputDataContract.VsTestConsolePath = path.dirname(matches[0]); } else { utils.Helper.publishEventToCi(AreaCodes.TOOLSINSTALLERCACHENOTFOUND, tl.loc('toolsInstallerPathNotSet'), 1041, false); throw new Error(tl.loc('toolsInstallerPathNotSet')); } // if Tools installer is not there throw. if (utils.Helper.isNullOrWhitespace(inputDataContract.VsTestConsolePath)) { ci.publishEvent({ subFeature: 'ToolsInstallerInstallationError' }); utils.Helper.publishEventToCi(AreaCodes.SPECIFIEDVSVERSIONNOTFOUND, 'Tools installer task did not complete successfully.', 1040, true); throw new Error(tl.loc('ToolsInstallerInstallationError')); } ci.publishEvent({ subFeature: 'ToolsInstallerInstallationSuccessful' }); } else if ((vsTestVersion !== '16.0') && (vsTestVersion !== '15.0') && (vsTestVersion !== '14.0') && (vsTestVersion.toLowerCase() !== 'latest')) { throw new Error(tl.loc('vstestVersionInvalid', vsTestVersion)); } else if (vsTestLocationMethod === utils.Constants.vsTestVersionString && vsTestVersion === '12.0') { throw (tl.loc('vs2013NotSupportedInDta')); } else { console.log(tl.loc('vsVersionSelected', vsTestVersion)); inputDataContract.VsTestConsolePath = getTestPlatformPath(inputDataContract); } } else { // hydra: should it be full path or directory above? inputDataContract.VsTestConsolePath = tl.getInput('vsTestLocation'); console.log(tl.loc('vstestLocationSpecified', 'vstest.console.exe', inputDataContract.VsTestConsolePath)); if (inputDataContract.VsTestConsolePath.endsWith('vstest.console.exe')) { inputDataContract.VsTestConsolePath = path.dirname(inputDataContract.VsTestConsolePath); } } return inputDataContract; } function getLoggingSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { // InputDataContract.Logging inputDataContract.Logging = <idc.Logging>{}; inputDataContract.Logging.EnableConsoleLogs = true; if (utils.Helper.isDebugEnabled()) { inputDataContract.Logging.DebugLogging = true; } return inputDataContract; } function getProxySettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { // Get proxy details inputDataContract.ProxySettings = <idc.ProxySettings>{}; inputDataContract.ProxySettings.ProxyUrl = tl.getVariable('agent.proxyurl'); inputDataContract.ProxySettings.ProxyUsername = tl.getVariable('agent.proxyusername'); inputDataContract.ProxySettings.ProxyPassword = tl.getVariable('agent.proxypassword'); inputDataContract.ProxySettings.ProxyBypassHosts = tl.getVariable('agent.proxybypasslist'); return inputDataContract; } function getDistributionSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { inputDataContract.DistributionSettings = <idc.DistributionSettings>{}; inputDataContract.DistributionSettings.NumberOfTestAgents = 1; const totalJobsInPhase = parseInt(tl.getVariable('SYSTEM_TOTALJOBSINPHASE')); if (!isNaN(totalJobsInPhase)) { inputDataContract.DistributionSettings.NumberOfTestAgents = totalJobsInPhase; } console.log(tl.loc('dtaNumberOfAgents', inputDataContract.DistributionSettings.NumberOfTestAgents)); const distributionType = tl.getInput('distributionBatchType'); switch (distributionType) { case 'basedOnTestCases': inputDataContract.DistributionSettings.DistributeTestsBasedOn = DistributionTypes.NUMBEROFTESTMETHODSBASED; const distributeByAgentsOption = tl.getInput('batchingBasedOnAgentsOption'); if (distributeByAgentsOption && distributeByAgentsOption === 'customBatchSize') { const batchSize = parseInt(tl.getInput('customBatchSizeValue')); if (!isNaN(batchSize) && batchSize > 0) { inputDataContract.DistributionSettings.NumberOfTestCasesPerSlice = batchSize; console.log(tl.loc('numberOfTestCasesPerSlice', inputDataContract.DistributionSettings.NumberOfTestCasesPerSlice)); } else { throw new Error(tl.loc('invalidTestBatchSize', batchSize)); } } break; case 'basedOnExecutionTime': inputDataContract.DistributionSettings.DistributeTestsBasedOn = DistributionTypes.EXECUTIONTIMEBASED; const batchBasedOnExecutionTimeOption = tl.getInput('batchingBasedOnExecutionTimeOption'); if (batchBasedOnExecutionTimeOption && batchBasedOnExecutionTimeOption === 'customTimeBatchSize') { const batchExecutionTimeInSec = parseInt(tl.getInput('customRunTimePerBatchValue')); if (isNaN(batchExecutionTimeInSec) || batchExecutionTimeInSec <= 0) { throw new Error(tl.loc('invalidRunTimePerBatch', batchExecutionTimeInSec)); } inputDataContract.DistributionSettings.RunTimePerSlice = batchExecutionTimeInSec; console.log(tl.loc('RunTimePerBatch', inputDataContract.DistributionSettings.RunTimePerSlice)); } break; case 'basedOnAssembly': inputDataContract.DistributionSettings.DistributeTestsBasedOn = DistributionTypes.ASSEMBLYBASED; break; } return inputDataContract; } function getExecutionSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { inputDataContract.ExecutionSettings = <idc.ExecutionSettings>{}; if (tl.filePathSupplied('runSettingsFile')) { inputDataContract.ExecutionSettings.SettingsFile = path.resolve(tl.getPathInput('runSettingsFile')); console.log(tl.loc('runSettingsFileInput', inputDataContract.ExecutionSettings.SettingsFile)); } inputDataContract.ExecutionSettings.TempFolder = utils.Helper.GetTempFolder(); inputDataContract.ExecutionSettings.OverridenParameters = tl.getInput('overrideTestrunParameters'); tl.debug(`OverrideTestrunParameters set to ${inputDataContract.ExecutionSettings.OverridenParameters}`); inputDataContract.ExecutionSettings.AssemblyLevelParallelism = tl.getBoolInput('runInParallel'); console.log(tl.loc('runInParallelInput', inputDataContract.ExecutionSettings.AssemblyLevelParallelism)); inputDataContract.ExecutionSettings.RunTestsInIsolation = tl.getBoolInput('runTestsInIsolation'); console.log(tl.loc('runInIsolationInput', inputDataContract.ExecutionSettings.RunTestsInIsolation)); if (serverBasedRun && inputDataContract.ExecutionSettings.RunTestsInIsolation) { inputDataContract.ExecutionSettings.RunTestsInIsolation = null; tl.warning(tl.loc('runTestInIsolationNotSupported')); } inputDataContract.ExecutionSettings.PathToCustomTestAdapters = tl.getInput('pathtoCustomTestAdapters'); if (!utils.Helper.isNullOrWhitespace(inputDataContract.ExecutionSettings.PathToCustomTestAdapters)) { inputDataContract.ExecutionSettings.PathToCustomTestAdapters = path.resolve(inputDataContract.ExecutionSettings.PathToCustomTestAdapters); } if (inputDataContract.ExecutionSettings.PathToCustomTestAdapters && !utils.Helper.pathExistsAsDirectory(inputDataContract.ExecutionSettings.PathToCustomTestAdapters)) { throw new Error(tl.loc('pathToCustomAdaptersInvalid', inputDataContract.ExecutionSettings.PathToCustomTestAdapters)); } console.log(tl.loc('pathToCustomAdaptersInput', inputDataContract.ExecutionSettings.PathToCustomTestAdapters)); inputDataContract.ExecutionSettings.ProceedAfterAbortedTestCase = false; if (tl.getVariable('ProceedAfterAbortedTestCase') && tl.getVariable('ProceedAfterAbortedTestCase').toUpperCase() === 'TRUE') { inputDataContract.ExecutionSettings.ProceedAfterAbortedTestCase = true; } tl.debug('ProceedAfterAbortedTestCase is set to : ' + inputDataContract.ExecutionSettings.ProceedAfterAbortedTestCase); // hydra: Maybe move all warnings to a diff function if (tl.getBoolInput('uiTests') && inputDataContract.ExecutionSettings.AssemblyLevelParallelism) { tl.warning(tl.loc('uitestsparallel')); } inputDataContract.ExecutionSettings.AdditionalConsoleParameters = tl.getInput('otherConsoleOptions'); console.log(tl.loc('otherConsoleOptionsInput', inputDataContract.ExecutionSettings.AdditionalConsoleParameters)); if (serverBasedRun && inputDataContract.ExecutionSettings.AdditionalConsoleParameters) { tl.warning(tl.loc('otherConsoleOptionsNotSupported')); inputDataContract.ExecutionSettings.AdditionalConsoleParameters = null; } inputDataContract.ExecutionSettings.CodeCoverageEnabled = tl.getBoolInput('codeCoverageEnabled'); console.log(tl.loc('codeCoverageInput', inputDataContract.ExecutionSettings.CodeCoverageEnabled)); inputDataContract = getDiagnosticsSettings(inputDataContract); console.log(tl.loc('diagnosticsInput', inputDataContract.ExecutionSettings.DiagnosticsSettings.Enabled)); // Custom console wrapper settings inputDataContract.ExecutionSettings.PathToCustomVsTestConsoleWrapperAssembly = tl.getVariable('vstest.customConsoleWrapperAssemblyLocation'); inputDataContract = getTiaSettings(inputDataContract); inputDataContract = getRerunSettings(inputDataContract); return inputDataContract; } function getDiagnosticsSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { inputDataContract.ExecutionSettings.DiagnosticsSettings = <idc.DiagnosticsSettings>{}; if (enableDiagnosticsSettings) { inputDataContract.ExecutionSettings.DiagnosticsSettings.Enabled = tl.getBoolInput('diagnosticsEnabled'); inputDataContract.ExecutionSettings.DiagnosticsSettings.DumpCollectionType = tl.getInput('collectDumpOn').toLowerCase(); } else { inputDataContract.ExecutionSettings.DiagnosticsSettings.Enabled = false; } return inputDataContract; } function getTiaSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { // TIA stuff if (tl.getBoolInput('runOnlyImpactedTests') === false) { return inputDataContract; } inputDataContract.ExecutionSettings.TiaSettings = <idc.TiaSettings>{}; inputDataContract.ExecutionSettings.TiaSettings.Enabled = tl.getBoolInput('runOnlyImpactedTests'); inputDataContract.ExecutionSettings.TiaSettings.RebaseLimit = +tl.getInput('runAllTestsAfterXBuilds'); inputDataContract.ExecutionSettings.TiaSettings.FileLevel = getTIALevel(tl.getVariable('tia.filelevel')); inputDataContract.ExecutionSettings.TiaSettings.SourcesDirectory = tl.getVariable('build.sourcesdirectory'); inputDataContract.ExecutionSettings.TiaSettings.FilterPaths = tl.getVariable('TIA_IncludePathFilters'); // User map file inputDataContract.ExecutionSettings.TiaSettings.UserMapFile = tl.getVariable('tia.usermapfile'); // disable editing settings file to switch on data collector inputDataContract.ExecutionSettings.TiaSettings.DisableDataCollection = utils.Helper.stringToBool(tl.getVariable('tia.disabletiadatacollector')); // This option gives the user ability to add Fully Qualified name filters for test impact. Does not work with XUnit inputDataContract.ExecutionSettings.TiaSettings.UseTestCaseFilterInResponseFile = utils.Helper.stringToBool(tl.getVariable('tia.useTestCaseFilterInResponseFile')); // A legacy switch to disable test impact from build variables inputDataContract.ExecutionSettings.TiaSettings.Enabled = !utils.Helper.stringToBool(tl.getVariable('DisableTestImpactAnalysis')); const buildReason = tl.getVariable('Build.Reason'); // https://www.visualstudio.com/en-us/docs/build/define/variables // PullRequest -> This is the case for TfsGit PR flow // CheckInShelveset -> This is the case for TFVC Gated Checkin if (buildReason && (buildReason === 'PullRequest' || buildReason === 'CheckInShelveset')) { inputDataContract.ExecutionSettings.TiaSettings.IsPrFlow = true; } else { inputDataContract.ExecutionSettings.TiaSettings.IsPrFlow = utils.Helper.stringToBool(tl.getVariable('tia.isPrFlow')); } return inputDataContract; } function getRerunSettings(inputDataContract : idc.InputDataContract) : idc.InputDataContract { if (tl.getBoolInput('rerunFailedTests') === false) { return inputDataContract; } inputDataContract.ExecutionSettings.RerunSettings = <idc.RerunSettings>{}; inputDataContract.ExecutionSettings.RerunSettings.RerunFailedTests = tl.getBoolInput('rerunFailedTests'); console.log(tl.loc('rerunFailedTests', inputDataContract.ExecutionSettings.RerunSettings.RerunFailedTests)); const rerunType = tl.getInput('rerunType') || 'basedOnTestFailurePercentage'; inputDataContract.ExecutionSettings.RerunSettings.RerunType = rerunType; if (rerunType === 'basedOnTestFailureCount') { const rerunFailedTestCasesMaxLimit = parseInt(tl.getInput('rerunFailedTestCasesMaxLimit')); if (!isNaN(rerunFailedTestCasesMaxLimit)) { inputDataContract.ExecutionSettings.RerunSettings.RerunFailedTestCasesMaxLimit = rerunFailedTestCasesMaxLimit; console.log(tl.loc('rerunFailedTestCasesMaxLimit', inputDataContract.ExecutionSettings.RerunSettings.RerunFailedTestCasesMaxLimit)); } else { tl.warning(tl.loc('invalidRerunFailedTestCasesMaxLimit')); } } else { const rerunFailedThreshold = parseInt(tl.getInput('rerunFailedThreshold')); if (!isNaN(rerunFailedThreshold)) { inputDataContract.ExecutionSettings.RerunSettings.RerunFailedThreshold = rerunFailedThreshold; console.log(tl.loc('rerunFailedThreshold', inputDataContract.ExecutionSettings.RerunSettings.RerunFailedThreshold)); } else { tl.warning(tl.loc('invalidRerunFailedThreshold')); } } const rerunMaxAttempts = parseInt(tl.getInput('rerunMaxAttempts')); if (!isNaN(rerunMaxAttempts)) { inputDataContract.ExecutionSettings.RerunSettings.RerunMaxAttempts = rerunMaxAttempts; console.log(tl.loc('rerunMaxAttempts', inputDataContract.ExecutionSettings.RerunSettings.RerunMaxAttempts)); } else { tl.warning(tl.loc('invalidRerunMaxAttempts')); } return inputDataContract; } function getRunIdentifier(): string { let runIdentifier: string = ''; const taskInstanceId = getDtaInstanceId(); const dontDistribute = tl.getBoolInput('dontDistribute'); const releaseId = tl.getVariable('Release.ReleaseId'); const jobId = tl.getVariable('System.JobPositionInPhase'); const parallelExecution = tl.getVariable('System.ParallelExecutionType'); const phaseId = utils.Helper.isNullEmptyOrUndefined(releaseId) ? tl.getVariable('System.PhaseId') : tl.getVariable('Release.DeployPhaseId'); if ((!utils.Helper.isNullEmptyOrUndefined(parallelExecution) && parallelExecution.toLowerCase() === 'multiconfiguration') || dontDistribute) { runIdentifier = `${phaseId}/${jobId}/${taskInstanceId}`; } else { runIdentifier = `${phaseId}/${taskInstanceId}`; } return runIdentifier; } // hydra: rename function and maybe refactor and add logic inline function getTIALevel(fileLevel: string) { if (fileLevel && fileLevel.toUpperCase() === 'FALSE') { return false; } return true; } function getTestPlatformPath(inputDataContract : idc.InputDataContract) { const vsTestVersion = tl.getInput('vsTestVersion'); if (vsTestVersion.toLowerCase() === 'latest') { tl.debug('Searching for latest Visual Studio.'); let vstestconsolePath = getVSTestConsolePath('17.0', '18.0'); if (vstestconsolePath) { return path.join(vstestconsolePath, 'Common7', 'IDE', 'Extensions', 'TestPlatform'); } vstestconsolePath = getVSTestConsolePath('16.0', '17.0'); if (vstestconsolePath) { return path.join(vstestconsolePath, 'Common7', 'IDE', 'Extensions', 'TestPlatform'); } vstestconsolePath = getVSTestConsolePath('15.0', '16.0'); if (vstestconsolePath) { return path.join(vstestconsolePath, 'Common7', 'IDE', 'CommonExtensions', 'Microsoft', 'TestWindow'); } // fallback tl.debug('Unable to find an instance of Visual Studio 2017 or higher.'); tl.debug('Searching for Visual Studio 2015..'); return getVSTestLocation(14); } const vsVersion: number = parseFloat(vsTestVersion); if (vsVersion === 16.0) { const vstestconsolePath = getVSTestConsolePath('15.0', '17.0'); if (vstestconsolePath) { return path.join(vstestconsolePath, 'Common7', 'IDE', 'Extensions', 'TestPlatform'); } throw (new Error(tl.loc('VstestNotFound', utils.Helper.getVSVersion(vsVersion)))); } if (vsVersion === 15.0) { const vstestconsolePath = getVSTestConsolePath('15.0', '16.0'); if (vstestconsolePath) { return path.join(vstestconsolePath, 'Common7', 'IDE', 'CommonExtensions', 'Microsoft', 'TestWindow'); } throw (new Error(tl.loc('VstestNotFound', utils.Helper.getVSVersion(vsVersion)))); } tl.debug('Searching for Visual Studio ' + vsVersion.toString()); return getVSTestLocation(vsVersion); } function getVSTestConsolePath(versionLowerLimit : string, versionUpperLimit : string): string { let vswhereTool = tl.tool(path.join(__dirname, 'vswhere.exe')); console.log(tl.loc('LookingForVsInstalltion', `[${versionLowerLimit},${versionUpperLimit})`)); vswhereTool.line(`-version [${versionLowerLimit},${versionUpperLimit}) -latest -products * -requires Microsoft.VisualStudio.PackageGroup.TestTools.Core -property installationPath`); let vsPath = vswhereTool.execSync({ silent: true } as tr.IExecSyncOptions).stdout; vsPath = utils.Helper.trimString(vsPath); if (!utils.Helper.isNullOrWhitespace(vsPath)) { tl.debug('Visual Studio 15.0 or higher installed path: ' + vsPath); return vsPath; } // Look for build tool installation if full VS not present console.log(tl.loc('LookingForBuildToolsInstalltion', `[${versionLowerLimit},${versionUpperLimit})`)); vswhereTool = tl.tool(path.join(__dirname, 'vswhere.exe')); vswhereTool.line(`-version [${versionLowerLimit},${versionUpperLimit}) -latest -products * -requires Microsoft.VisualStudio.Component.TestTools.BuildTools -property installationPath`); vsPath = vswhereTool.execSync({ silent: true } as tr.IExecSyncOptions).stdout; vsPath = utils.Helper.trimString(vsPath); if (!utils.Helper.isNullOrWhitespace(vsPath)) { tl.debug('Build tools installed path: ' + vsPath); return vsPath; } return null; } export function getVSTestLocation(vsVersion: number): string { const vsCommon: string = tl.getVariable('VS' + vsVersion + '0COMNTools'); if (!vsCommon) { throw (new Error(tl.loc('VstestNotFound', utils.Helper.getVSVersion(vsVersion)))); } return path.join(vsCommon, '..\\IDE\\CommonExtensions\\Microsoft\\TestWindow'); } async function logWarningForWER(runUITests: boolean) { if (!runUITests) { return; } const regPathHKLM = 'HKLM\\SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting'; const regPathHKCU = 'HKCU\\SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting'; const isEnabledInHKCU = await isDontShowUIRegKeySet(regPathHKCU); const isEnabledInHKLM = await isDontShowUIRegKeySet(regPathHKLM); if (!isEnabledInHKCU && !isEnabledInHKLM) { tl.warning(tl.loc('DontShowWERUIDisabledWarning')); } } function isDontShowUIRegKeySet(regPath: string): Q.Promise<boolean> { const defer = Q.defer<boolean>(); const regValue = 'DontShowUI'; regedit.list(regPath).on('data', (entry) => { if (entry && entry.data && entry.data.values && entry.data.values[regValue] && (entry.data.values[regValue].value === 1)) { defer.resolve(true); } defer.resolve(false); }); return defer.promise; } function addResultsDirectoryToTelemetry(resultsDir: string){ if (resultsDir.startsWith(path.join(tl.getVariable('Agent.TempDirectory'), 'TestResults'))) { ci.publishTelemetry('TestExecution', 'ResultsDirectory', { 'TestResultsFolderUi': '$(Agent.TempDirectory)/TestResults' } ); } else if (resultsDir.startsWith(tl.getVariable('Agent.TempDirectory'))) { ci.publishTelemetry('TestExecution', 'ResultsDirectory', { 'TestResultsFolderUi': '$(Agent.TempDirectory)' } ); } else if (resultsDir.startsWith(tl.getVariable('Common.TestResultsDirectory'))) { ci.publishTelemetry('TestExecution', 'ResultsDirectory', { 'TestResultsFolderUi': '$(Common.TestResultsDirectory)' }) } else if (resultsDir.startsWith(tl.getVariable('System.DefaultWorkingDirectory'))) { ci.publishTelemetry('TestExecution', 'ResultsDirectory', { 'TestResultsFolderUi': '$(System.DefaultWorkingDirectory)' }) } else { ci.publishTelemetry('TestExecution', 'ResultsDirectory', { 'TestResultsFolderUi': 'Custom Directory' }) } } export function setIsServerBasedRun(isServerBasedRun: boolean) { serverBasedRun = isServerBasedRun; } export function setEnableDiagnosticsSettings(enableDiagnosticsSettingsFF: boolean) { enableDiagnosticsSettings = enableDiagnosticsSettingsFF; tl.debug('Diagnostics feature flag is set to: ' + enableDiagnosticsSettingsFF); } export function getDtaInstanceId(): number { const taskInstanceIdString = tl.getVariable('DTA_INSTANCE_ID'); let taskInstanceId: number = 1; if (taskInstanceIdString) { const instanceId: number = Number(taskInstanceIdString); if (!isNaN(instanceId)) { taskInstanceId = instanceId + 1; } } tl.setVariable('DTA_INSTANCE_ID', taskInstanceId.toString()); return taskInstanceId; }
the_stack
import { CfnIdentityPool, } from '@aws-cdk/aws-cognito'; import { IOpenIdConnectProvider, ISamlProvider, Role, FederatedPrincipal, IRole, } from '@aws-cdk/aws-iam'; import { Resource, IResource, Stack, ArnFormat, Lazy, } from '@aws-cdk/core'; import { Construct, } from 'constructs'; import { IdentityPoolRoleAttachment, IdentityPoolRoleMapping, } from './identitypool-role-attachment'; import { IUserPoolAuthenticationProvider, } from './identitypool-user-pool-authentication-provider'; /** * Represents a Cognito IdentityPool */ export interface IIdentityPool extends IResource { /** * The id of the Identity Pool in the format REGION:GUID * @attribute */ readonly identityPoolId: string; /** * The ARN of the Identity Pool * @attribute */ readonly identityPoolArn: string; /** * Name of the Identity Pool * @attribute */ readonly identityPoolName: string } /** * Props for the IdentityPool construct */ export interface IdentityPoolProps { /** * The name of the Identity Pool * @default - automatically generated name by CloudFormation at deploy time */ readonly identityPoolName?: string; /** * The Default Role to be assumed by Authenticated Users * @default - A Default Authenticated Role will be added */ readonly authenticatedRole?: IRole; /** * The Default Role to be assumed by Unauthenticated Users * @default - A Default Unauthenticated Role will be added */ readonly unauthenticatedRole?: IRole; /** * Wwhether the identity pool supports unauthenticated logins * @default - false */ readonly allowUnauthenticatedIdentities?: boolean /** * Rules for mapping roles to users * @default - no Role Mappings */ readonly roleMappings?: IdentityPoolRoleMapping[]; /** * Enables the Basic (Classic) authentication flow * @default - Classic Flow not allowed */ readonly allowClassicFlow?: boolean; /** * Authentication providers for using in identity pool. * @default - No Authentication Providers passed directly to Identity Pool */ readonly authenticationProviders?: IdentityPoolAuthenticationProviders } /** * Types of Identity Pool Login Providers */ export enum IdentityPoolProviderType { /** Facebook Provider type */ FACEBOOK = 'Facebook', /** Google Provider Type */ GOOGLE = 'Google', /** Amazon Provider Type */ AMAZON = 'Amazon', /** Apple Provider Type */ APPLE = 'Apple', /** Twitter Provider Type */ TWITTER = 'Twitter', /** Digits Provider Type */ DIGITS = 'Digits', /** Open Id Provider Type */ OPEN_ID = 'OpenId', /** Saml Provider Type */ SAML = 'Saml', /** User Pool Provider Type */ USER_POOL = 'UserPool', /** Custom Provider Type */ CUSTOM = 'Custom', } /** * Keys for Login Providers - correspond to client id's of respective federation identity providers */ export class IdentityPoolProviderUrl { /** Facebook Provider Url */ public static readonly FACEBOOK = new IdentityPoolProviderUrl(IdentityPoolProviderType.FACEBOOK, 'graph.facebook.com'); /** Google Provider Url */ public static readonly GOOGLE = new IdentityPoolProviderUrl(IdentityPoolProviderType.GOOGLE, 'accounts.google.com'); /** Amazon Provider Url */ public static readonly AMAZON = new IdentityPoolProviderUrl(IdentityPoolProviderType.AMAZON, 'www.amazon.com'); /** Apple Provider Url */ public static readonly APPLE = new IdentityPoolProviderUrl(IdentityPoolProviderType.APPLE, 'appleid.apple.com'); /** Twitter Provider Url */ public static readonly TWITTER = new IdentityPoolProviderUrl(IdentityPoolProviderType.TWITTER, 'api.twitter.com'); /** Digits Provider Url */ public static readonly DIGITS = new IdentityPoolProviderUrl(IdentityPoolProviderType.DIGITS, 'www.digits.com'); /** OpenId Provider Url */ public static openId(url: string): IdentityPoolProviderUrl { return new IdentityPoolProviderUrl(IdentityPoolProviderType.OPEN_ID, url); } /** Saml Provider Url */ public static saml(url: string): IdentityPoolProviderUrl { return new IdentityPoolProviderUrl(IdentityPoolProviderType.SAML, url); } /** User Pool Provider Url */ public static userPool(url: string): IdentityPoolProviderUrl { return new IdentityPoolProviderUrl(IdentityPoolProviderType.USER_POOL, url); } /** Custom Provider Url */ public static custom(url: string): IdentityPoolProviderUrl { return new IdentityPoolProviderUrl(IdentityPoolProviderType.CUSTOM, url); } constructor( /** type of Provider Url */ public readonly type: IdentityPoolProviderType, /** value of Provider Url */ public readonly value: string, ) {} } /** * Login Provider for Identity Federation using Amazon Credentials */ export interface IdentityPoolAmazonLoginProvider { /** * App Id for Amazon Identity Federation */ readonly appId: string } /** * Login Provider for Identity Federation using Facebook Credentials */ export interface IdentityPoolFacebookLoginProvider { /** * App Id for Facebook Identity Federation */ readonly appId: string } /** * Login Provider for Identity Federation using Apple Credentials */ export interface IdentityPoolAppleLoginProvider { /** * App Id for Apple Identity Federation */ readonly servicesId: string } /** * Login Provider for Identity Federation using Google Credentials */ export interface IdentityPoolGoogleLoginProvider { /** * App Id for Google Identity Federation */ readonly clientId: string } /** * Login Provider for Identity Federation using Twitter Credentials */ export interface IdentityPoolTwitterLoginProvider { /** * App Id for Twitter Identity Federation */ readonly consumerKey: string /** * App Secret for Twitter Identity Federation */ readonly consumerSecret: string } /** * Login Provider for Identity Federation using Digits Credentials */ export interface IdentityPoolDigitsLoginProvider extends IdentityPoolTwitterLoginProvider {} /** * External Identity Providers To Connect to User Pools and Identity Pools */ export interface IdentityPoolProviders { /** App Id for Facebook Identity Federation * @default - No Facebook Authentication Provider used without OpenIdConnect or a User Pool */ readonly facebook?: IdentityPoolFacebookLoginProvider /** Client Id for Google Identity Federation * @default - No Google Authentication Provider used without OpenIdConnect or a User Pool */ readonly google?: IdentityPoolGoogleLoginProvider /** App Id for Amazon Identity Federation * @default - No Amazon Authentication Provider used without OpenIdConnect or a User Pool */ readonly amazon?: IdentityPoolAmazonLoginProvider /** Services Id for Apple Identity Federation * @default - No Apple Authentication Provider used without OpenIdConnect or a User Pool */ readonly apple?: IdentityPoolAppleLoginProvider /** Consumer Key and Secret for Twitter Identity Federation * @default - No Twitter Authentication Provider used without OpenIdConnect or a User Pool */ readonly twitter?: IdentityPoolTwitterLoginProvider /** Consumer Key and Secret for Digits Identity Federation * @default - No Digits Authentication Provider used without OpenIdConnect or a User Pool */ readonly digits?: IdentityPoolDigitsLoginProvider } /** * Authentication providers for using in identity pool. * @see https://docs.aws.amazon.com/cognito/latest/developerguide/external-identity-providers.html */ export interface IdentityPoolAuthenticationProviders extends IdentityPoolProviders { /** * The User Pool Authentication Providers associated with this Identity Pool * @default - no User Pools Associated */ readonly userPools?: IUserPoolAuthenticationProvider[]; /** * The OpenIdConnect Provider associated with this Identity Pool * @default - no OpenIdConnectProvider */ readonly openIdConnectProviders?: IOpenIdConnectProvider[]; /** * The Security Assertion Markup Language Provider associated with this Identity Pool * @default - no SamlProvider */ readonly samlProviders?: ISamlProvider[]; /** * The Developer Provider Name to associate with this Identity Pool * @default - no Custom Provider */ readonly customProvider?: string; } /** * Define a Cognito Identity Pool * * @resource AWS::Cognito::IdentityPool */ export class IdentityPool extends Resource implements IIdentityPool { /** * Import an existing Identity Pool from its id */ public static fromIdentityPoolId(scope: Construct, id: string, identityPoolId: string): IIdentityPool { const identityPoolArn = Stack.of(scope).formatArn({ service: 'cognito-identity', resource: 'identitypool', resourceName: identityPoolId, arnFormat: ArnFormat.SLASH_RESOURCE_NAME, }); return IdentityPool.fromIdentityPoolArn(scope, id, identityPoolArn); } /** * Import an existing Identity Pool from its Arn */ public static fromIdentityPoolArn(scope: Construct, id: string, identityPoolArn: string): IIdentityPool { const pool = Stack.of(scope).splitArn(identityPoolArn, ArnFormat.SLASH_RESOURCE_NAME); const res = pool.resourceName || ''; if (!res) { throw new Error('Invalid Identity Pool ARN'); } const idParts = res.split(':'); if (!(idParts.length === 2)) throw new Error('Invalid Identity Pool Id: Identity Pool Ids must follow the format <region>:<id>'); if (idParts[0] !== pool.region) throw new Error('Invalid Identity Pool Id: Region in Identity Pool Id must match stack region'); class ImportedIdentityPool extends Resource implements IIdentityPool { public readonly identityPoolId = res; public readonly identityPoolArn = identityPoolArn; public readonly identityPoolName: string constructor() { super(scope, id, { account: pool.account, region: pool.region, }); this.identityPoolName = this.physicalName; } } return new ImportedIdentityPool(); } /** * The id of the Identity Pool in the format REGION:GUID * @attribute */ public readonly identityPoolId: string; /** * The ARN of the Identity Pool * @attribute */ public readonly identityPoolArn: string; /** * The name of the Identity Pool * @attribute */ public readonly identityPoolName: string; /** * Default role for authenticated users */ public readonly authenticatedRole: IRole; /** * Default role for unauthenticated users */ public readonly unauthenticatedRole: IRole; /** * List of Identity Providers added in constructor for use with property overrides */ private cognitoIdentityProviders: CfnIdentityPool.CognitoIdentityProviderProperty[] = []; /** * Running count of added role attachments */ private roleAttachmentCount: number = 0; constructor(scope: Construct, id: string, props:IdentityPoolProps = {}) { super(scope, id, { physicalName: props.identityPoolName, }); const authProviders: IdentityPoolAuthenticationProviders = props.authenticationProviders || {}; const providers = authProviders.userPools ? authProviders.userPools.map(userPool => userPool.bind(this, this)) : undefined; if (providers && providers.length) this.cognitoIdentityProviders = providers; const openIdConnectProviderArns = authProviders.openIdConnectProviders ? authProviders.openIdConnectProviders.map(openIdProvider => openIdProvider.openIdConnectProviderArn, ) : undefined; const samlProviderArns = authProviders.samlProviders ? authProviders.samlProviders.map(samlProvider => samlProvider.samlProviderArn, ) : undefined; let supportedLoginProviders:any = {}; if (authProviders.amazon) supportedLoginProviders[IdentityPoolProviderUrl.AMAZON.value] = authProviders.amazon.appId; if (authProviders.facebook) supportedLoginProviders[IdentityPoolProviderUrl.FACEBOOK.value] = authProviders.facebook.appId; if (authProviders.google) supportedLoginProviders[IdentityPoolProviderUrl.GOOGLE.value] = authProviders.google.clientId; if (authProviders.apple) supportedLoginProviders[IdentityPoolProviderUrl.APPLE.value] = authProviders.apple.servicesId; if (authProviders.twitter) supportedLoginProviders[IdentityPoolProviderUrl.TWITTER.value] = `${authProviders.twitter.consumerKey};${authProviders.twitter.consumerSecret}`; if (authProviders.digits) supportedLoginProviders[IdentityPoolProviderUrl.DIGITS.value] = `${authProviders.digits.consumerKey};${authProviders.digits.consumerSecret}`; if (!Object.keys(supportedLoginProviders).length) supportedLoginProviders = undefined; const cfnIdentityPool = new CfnIdentityPool(this, 'Resource', { allowUnauthenticatedIdentities: props.allowUnauthenticatedIdentities ? true : false, allowClassicFlow: props.allowClassicFlow, identityPoolName: this.physicalName, developerProviderName: authProviders.customProvider, openIdConnectProviderArns, samlProviderArns, supportedLoginProviders, cognitoIdentityProviders: Lazy.any({ produce: () => this.cognitoIdentityProviders }), }); this.identityPoolName = cfnIdentityPool.attrName; this.identityPoolId = cfnIdentityPool.ref; this.identityPoolArn = Stack.of(scope).formatArn({ service: 'cognito-identity', resource: 'identitypool', resourceName: this.identityPoolId, arnFormat: ArnFormat.SLASH_RESOURCE_NAME, }); this.authenticatedRole = props.authenticatedRole ? props.authenticatedRole : this.configureDefaultRole('Authenticated'); this.unauthenticatedRole = props.unauthenticatedRole ? props.unauthenticatedRole : this.configureDefaultRole('Unauthenticated'); const attachment = new IdentityPoolRoleAttachment(this, 'DefaultRoleAttachment', { identityPool: this, authenticatedRole: this.authenticatedRole, unauthenticatedRole: this.unauthenticatedRole, roleMappings: props.roleMappings, }); // This added by the original author, but it's causing cyclic dependencies. // Don't know why this was added in the first place, but I'm disabling it for now and if // no complaints come from this, we're probably safe to remove it altogether. // attachment.node.addDependency(this); Array.isArray(attachment); } /** * Add a User Pool to the IdentityPool and configure User Pool Client to handle identities */ public addUserPoolAuthentication(userPool: IUserPoolAuthenticationProvider): void { const providers = userPool.bind(this, this); this.cognitoIdentityProviders = this.cognitoIdentityProviders.concat(providers); } /** * Adds Role Mappings to Identity Pool */ public addRoleMappings(...roleMappings: IdentityPoolRoleMapping[]): void { if (!roleMappings || !roleMappings.length) return; this.roleAttachmentCount++; const name = 'RoleMappingAttachment' + this.roleAttachmentCount.toString(); const attachment = new IdentityPoolRoleAttachment(this, name, { identityPool: this, authenticatedRole: this.authenticatedRole, unauthenticatedRole: this.unauthenticatedRole, roleMappings, }); // This added by the original author, but it's causing cyclic dependencies. // Don't know why this was added in the first place, but I'm disabling it for now and if // no complaints come from this, we're probably safe to remove it altogether. // attachment.node.addDependency(this); Array.isArray(attachment); } /** * Configure Default Roles For Identity Pool */ private configureDefaultRole(type: string): IRole { const assumedBy = this.configureDefaultGrantPrincipal(type.toLowerCase()); const role = new Role(this, `${type}Role`, { description: `Default ${type} Role for Identity Pool ${this.identityPoolName}`, assumedBy, }); return role; } private configureDefaultGrantPrincipal(type: string) { return new FederatedPrincipal('cognito-identity.amazonaws.com', { 'StringEquals': { 'cognito-identity.amazonaws.com:aud': this.identityPoolId, }, 'ForAnyValue:StringLike': { 'cognito-identity.amazonaws.com:amr': type, }, }, 'sts:AssumeRoleWithWebIdentity'); } }
the_stack
import { getSerdePlugin } from "@aws-sdk/middleware-serde"; import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@aws-sdk/protocol-http"; import { Command as $Command } from "@aws-sdk/smithy-client"; import { FinalizeHandlerArguments, Handler, HandlerExecutionContext, HttpHandlerOptions as __HttpHandlerOptions, MetadataBearer as __MetadataBearer, MiddlewareStack, SerdeContext as __SerdeContext, } from "@aws-sdk/types"; import { CreateGovCloudAccountRequest, CreateGovCloudAccountResponse } from "../models/models_0"; import { OrganizationsClientResolvedConfig, ServiceInputTypes, ServiceOutputTypes } from "../OrganizationsClient"; import { deserializeAws_json1_1CreateGovCloudAccountCommand, serializeAws_json1_1CreateGovCloudAccountCommand, } from "../protocols/Aws_json1_1"; export interface CreateGovCloudAccountCommandInput extends CreateGovCloudAccountRequest {} export interface CreateGovCloudAccountCommandOutput extends CreateGovCloudAccountResponse, __MetadataBearer {} /** * <p>This action is available if all of the following are true:</p> * <ul> * <li> * <p>You're authorized to create accounts in the AWS GovCloud (US) Region. For * more information on the AWS GovCloud (US) Region, see the <a href="http://docs.aws.amazon.com/govcloud-us/latest/UserGuide/welcome.html"> * <i>AWS GovCloud User Guide</i>.</a> * </p> * </li> * <li> * <p>You already have an account in the AWS GovCloud (US) Region that is paired * with a management account of an organization in the commercial Region.</p> * </li> * <li> * <p>You call this action from the management account of your organization in the * commercial Region.</p> * </li> * <li> * <p>You have the <code>organizations:CreateGovCloudAccount</code> permission. * </p> * </li> * </ul> * <p>AWS Organizations automatically creates the required service-linked role named * <code>AWSServiceRoleForOrganizations</code>. For more information, see <a href="http://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services.html#orgs_integrate_services-using_slrs">AWS Organizations and Service-Linked Roles</a> in the * <i>AWS Organizations User Guide.</i> * </p> * <p>AWS automatically enables AWS CloudTrail for AWS GovCloud (US) accounts, but you should also * do the following:</p> * <ul> * <li> * <p>Verify that AWS CloudTrail is enabled to store logs.</p> * </li> * <li> * <p>Create an S3 bucket for AWS CloudTrail log storage.</p> * <p>For more information, see <a href="http://docs.aws.amazon.com/govcloud-us/latest/UserGuide/verifying-cloudtrail.html">Verifying AWS CloudTrail Is * Enabled</a> in the <i>AWS GovCloud User Guide</i>. * </p> * </li> * </ul> * <p>If the request includes tags, then the requester must have the * <code>organizations:TagResource</code> permission. The tags are attached to the * commercial account associated with the GovCloud account, rather than the GovCloud * account itself. To add tags to the GovCloud account, call the <a>TagResource</a> operation in the GovCloud Region after the new GovCloud * account exists.</p> * <p>You call this action from the management account of your organization in the * commercial Region to create a standalone AWS account in the AWS GovCloud (US) * Region. After the account is created, the management account of an organization in the * AWS GovCloud (US) Region can invite it to that organization. For more information on * inviting standalone accounts in the AWS GovCloud (US) to join an organization, see * <a href="http://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-organizations.html">AWS Organizations</a> in * the <i>AWS GovCloud User Guide.</i> * </p> * <p>Calling <code>CreateGovCloudAccount</code> is an asynchronous request that AWS * performs in the background. Because <code>CreateGovCloudAccount</code> operates * asynchronously, it can return a successful completion message even though account * initialization might still be in progress. You might need to wait a few minutes before * you can successfully access the account. To check the status of the request, do one of * the following:</p> * <ul> * <li> * <p>Use the <code>OperationId</code> response element from this operation to * provide as a parameter to the <a>DescribeCreateAccountStatus</a> * operation.</p> * </li> * <li> * <p>Check the AWS CloudTrail log for the <code>CreateAccountResult</code> event. For * information on using AWS CloudTrail with Organizations, see <a href="http://docs.aws.amazon.com/organizations/latest/userguide/orgs_monitoring.html">Monitoring the Activity in Your * Organization</a> in the <i>AWS Organizations User Guide.</i> * </p> * </li> * </ul> * <p></p> * <p>When you call the <code>CreateGovCloudAccount</code> action, you create two accounts: * a standalone account in the AWS GovCloud (US) Region and an associated account in the * commercial Region for billing and support purposes. The account in the commercial Region * is automatically a member of the organization whose credentials made the request. Both * accounts are associated with the same email address.</p> * <p>A role is created in the new account in the commercial Region that allows the * management account in the organization in the commercial Region to assume it. An AWS * GovCloud (US) account is then created and associated with the commercial account that * you just created. A role is also created in the new AWS GovCloud (US) account that can * be assumed by the AWS GovCloud (US) account that is associated with the management * account of the commercial organization. For more information and to view a diagram that * explains how account access works, see <a href="http://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-organizations.html">AWS Organizations</a> in the * <i>AWS GovCloud User Guide.</i> * </p> * * * <p>For more information about creating accounts, see <a href="https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_create.html">Creating * an AWS Account in Your Organization</a> in the * <i>AWS Organizations User Guide.</i> * </p> * <important> * <ul> * <li> * <p>When you create an account in an organization using the AWS Organizations console, * API, or CLI commands, the information required for the account to operate as * a standalone account is <i>not</i> automatically collected. * This includes a payment method and signing the end user license agreement * (EULA). If you must remove an account from your organization later, you can * do so only after you provide the missing information. Follow the steps at * <a href="http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info"> To leave an organization as a member account</a> in the * <i>AWS Organizations User Guide.</i> * </p> * </li> * <li> * <p>If you get an exception that indicates that you exceeded your account * limits for the organization, contact <a href="https://console.aws.amazon.com/support/home#/">AWS Support</a>.</p> * </li> * <li> * <p>If you get an exception that indicates that the operation failed because * your organization is still initializing, wait one hour and then try again. * If the error persists, contact <a href="https://console.aws.amazon.com/support/home#/">AWS * Support</a>.</p> * </li> * <li> * <p>Using <code>CreateGovCloudAccount</code> to create multiple temporary * accounts isn't recommended. You can only close an account from the AWS * Billing and Cost Management console, and you must be signed in as the root * user. For information on the requirements and process for closing an * account, see <a href="http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_close.html">Closing an AWS Account</a> in the * <i>AWS Organizations User Guide</i>.</p> * </li> * </ul> * </important> * <note> * <p>When you create a member account with this operation, you can choose whether to * create the account with the <b>IAM User and Role Access to * Billing Information</b> switch enabled. If you enable it, IAM users and * roles that have appropriate permissions can view billing information for the * account. If you disable it, only the account root user can access billing * information. For information about how to disable this switch for an account, see * <a href="https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/grantaccess.html">Granting * Access to Your Billing Information and Tools</a>.</p> * </note> * @example * Use a bare-bones client and the command you need to make an API call. * ```javascript * import { OrganizationsClient, CreateGovCloudAccountCommand } from "@aws-sdk/client-organizations"; // ES Modules import * // const { OrganizationsClient, CreateGovCloudAccountCommand } = require("@aws-sdk/client-organizations"); // CommonJS import * const client = new OrganizationsClient(config); * const command = new CreateGovCloudAccountCommand(input); * const response = await client.send(command); * ``` * * @see {@link CreateGovCloudAccountCommandInput} for command's `input` shape. * @see {@link CreateGovCloudAccountCommandOutput} for command's `response` shape. * @see {@link OrganizationsClientResolvedConfig | config} for command's `input` shape. * */ export class CreateGovCloudAccountCommand extends $Command< CreateGovCloudAccountCommandInput, CreateGovCloudAccountCommandOutput, OrganizationsClientResolvedConfig > { // Start section: command_properties // End section: command_properties constructor(readonly input: CreateGovCloudAccountCommandInput) { // Start section: command_constructor super(); // End section: command_constructor } /** * @internal */ resolveMiddleware( clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>, configuration: OrganizationsClientResolvedConfig, options?: __HttpHandlerOptions ): Handler<CreateGovCloudAccountCommandInput, CreateGovCloudAccountCommandOutput> { this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "OrganizationsClient"; const commandName = "CreateGovCloudAccountCommand"; const handlerExecutionContext: HandlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: CreateGovCloudAccountRequest.filterSensitiveLog, outputFilterSensitiveLog: CreateGovCloudAccountResponse.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve( (request: FinalizeHandlerArguments<any>) => requestHandler.handle(request.request as __HttpRequest, options || {}), handlerExecutionContext ); } private serialize(input: CreateGovCloudAccountCommandInput, context: __SerdeContext): Promise<__HttpRequest> { return serializeAws_json1_1CreateGovCloudAccountCommand(input, context); } private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<CreateGovCloudAccountCommandOutput> { return deserializeAws_json1_1CreateGovCloudAccountCommand(output, context); } // Start section: command_body_extra // End section: command_body_extra }
the_stack
module Fayde.Data { export interface IPropertyPathWalkerListener { IsBrokenChanged(); ValueChanged(); } export interface IPropertyPathNode { Next: IPropertyPathNode; Value: any; IsBroken: boolean; ValueType: IType; GetSource(): any; SetSource(source: any); SetValue(value: any); Listen(listener: IPropertyPathNodeListener); Unlisten(listener: IPropertyPathNodeListener); } export interface ICollectionViewNode extends IPropertyPathNode { BindToView: boolean; } export interface IPropertyPathNodeListener { IsBrokenChanged(node: IPropertyPathNode); ValueChanged(node: IPropertyPathNode); } export class PropertyPathWalker implements IPropertyPathNodeListener { Path: string; IsDataContextBound: boolean; Source: any; ValueInternal: any; Node: IPropertyPathNode; FinalNode: IPropertyPathNode; private _Listener: IPropertyPathWalkerListener; get IsPathBroken (): boolean { var path = this.Path; if (this.IsDataContextBound && (!path || path.length < 1)) return false; var node = this.Node; while (node) { if (node.IsBroken) return true; node = node.Next; } return false; } get FinalPropertyName (): string { var final = <StandardPropertyPathNode>this.FinalNode; if (final instanceof StandardPropertyPathNode) return final.PropertyInfo ? final.PropertyInfo.name : ""; var lastName = ""; for (var cur = this.Node; cur; cur = cur.Next) { if (cur instanceof StandardPropertyPathNode) lastName = (<StandardPropertyPathNode>cur).PropertyInfo ? (<StandardPropertyPathNode>cur).PropertyInfo.name : ""; } return lastName; } constructor (path: string, bindDirectlyToSource?: boolean, bindsToView?: boolean, isDataContextBound?: boolean) { bindDirectlyToSource = bindDirectlyToSource !== false; bindsToView = bindsToView === true; this.IsDataContextBound = isDataContextBound === true; this.Path = path; this.IsDataContextBound = isDataContextBound; var lastCVNode: ICollectionViewNode = null; if (!path || path === ".") { lastCVNode = new CollectionViewNode(bindDirectlyToSource, bindsToView); this.Node = lastCVNode; this.FinalNode = lastCVNode; } else { var data: IPropertyPathParserData = { typeName: undefined, propertyName: undefined, index: undefined }; var type: PropertyNodeType; var parser = new PropertyPathParser(path); while ((type = parser.Step(data)) !== PropertyNodeType.None) { var isViewProperty = false; //boolean isViewProperty = CollectionViewProperties.Any (prop => prop.Name == propertyName); // static readonly PropertyInfo[] CollectionViewProperties = typeof (ICollectionView).GetProperties (); var node = lastCVNode = new CollectionViewNode(bindDirectlyToSource, isViewProperty); switch (type) { case PropertyNodeType.AttachedProperty: case PropertyNodeType.Property: node.Next = new StandardPropertyPathNode(data.typeName, data.propertyName); break; case PropertyNodeType.Indexed: node.Next = new IndexedPropertyPathNode(data.index); break; default: break; } if (this.FinalNode) this.FinalNode.Next = node; else this.Node = node; this.FinalNode = node.Next; } } lastCVNode.BindToView = lastCVNode.BindToView || bindsToView; this.FinalNode.Listen(this); } GetValue (item: any) { this.Update(item); var o = this.FinalNode.Value; return o; } Update (source: any) { this.Source = source; this.Node.SetSource(source); } Listen (listener: IPropertyPathWalkerListener) { this._Listener = listener; } Unlisten (listener: IPropertyPathWalkerListener) { if (this._Listener === listener) this._Listener = null; } IsBrokenChanged (node: IPropertyPathNode) { this.ValueInternal = node.Value; var listener = this._Listener; if (listener) listener.IsBrokenChanged(); } ValueChanged (node: IPropertyPathNode) { this.ValueInternal = node.Value; var listener = this._Listener; if (listener) listener.ValueChanged(); } GetContext (): any { var context: IPropertyPathNode = null; var cur = this.Node; var final = this.FinalNode; while (cur && cur !== final) { context = cur; cur = cur.Next; } if (!context) return undefined; return context.Value; } } class PropertyPathNode implements IPropertyPathNode { Next: IPropertyPathNode; _IsBroken: boolean; _Source: any; private _Value: any; DependencyProperty: DependencyProperty; PropertyInfo: any; private _NodeListener: IPropertyPathNodeListener; ValueType: IType; get IsBroken (): boolean { return this._IsBroken; } get Source (): any { return this._Source; } get Value (): any { return this._Value; } Listen (listener: IPropertyPathNodeListener) { this._NodeListener = listener; } Unlisten (listener: IPropertyPathNodeListener) { if (this._NodeListener === listener) this._NodeListener = null; } OnSourceChanged (oldSource, newSource) { } OnSourcePropertyChanged (o, e) { } UpdateValue () { throw new Exception("No override for abstract method: PropertyPathNode.UpdateValue"); } SetValue (value: any) { throw new Exception("No override for abstract method: PropertyPathNode.SetValue"); } GetSource (): any { return this._Source; } SetSource (value: any) { if (value == null || value !== this._Source) { var oldSource = this._Source; var npc = INotifyPropertyChanged_.as(oldSource); if (npc) npc.PropertyChanged.off(this.OnSourcePropertyChanged, this); this._Source = value; npc = INotifyPropertyChanged_.as(this._Source); if (npc) npc.PropertyChanged.on(this.OnSourcePropertyChanged, this); this.OnSourceChanged(oldSource, this._Source); this.UpdateValue(); if (this.Next) this.Next.SetSource(this._Value); } } UpdateValueAndIsBroken (newValue: any, isBroken: boolean) { var emitBrokenChanged = this._IsBroken !== isBroken; var emitValueChanged = !nullstone.equals(this.Value, newValue); this._IsBroken = isBroken; this._Value = newValue; if (emitValueChanged) { var listener = this._NodeListener; if (listener) listener.ValueChanged(this); } else if (emitBrokenChanged) { var listener = this._NodeListener; if (listener) listener.IsBrokenChanged(this); } } _CheckIsBroken (): boolean { return !this.Source || (!this.PropertyInfo && !this.DependencyProperty); } } class StandardPropertyPathNode extends PropertyPathNode { private _STypeName: string; private _PropertyName: string; PropertyInfo: nullstone.IPropertyInfo; private _DPListener: Providers.IPropertyChangedListener; constructor (typeName: string, propertyName: string) { super(); this._STypeName = typeName; this._PropertyName = propertyName; } SetValue (value: any) { if (this.DependencyProperty) (<DependencyObject>this.Source).SetValue(this.DependencyProperty, value); else if (this.PropertyInfo) this.PropertyInfo.setValue(this.Source, value); } UpdateValue () { if (this.DependencyProperty) { this.ValueType = this.DependencyProperty.GetTargetType(); this.UpdateValueAndIsBroken((<DependencyObject>this.Source).GetValue(this.DependencyProperty), this._CheckIsBroken()); } else if (this.PropertyInfo) { //TODO: this.ValueType = PropertyInfo.PropertyType; this.ValueType = null; try { this.UpdateValueAndIsBroken(this.PropertyInfo.getValue(this.Source), this._CheckIsBroken()); } catch (err) { this.UpdateValueAndIsBroken(null, this._CheckIsBroken()); } } else { this.ValueType = null; this.UpdateValueAndIsBroken(null, this._CheckIsBroken()); } } OnSourceChanged (oldSource: any, newSource: any) { super.OnSourceChanged(oldSource, newSource); var oldDO: DependencyObject; var newDO: DependencyObject; if (oldSource instanceof DependencyObject) oldDO = <DependencyObject>oldSource; if (newSource instanceof DependencyObject) newDO = <DependencyObject>newSource; var listener = this._DPListener; if (listener) { listener.Detach(); this._DPListener = listener = null; } this.DependencyProperty = null; this.PropertyInfo = null; if (!this.Source) return; var type = this.Source.constructor; var typeName = this._STypeName; if (typeName) { if (typeName.indexOf(":") > -1) console.warn("[Not supported] Cannot resolve type name outside of default namespace.", typeName); var oresolve = { type: undefined, isPrimitive: false }; if (CoreLibrary.resolveType(null, typeName, oresolve)) type = oresolve.type; } if (newDO) { var propd = DependencyProperty.GetDependencyProperty(type, this._PropertyName, true); if (propd) { this.DependencyProperty = propd; this._DPListener = listener = propd.Store.ListenToChanged(newDO, propd, this.OnPropertyChanged, this); } } if (!this.DependencyProperty || !this.DependencyProperty.IsAttached) { this.PropertyInfo = nullstone.PropertyInfo.find(this.Source, this._PropertyName); } } OnPropertyChanged (sender, args: IDependencyPropertyChangedEventArgs) { try { this.UpdateValue(); if (this.Next) this.Next.SetSource(this.Value); } catch (err) { //Ignore } } OnSourcePropertyChanged (sender, e) { if (e.PropertyName === this._PropertyName && this.PropertyInfo) { this.UpdateValue(); var next = this.Next; if (next) next.SetSource(this.Value); } } } class CollectionViewNode extends PropertyPathNode implements ICollectionViewNode { BindsDirectlyToSource: boolean; BindToView: boolean; private _ViewPropertyListener: Providers.IPropertyChangedListener; private _View: ICollectionView; constructor (bindsDirectlyToSource: boolean, bindToView: boolean) { super(); this.BindsDirectlyToSource = bindsDirectlyToSource === true; this.BindToView = bindToView === true; } OnSourceChanged (oldSource: any, newSource: any) { super.OnSourceChanged(oldSource, newSource); this.DisconnectViewHandlers(); this.ConnectViewHandlers(newSource, newSource); } ViewChanged (sender: any, e: IDependencyPropertyChangedEventArgs) { this.DisconnectViewHandlers(true); this.ConnectViewHandlers(null, e.NewValue); this.ViewCurrentChanged(this, null); } ViewCurrentChanged (sender: any, e: nullstone.IEventArgs) { this.UpdateValue(); if (this.Next) this.Next.SetSource(this.Value); } SetValue () { throw new NotSupportedException("SetValue"); } UpdateValue () { var src = this.Source; if (!this.BindsDirectlyToSource) { var view: ICollectionView; if (src instanceof CollectionViewSource) src = view = src.View; else view = ICollectionView_.as(src); if (view && !this.BindToView) src = view.CurrentItem; } this.ValueType = src == null ? null : src.constructor; this.UpdateValueAndIsBroken(src, this._CheckIsBroken()); } _CheckIsBroken (): boolean { return this.Source == null; } ConnectViewHandlers (source: CollectionViewSource, view: ICollectionView) { if (source instanceof CollectionViewSource) { this._ViewPropertyListener = CollectionViewSource.ViewProperty.Store.ListenToChanged(source, CollectionViewSource.ViewProperty, this.ViewChanged, this); view = source.View; } this._View = ICollectionView_.as(view); if (this._View) this._View.CurrentChanged.on(this.ViewCurrentChanged, this); } DisconnectViewHandlers (onlyView?: boolean) { if (!onlyView) onlyView = false; if (this._ViewPropertyListener && !onlyView) { this._ViewPropertyListener.Detach(); this._ViewPropertyListener = null; } if (this._View) { this._View.CurrentChanged.off(this.ViewCurrentChanged, this); } } } class IndexedPropertyPathNode extends PropertyPathNode { Index: number; _Source: any; _IsBroken: boolean; PropertyInfo: nullstone.IndexedPropertyInfo; constructor (index: any) { super(); this._IsBroken = false; var val = parseInt(index, 10); if (!isNaN(val)) index = val; Object.defineProperty(this, "Index", {value: index, writable: false}); } UpdateValue () { if (this.PropertyInfo == null) { this._IsBroken = true; this.ValueType = null; this.UpdateValueAndIsBroken(null, this._IsBroken); return; } try { var newVal = this.PropertyInfo.getValue(this.Source, this.Index); this._IsBroken = false; this.ValueType = this.PropertyInfo.propertyType; this.UpdateValueAndIsBroken(newVal, this._IsBroken); } catch (err) { this._IsBroken = true; this.ValueType = null; this.UpdateValueAndIsBroken(null, this._IsBroken); } } SetValue (value: any) { if (this.PropertyInfo) this.PropertyInfo.setValue(this.Source, this.Index, value); } _CheckIsBroken (): boolean { return this._IsBroken || super._CheckIsBroken(); } OnSourcePropertyChanged (o, e) { this.UpdateValue(); if (this.Next != null) this.Next.SetSource(this.Value); } OnSourceChanged (oldSource: any, newSource: any) { super.OnSourceChanged(oldSource, newSource); var cc = Collections.INotifyCollectionChanged_.as(oldSource); if (cc) cc.CollectionChanged.off(this.CollectionChanged, this); cc = Collections.INotifyCollectionChanged_.as(newSource); if (cc) cc.CollectionChanged.on(this.CollectionChanged, this); this._GetIndexer(); } private _GetIndexer () { this.PropertyInfo = null; if (this._Source != null) { this.PropertyInfo = nullstone.IndexedPropertyInfo.find(this._Source); } } CollectionChanged (o, e) { this.UpdateValue(); if (this.Next) this.Next.SetSource(this.Value); } } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config'; interface Blob {} declare class WorkSpaces extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: WorkSpaces.Types.ClientConfiguration) config: Config & WorkSpaces.Types.ClientConfiguration; /** * Creates tags for a WorkSpace. */ createTags(params: WorkSpaces.Types.CreateTagsRequest, callback?: (err: AWSError, data: WorkSpaces.Types.CreateTagsResult) => void): Request<WorkSpaces.Types.CreateTagsResult, AWSError>; /** * Creates tags for a WorkSpace. */ createTags(callback?: (err: AWSError, data: WorkSpaces.Types.CreateTagsResult) => void): Request<WorkSpaces.Types.CreateTagsResult, AWSError>; /** * Creates one or more WorkSpaces. This operation is asynchronous and returns before the WorkSpaces are created. */ createWorkspaces(params: WorkSpaces.Types.CreateWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.CreateWorkspacesResult) => void): Request<WorkSpaces.Types.CreateWorkspacesResult, AWSError>; /** * Creates one or more WorkSpaces. This operation is asynchronous and returns before the WorkSpaces are created. */ createWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.CreateWorkspacesResult) => void): Request<WorkSpaces.Types.CreateWorkspacesResult, AWSError>; /** * Deletes tags from a WorkSpace. */ deleteTags(params: WorkSpaces.Types.DeleteTagsRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DeleteTagsResult) => void): Request<WorkSpaces.Types.DeleteTagsResult, AWSError>; /** * Deletes tags from a WorkSpace. */ deleteTags(callback?: (err: AWSError, data: WorkSpaces.Types.DeleteTagsResult) => void): Request<WorkSpaces.Types.DeleteTagsResult, AWSError>; /** * Describes tags for a WorkSpace. */ describeTags(params: WorkSpaces.Types.DescribeTagsRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeTagsResult) => void): Request<WorkSpaces.Types.DescribeTagsResult, AWSError>; /** * Describes tags for a WorkSpace. */ describeTags(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeTagsResult) => void): Request<WorkSpaces.Types.DescribeTagsResult, AWSError>; /** * Obtains information about the WorkSpace bundles that are available to your account in the specified region. You can filter the results with either the BundleIds parameter, or the Owner parameter, but not both. This operation supports pagination with the use of the NextToken request and response parameters. If more results are available, the NextToken response member contains a token that you pass in the next call to this operation to retrieve the next set of items. */ describeWorkspaceBundles(params: WorkSpaces.Types.DescribeWorkspaceBundlesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspaceBundlesResult) => void): Request<WorkSpaces.Types.DescribeWorkspaceBundlesResult, AWSError>; /** * Obtains information about the WorkSpace bundles that are available to your account in the specified region. You can filter the results with either the BundleIds parameter, or the Owner parameter, but not both. This operation supports pagination with the use of the NextToken request and response parameters. If more results are available, the NextToken response member contains a token that you pass in the next call to this operation to retrieve the next set of items. */ describeWorkspaceBundles(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspaceBundlesResult) => void): Request<WorkSpaces.Types.DescribeWorkspaceBundlesResult, AWSError>; /** * Retrieves information about the AWS Directory Service directories in the region that are registered with Amazon WorkSpaces and are available to your account. This operation supports pagination with the use of the NextToken request and response parameters. If more results are available, the NextToken response member contains a token that you pass in the next call to this operation to retrieve the next set of items. */ describeWorkspaceDirectories(params: WorkSpaces.Types.DescribeWorkspaceDirectoriesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspaceDirectoriesResult) => void): Request<WorkSpaces.Types.DescribeWorkspaceDirectoriesResult, AWSError>; /** * Retrieves information about the AWS Directory Service directories in the region that are registered with Amazon WorkSpaces and are available to your account. This operation supports pagination with the use of the NextToken request and response parameters. If more results are available, the NextToken response member contains a token that you pass in the next call to this operation to retrieve the next set of items. */ describeWorkspaceDirectories(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspaceDirectoriesResult) => void): Request<WorkSpaces.Types.DescribeWorkspaceDirectoriesResult, AWSError>; /** * Obtains information about the specified WorkSpaces. Only one of the filter parameters, such as BundleId, DirectoryId, or WorkspaceIds, can be specified at a time. This operation supports pagination with the use of the NextToken request and response parameters. If more results are available, the NextToken response member contains a token that you pass in the next call to this operation to retrieve the next set of items. */ describeWorkspaces(params: WorkSpaces.Types.DescribeWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspacesResult) => void): Request<WorkSpaces.Types.DescribeWorkspacesResult, AWSError>; /** * Obtains information about the specified WorkSpaces. Only one of the filter parameters, such as BundleId, DirectoryId, or WorkspaceIds, can be specified at a time. This operation supports pagination with the use of the NextToken request and response parameters. If more results are available, the NextToken response member contains a token that you pass in the next call to this operation to retrieve the next set of items. */ describeWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspacesResult) => void): Request<WorkSpaces.Types.DescribeWorkspacesResult, AWSError>; /** * Describes the connection status of a specified WorkSpace. */ describeWorkspacesConnectionStatus(params: WorkSpaces.Types.DescribeWorkspacesConnectionStatusRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspacesConnectionStatusResult) => void): Request<WorkSpaces.Types.DescribeWorkspacesConnectionStatusResult, AWSError>; /** * Describes the connection status of a specified WorkSpace. */ describeWorkspacesConnectionStatus(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspacesConnectionStatusResult) => void): Request<WorkSpaces.Types.DescribeWorkspacesConnectionStatusResult, AWSError>; /** * Modifies the WorkSpace properties, including the RunningMode and AutoStop time. */ modifyWorkspaceProperties(params: WorkSpaces.Types.ModifyWorkspacePropertiesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.ModifyWorkspacePropertiesResult) => void): Request<WorkSpaces.Types.ModifyWorkspacePropertiesResult, AWSError>; /** * Modifies the WorkSpace properties, including the RunningMode and AutoStop time. */ modifyWorkspaceProperties(callback?: (err: AWSError, data: WorkSpaces.Types.ModifyWorkspacePropertiesResult) => void): Request<WorkSpaces.Types.ModifyWorkspacePropertiesResult, AWSError>; /** * Reboots the specified WorkSpaces. To be able to reboot a WorkSpace, the WorkSpace must have a State of AVAILABLE, IMPAIRED, or INOPERABLE. This operation is asynchronous and returns before the WorkSpaces have rebooted. */ rebootWorkspaces(params: WorkSpaces.Types.RebootWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.RebootWorkspacesResult) => void): Request<WorkSpaces.Types.RebootWorkspacesResult, AWSError>; /** * Reboots the specified WorkSpaces. To be able to reboot a WorkSpace, the WorkSpace must have a State of AVAILABLE, IMPAIRED, or INOPERABLE. This operation is asynchronous and returns before the WorkSpaces have rebooted. */ rebootWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.RebootWorkspacesResult) => void): Request<WorkSpaces.Types.RebootWorkspacesResult, AWSError>; /** * Rebuilds the specified WorkSpaces. Rebuilding a WorkSpace is a potentially destructive action that can result in the loss of data. Rebuilding a WorkSpace causes the following to occur: The system is restored to the image of the bundle that the WorkSpace is created from. Any applications that have been installed, or system settings that have been made since the WorkSpace was created will be lost. The data drive (D drive) is re-created from the last automatic snapshot taken of the data drive. The current contents of the data drive are overwritten. Automatic snapshots of the data drive are taken every 12 hours, so the snapshot can be as much as 12 hours old. To be able to rebuild a WorkSpace, the WorkSpace must have a State of AVAILABLE or ERROR. This operation is asynchronous and returns before the WorkSpaces have been completely rebuilt. */ rebuildWorkspaces(params: WorkSpaces.Types.RebuildWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.RebuildWorkspacesResult) => void): Request<WorkSpaces.Types.RebuildWorkspacesResult, AWSError>; /** * Rebuilds the specified WorkSpaces. Rebuilding a WorkSpace is a potentially destructive action that can result in the loss of data. Rebuilding a WorkSpace causes the following to occur: The system is restored to the image of the bundle that the WorkSpace is created from. Any applications that have been installed, or system settings that have been made since the WorkSpace was created will be lost. The data drive (D drive) is re-created from the last automatic snapshot taken of the data drive. The current contents of the data drive are overwritten. Automatic snapshots of the data drive are taken every 12 hours, so the snapshot can be as much as 12 hours old. To be able to rebuild a WorkSpace, the WorkSpace must have a State of AVAILABLE or ERROR. This operation is asynchronous and returns before the WorkSpaces have been completely rebuilt. */ rebuildWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.RebuildWorkspacesResult) => void): Request<WorkSpaces.Types.RebuildWorkspacesResult, AWSError>; /** * Starts the specified WorkSpaces. The API only works with WorkSpaces that have RunningMode configured as AutoStop and the State set to “STOPPED.” */ startWorkspaces(params: WorkSpaces.Types.StartWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.StartWorkspacesResult) => void): Request<WorkSpaces.Types.StartWorkspacesResult, AWSError>; /** * Starts the specified WorkSpaces. The API only works with WorkSpaces that have RunningMode configured as AutoStop and the State set to “STOPPED.” */ startWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.StartWorkspacesResult) => void): Request<WorkSpaces.Types.StartWorkspacesResult, AWSError>; /** * Stops the specified WorkSpaces. The API only works with WorkSpaces that have RunningMode configured as AutoStop and the State set to AVAILABLE, IMPAIRED, UNHEALTHY, or ERROR. */ stopWorkspaces(params: WorkSpaces.Types.StopWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.StopWorkspacesResult) => void): Request<WorkSpaces.Types.StopWorkspacesResult, AWSError>; /** * Stops the specified WorkSpaces. The API only works with WorkSpaces that have RunningMode configured as AutoStop and the State set to AVAILABLE, IMPAIRED, UNHEALTHY, or ERROR. */ stopWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.StopWorkspacesResult) => void): Request<WorkSpaces.Types.StopWorkspacesResult, AWSError>; /** * Terminates the specified WorkSpaces. Terminating a WorkSpace is a permanent action and cannot be undone. The user's data is not maintained and will be destroyed. If you need to archive any user data, contact Amazon Web Services before terminating the WorkSpace. You can terminate a WorkSpace that is in any state except SUSPENDED. This operation is asynchronous and returns before the WorkSpaces have been completely terminated. */ terminateWorkspaces(params: WorkSpaces.Types.TerminateWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.TerminateWorkspacesResult) => void): Request<WorkSpaces.Types.TerminateWorkspacesResult, AWSError>; /** * Terminates the specified WorkSpaces. Terminating a WorkSpace is a permanent action and cannot be undone. The user's data is not maintained and will be destroyed. If you need to archive any user data, contact Amazon Web Services before terminating the WorkSpace. You can terminate a WorkSpace that is in any state except SUSPENDED. This operation is asynchronous and returns before the WorkSpaces have been completely terminated. */ terminateWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.TerminateWorkspacesResult) => void): Request<WorkSpaces.Types.TerminateWorkspacesResult, AWSError>; } declare namespace WorkSpaces { export type ARN = string; export type Alias = string; export type BooleanObject = boolean; export type BundleId = string; export type BundleIdList = BundleId[]; export type BundleList = WorkspaceBundle[]; export type BundleOwner = string; export type Compute = "VALUE"|"STANDARD"|"PERFORMANCE"|string; export interface ComputeType { /** * The name of the compute type for the bundle. */ Name?: Compute; } export type ComputerName = string; export type ConnectionState = "CONNECTED"|"DISCONNECTED"|"UNKNOWN"|string; export interface CreateTagsRequest { /** * The resource ID of the request. */ ResourceId: NonEmptyString; /** * The tags of the request. */ Tags: TagList; } export interface CreateTagsResult { } export interface CreateWorkspacesRequest { /** * An array of structures that specify the WorkSpaces to create. */ Workspaces: WorkspaceRequestList; } export interface CreateWorkspacesResult { /** * An array of structures that represent the WorkSpaces that could not be created. */ FailedRequests?: FailedCreateWorkspaceRequests; /** * An array of structures that represent the WorkSpaces that were created. Because this operation is asynchronous, the identifier in WorkspaceId is not immediately available. If you immediately call DescribeWorkspaces with this identifier, no information will be returned. */ PendingRequests?: WorkspaceList; } export type DefaultOu = string; export interface DefaultWorkspaceCreationProperties { /** * Specifies if the directory is enabled for Amazon WorkDocs. */ EnableWorkDocs?: BooleanObject; /** * A public IP address will be attached to all WorkSpaces that are created or rebuilt. */ EnableInternetAccess?: BooleanObject; /** * The organizational unit (OU) in the directory that the WorkSpace machine accounts are placed in. */ DefaultOu?: DefaultOu; /** * The identifier of any custom security groups that are applied to the WorkSpaces when they are created. */ CustomSecurityGroupId?: SecurityGroupId; /** * The WorkSpace user is an administrator on the WorkSpace. */ UserEnabledAsLocalAdministrator?: BooleanObject; } export interface DeleteTagsRequest { /** * The resource ID of the request. */ ResourceId: NonEmptyString; /** * The tag keys of the request. */ TagKeys: TagKeyList; } export interface DeleteTagsResult { } export interface DescribeTagsRequest { /** * The resource ID of the request. */ ResourceId: NonEmptyString; } export interface DescribeTagsResult { /** * The list of tags. */ TagList?: TagList; } export interface DescribeWorkspaceBundlesRequest { /** * An array of strings that contains the identifiers of the bundles to retrieve. This parameter cannot be combined with any other filter parameter. */ BundleIds?: BundleIdList; /** * The owner of the bundles to retrieve. This parameter cannot be combined with any other filter parameter. This contains one of the following values: null- Retrieves the bundles that belong to the account making the call. AMAZON- Retrieves the bundles that are provided by AWS. */ Owner?: BundleOwner; /** * The NextToken value from a previous call to this operation. Pass null if this is the first call. */ NextToken?: PaginationToken; } export interface DescribeWorkspaceBundlesResult { /** * An array of structures that contain information about the bundles. */ Bundles?: BundleList; /** * If not null, more results are available. Pass this value for the NextToken parameter in a subsequent call to this operation to retrieve the next set of items. This token is valid for one day and must be used within that time frame. */ NextToken?: PaginationToken; } export interface DescribeWorkspaceDirectoriesRequest { /** * An array of strings that contains the directory identifiers to retrieve information for. If this member is null, all directories are retrieved. */ DirectoryIds?: DirectoryIdList; /** * The NextToken value from a previous call to this operation. Pass null if this is the first call. */ NextToken?: PaginationToken; } export interface DescribeWorkspaceDirectoriesResult { /** * An array of structures that contain information about the directories. */ Directories?: DirectoryList; /** * If not null, more results are available. Pass this value for the NextToken parameter in a subsequent call to this operation to retrieve the next set of items. This token is valid for one day and must be used within that time frame. */ NextToken?: PaginationToken; } export interface DescribeWorkspacesConnectionStatusRequest { /** * An array of strings that contain the identifiers of the WorkSpaces. */ WorkspaceIds?: WorkspaceIdList; /** * The next token of the request. */ NextToken?: PaginationToken; } export interface DescribeWorkspacesConnectionStatusResult { /** * The connection status of the WorkSpace. */ WorkspacesConnectionStatus?: WorkspaceConnectionStatusList; /** * The next token of the result. */ NextToken?: PaginationToken; } export interface DescribeWorkspacesRequest { /** * An array of strings that contain the identifiers of the WorkSpaces for which to retrieve information. This parameter cannot be combined with any other filter parameter. Because the CreateWorkspaces operation is asynchronous, the identifier it returns is not immediately available. If you immediately call DescribeWorkspaces with this identifier, no information is returned. */ WorkspaceIds?: WorkspaceIdList; /** * Specifies the directory identifier to which to limit the WorkSpaces. Optionally, you can specify a specific directory user with the UserName parameter. This parameter cannot be combined with any other filter parameter. */ DirectoryId?: DirectoryId; /** * Used with the DirectoryId parameter to specify the directory user for whom to obtain the WorkSpace. */ UserName?: UserName; /** * The identifier of a bundle to obtain the WorkSpaces for. All WorkSpaces that are created from this bundle will be retrieved. This parameter cannot be combined with any other filter parameter. */ BundleId?: BundleId; /** * The maximum number of items to return. */ Limit?: Limit; /** * The NextToken value from a previous call to this operation. Pass null if this is the first call. */ NextToken?: PaginationToken; } export interface DescribeWorkspacesResult { /** * An array of structures that contain the information about the WorkSpaces. Because the CreateWorkspaces operation is asynchronous, some of this information may be incomplete for a newly-created WorkSpace. */ Workspaces?: WorkspaceList; /** * If not null, more results are available. Pass this value for the NextToken parameter in a subsequent call to this operation to retrieve the next set of items. This token is valid for one day and must be used within that time frame. */ NextToken?: PaginationToken; } export type Description = string; export type DirectoryId = string; export type DirectoryIdList = DirectoryId[]; export type DirectoryList = WorkspaceDirectory[]; export type DirectoryName = string; export type DnsIpAddresses = IpAddress[]; export type ErrorType = string; export type ExceptionMessage = string; export interface FailedCreateWorkspaceRequest { /** * A FailedCreateWorkspaceRequest$WorkspaceRequest object that contains the information about the WorkSpace that could not be created. */ WorkspaceRequest?: WorkspaceRequest; /** * The error code. */ ErrorCode?: ErrorType; /** * The textual error message. */ ErrorMessage?: Description; } export type FailedCreateWorkspaceRequests = FailedCreateWorkspaceRequest[]; export type FailedRebootWorkspaceRequests = FailedWorkspaceChangeRequest[]; export type FailedRebuildWorkspaceRequests = FailedWorkspaceChangeRequest[]; export type FailedStartWorkspaceRequests = FailedWorkspaceChangeRequest[]; export type FailedStopWorkspaceRequests = FailedWorkspaceChangeRequest[]; export type FailedTerminateWorkspaceRequests = FailedWorkspaceChangeRequest[]; export interface FailedWorkspaceChangeRequest { /** * The identifier of the WorkSpace. */ WorkspaceId?: WorkspaceId; /** * The error code. */ ErrorCode?: ErrorType; /** * The textual error message. */ ErrorMessage?: Description; } export type IpAddress = string; export type Limit = number; export interface ModifyWorkspacePropertiesRequest { /** * The ID of the WorkSpace. */ WorkspaceId: WorkspaceId; /** * The WorkSpace properties of the request. */ WorkspaceProperties: WorkspaceProperties; } export interface ModifyWorkspacePropertiesResult { } export type NonEmptyString = string; export type PaginationToken = string; export interface RebootRequest { /** * The identifier of the WorkSpace to reboot. */ WorkspaceId: WorkspaceId; } export type RebootWorkspaceRequests = RebootRequest[]; export interface RebootWorkspacesRequest { /** * An array of structures that specify the WorkSpaces to reboot. */ RebootWorkspaceRequests: RebootWorkspaceRequests; } export interface RebootWorkspacesResult { /** * An array of structures representing any WorkSpaces that could not be rebooted. */ FailedRequests?: FailedRebootWorkspaceRequests; } export interface RebuildRequest { /** * The identifier of the WorkSpace to rebuild. */ WorkspaceId: WorkspaceId; } export type RebuildWorkspaceRequests = RebuildRequest[]; export interface RebuildWorkspacesRequest { /** * An array of structures that specify the WorkSpaces to rebuild. */ RebuildWorkspaceRequests: RebuildWorkspaceRequests; } export interface RebuildWorkspacesResult { /** * An array of structures representing any WorkSpaces that could not be rebuilt. */ FailedRequests?: FailedRebuildWorkspaceRequests; } export type RegistrationCode = string; export type RunningMode = "AUTO_STOP"|"ALWAYS_ON"|string; export type RunningModeAutoStopTimeoutInMinutes = number; export type SecurityGroupId = string; export interface StartRequest { /** * The ID of the WorkSpace. */ WorkspaceId?: WorkspaceId; } export type StartWorkspaceRequests = StartRequest[]; export interface StartWorkspacesRequest { /** * The requests. */ StartWorkspaceRequests: StartWorkspaceRequests; } export interface StartWorkspacesResult { /** * The failed requests. */ FailedRequests?: FailedStartWorkspaceRequests; } export interface StopRequest { /** * The ID of the WorkSpace. */ WorkspaceId?: WorkspaceId; } export type StopWorkspaceRequests = StopRequest[]; export interface StopWorkspacesRequest { /** * The requests. */ StopWorkspaceRequests: StopWorkspaceRequests; } export interface StopWorkspacesResult { /** * The failed requests. */ FailedRequests?: FailedStopWorkspaceRequests; } export type SubnetId = string; export type SubnetIds = SubnetId[]; export interface Tag { /** * The key of the tag. */ Key: TagKey; /** * The value of the tag. */ Value?: TagValue; } export type TagKey = string; export type TagKeyList = NonEmptyString[]; export type TagList = Tag[]; export type TagValue = string; export interface TerminateRequest { /** * The identifier of the WorkSpace to terminate. */ WorkspaceId: WorkspaceId; } export type TerminateWorkspaceRequests = TerminateRequest[]; export interface TerminateWorkspacesRequest { /** * An array of structures that specify the WorkSpaces to terminate. */ TerminateWorkspaceRequests: TerminateWorkspaceRequests; } export interface TerminateWorkspacesResult { /** * An array of structures representing any WorkSpaces that could not be terminated. */ FailedRequests?: FailedTerminateWorkspaceRequests; } export type Timestamp = Date; export type UserName = string; export interface UserStorage { /** * The amount of user storage for the bundle. */ Capacity?: NonEmptyString; } export type VolumeEncryptionKey = string; export interface Workspace { /** * The identifier of the WorkSpace. */ WorkspaceId?: WorkspaceId; /** * The identifier of the AWS Directory Service directory that the WorkSpace belongs to. */ DirectoryId?: DirectoryId; /** * The user that the WorkSpace is assigned to. */ UserName?: UserName; /** * The IP address of the WorkSpace. */ IpAddress?: IpAddress; /** * The operational state of the WorkSpace. */ State?: WorkspaceState; /** * The identifier of the bundle that the WorkSpace was created from. */ BundleId?: BundleId; /** * The identifier of the subnet that the WorkSpace is in. */ SubnetId?: SubnetId; /** * If the WorkSpace could not be created, this contains a textual error message that describes the failure. */ ErrorMessage?: Description; /** * If the WorkSpace could not be created, this contains the error code. */ ErrorCode?: WorkspaceErrorCode; /** * The name of the WorkSpace as seen by the operating system. */ ComputerName?: ComputerName; /** * The KMS key used to encrypt data stored on your WorkSpace. */ VolumeEncryptionKey?: VolumeEncryptionKey; /** * Specifies whether the data stored on the user volume, or D: drive, is encrypted. */ UserVolumeEncryptionEnabled?: BooleanObject; /** * Specifies whether the data stored on the root volume, or C: drive, is encrypted. */ RootVolumeEncryptionEnabled?: BooleanObject; WorkspaceProperties?: WorkspaceProperties; } export interface WorkspaceBundle { /** * The bundle identifier. */ BundleId?: BundleId; /** * The name of the bundle. */ Name?: NonEmptyString; /** * The owner of the bundle. This contains the owner's account identifier, or AMAZON if the bundle is provided by AWS. */ Owner?: BundleOwner; /** * The bundle description. */ Description?: Description; /** * A UserStorage object that specifies the amount of user storage that the bundle contains. */ UserStorage?: UserStorage; /** * A ComputeType object that specifies the compute type for the bundle. */ ComputeType?: ComputeType; } export interface WorkspaceConnectionStatus { /** * The ID of the WorkSpace. */ WorkspaceId?: WorkspaceId; /** * The connection state of the WorkSpace. Returns UNKOWN if the WorkSpace is in a Stopped state. */ ConnectionState?: ConnectionState; /** * The timestamp of the connection state check. */ ConnectionStateCheckTimestamp?: Timestamp; /** * The timestamp of the last known user connection. */ LastKnownUserConnectionTimestamp?: Timestamp; } export type WorkspaceConnectionStatusList = WorkspaceConnectionStatus[]; export interface WorkspaceDirectory { /** * The directory identifier. */ DirectoryId?: DirectoryId; /** * The directory alias. */ Alias?: Alias; /** * The name of the directory. */ DirectoryName?: DirectoryName; /** * The registration code for the directory. This is the code that users enter in their Amazon WorkSpaces client application to connect to the directory. */ RegistrationCode?: RegistrationCode; /** * An array of strings that contains the identifiers of the subnets used with the directory. */ SubnetIds?: SubnetIds; /** * An array of strings that contains the IP addresses of the DNS servers for the directory. */ DnsIpAddresses?: DnsIpAddresses; /** * The user name for the service account. */ CustomerUserName?: UserName; /** * The identifier of the IAM role. This is the role that allows Amazon WorkSpaces to make calls to other services, such as Amazon EC2, on your behalf. */ IamRoleId?: ARN; /** * The directory type. */ DirectoryType?: WorkspaceDirectoryType; /** * The identifier of the security group that is assigned to new WorkSpaces. */ WorkspaceSecurityGroupId?: SecurityGroupId; /** * The state of the directory's registration with Amazon WorkSpaces */ State?: WorkspaceDirectoryState; /** * A structure that specifies the default creation properties for all WorkSpaces in the directory. */ WorkspaceCreationProperties?: DefaultWorkspaceCreationProperties; } export type WorkspaceDirectoryState = "REGISTERING"|"REGISTERED"|"DEREGISTERING"|"DEREGISTERED"|"ERROR"|string; export type WorkspaceDirectoryType = "SIMPLE_AD"|"AD_CONNECTOR"|string; export type WorkspaceErrorCode = string; export type WorkspaceId = string; export type WorkspaceIdList = WorkspaceId[]; export type WorkspaceList = Workspace[]; export interface WorkspaceProperties { /** * The running mode of the WorkSpace. AlwaysOn WorkSpaces are billed monthly. AutoStop WorkSpaces are billed by the hour and stopped when no longer being used in order to save on costs. */ RunningMode?: RunningMode; /** * The time after a user logs off when WorkSpaces are automatically stopped. Configured in 60 minute intervals. */ RunningModeAutoStopTimeoutInMinutes?: RunningModeAutoStopTimeoutInMinutes; } export interface WorkspaceRequest { /** * The identifier of the AWS Directory Service directory to create the WorkSpace in. You can use the DescribeWorkspaceDirectories operation to obtain a list of the directories that are available. */ DirectoryId: DirectoryId; /** * The username that the WorkSpace is assigned to. This username must exist in the AWS Directory Service directory specified by the DirectoryId member. */ UserName: UserName; /** * The identifier of the bundle to create the WorkSpace from. You can use the DescribeWorkspaceBundles operation to obtain a list of the bundles that are available. */ BundleId: BundleId; /** * The KMS key used to encrypt data stored on your WorkSpace. */ VolumeEncryptionKey?: VolumeEncryptionKey; /** * Specifies whether the data stored on the user volume, or D: drive, is encrypted. */ UserVolumeEncryptionEnabled?: BooleanObject; /** * Specifies whether the data stored on the root volume, or C: drive, is encrypted. */ RootVolumeEncryptionEnabled?: BooleanObject; WorkspaceProperties?: WorkspaceProperties; /** * The tags of the WorkSpace request. */ Tags?: TagList; } export type WorkspaceRequestList = WorkspaceRequest[]; export type WorkspaceState = "PENDING"|"AVAILABLE"|"IMPAIRED"|"UNHEALTHY"|"REBOOTING"|"STARTING"|"REBUILDING"|"MAINTENANCE"|"TERMINATING"|"TERMINATED"|"SUSPENDED"|"STOPPING"|"STOPPED"|"ERROR"|string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2015-04-08"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the WorkSpaces client. */ export import Types = WorkSpaces; } export = WorkSpaces;
the_stack
import { useEffect, useMemo, useState } from 'react'; import molecule from '@dtinsight/molecule'; import { Scrollable } from '@dtinsight/molecule/esm/components'; import { connect } from '@dtinsight/molecule/esm/react'; import API from '@/api'; import { message, Spin, Steps } from 'antd'; import { checkExist, getTenantId } from '@/utils'; import saveTask from '@/utils/saveTask'; import type { IDataSourceUsedInSyncProps, ISyncDataProps, IChannelFormProps, IDataColumnsProps, ISourceFormField, ITargetFormField, } from '@/interface'; import { DATA_SYNC_MODE, SUPPROT_SUB_LIBRARY_DB_ARRAY } from '@/constant'; import { Utils } from '@dtinsight/dt-utils/lib'; import type { IKeyMapProps } from './keymap'; import Keymap, { OPERATOR_TYPE } from './keymap'; import Target from './target'; import Channel, { UnlimitedSpeed } from './channel'; import Source from './source'; import Preview from './preview'; import { getStepStatus } from './help'; import { EditorEvent } from '@dtinsight/molecule/esm/model'; import { throttle } from 'lodash'; import './index.scss'; const { Step } = Steps; const throttleUpdateTab = throttle((nextTab: molecule.model.IEditorTab, isEmit: boolean) => { const { current } = molecule.editor.getState(); if (current?.tab) { molecule.editor.updateTab(nextTab); // emit OnUpdateTab so taskParams could be updated if (isEmit) { molecule.editor.emit(EditorEvent.OnUpdateTab, nextTab); } } }, 800); function DataSync({ current }: molecule.model.IEditor) { const [currentStep, setCurrentStep] = useState(0); const [currentData, rawSetCurrentData] = useState<ISyncDataProps | null>(null); /** * keymap 中用户自定义的字段 */ const [userColumns, setUserColumns] = useState<IKeyMapProps>({ source: [], target: [] }); const [loading, setLoading] = useState(false); const [dataSourceList, setDataSourceList] = useState<IDataSourceUsedInSyncProps[]>([]); /** * 包装一层 setCurrentData,以便于区分是否触发 onUpdateTab 事件 */ const setCurrentData = ( nextValues: ISyncDataProps | ((prev: ISyncDataProps | null) => ISyncDataProps), isEmit: boolean = true, ) => { if (typeof nextValues === 'function') { rawSetCurrentData((value) => { const nextValue = nextValues(value); setTimeout(() => { if (current?.tab) { const { sourceMap, targetMap, settingMap } = nextValue; const nextTab = { ...current.tab, data: { ...current.tab.data, sourceMap, targetMap, settingMap }, }; throttleUpdateTab(nextTab, isEmit); } }, 0); return nextValue; }); } else { rawSetCurrentData(nextValues); // sync to tab data if (current?.tab) { const { sourceMap, targetMap, settingMap } = nextValues; const nextTab = { ...current.tab, data: { ...current.tab.data, sourceMap, targetMap, settingMap }, }; throttleUpdateTab(nextTab, isEmit); } } }; const handleSourceChanged = (values: Partial<ISourceFormField>) => { setCurrentData((d) => { const currentDataSourceId = d?.sourceMap?.sourceId || values.sourceId; const target = dataSourceList.find((l) => l.dataInfoId === currentDataSourceId); const isSupportSub = SUPPROT_SUB_LIBRARY_DB_ARRAY.includes(target?.dataTypeCode || -1); // Only the dataSource which has sub library like mySQL need this const sourceList = isSupportSub ? [ { key: 'main', tables: values.table || d?.sourceMap?.table, type: target!.dataTypeCode, name: target!.dataName, sourceId: values.sourceId || d?.sourceMap?.sourceId, }, ] : []; // increment updates const nextData = d!; nextData.sourceMap = { ...nextData.sourceMap, ...values, sourceList, type: target?.dataTypeCode || nextData.sourceMap?.type, }; // 以下属性的变更会引起 columns 的变更 const PROPERTY_OF_EFFECTS = ['table', 'schema', 'sourceId']; if (PROPERTY_OF_EFFECTS.some((property) => Object.keys(values).includes(property))) { nextData.sourceMap.column = []; if (nextData.targetMap) { nextData.targetMap.column = []; } } return nextData; }); }; const handleTargetChanged = (values: Partial<ITargetFormField>) => { const nextValue = values; const SHOULD_TRIM_FIELD: (keyof ITargetFormField)[] = [ 'partition', 'path', 'fileName', 'fileName', ]; SHOULD_TRIM_FIELD.forEach((field) => { if (nextValue.hasOwnProperty(field)) { nextValue[field] = Utils.trimAll(nextValue[field] as string) as any; } }); const target = dataSourceList.find((l) => l.dataInfoId === values.sourceId); // increment updates setCurrentData((d) => { const nextData = { ...d! }; nextData.targetMap = { ...nextData.targetMap, ...values, name: target?.dataName || nextData.targetMap?.name, type: target?.dataTypeCode || nextData.targetMap?.type, }; // 以下属性的变更会引起 columns 的变更 const PROPERTY_OF_EFFECTS = ['table', 'schema', 'sourceId']; if (PROPERTY_OF_EFFECTS.some((property) => Object.keys(values).includes(property))) { nextData.sourceMap!.column = []; nextData.targetMap.column = []; } return nextData; }); }; const handleLinesChange = (lines: IKeyMapProps) => { setCurrentData((d) => { const nextData = { ...d! }; nextData.sourceMap!.column = lines.source; nextData.targetMap!.column = lines.target; return nextData; }); }; const handleColChanged = ( col: IDataColumnsProps | IDataColumnsProps[], operation: Valueof<typeof OPERATOR_TYPE>, flag: 'source' | 'target', ) => { const cols = Array.isArray(col) ? col : [col]; switch (operation) { case OPERATOR_TYPE.ADD: { cols.forEach((c) => { handleAddCol(c, flag); }); break; } case OPERATOR_TYPE.REMOVE: { cols.forEach((c) => { handleRemoveCol(c, flag); }); break; } case OPERATOR_TYPE.EDIT: { cols.forEach((c) => { handleEditCol(c, flag); }); break; } case OPERATOR_TYPE.REPLACE: { // replace mode is to replace the whole column field setUserColumns((uCols) => { const nextCols = { ...uCols }; nextCols[flag] = cols; return nextCols; }); break; } default: break; } }; // 编辑列 const handleEditCol = (col: IDataColumnsProps, flag: 'source' | 'target') => { // const field = flag === 'source' ? 'sourceMap' : 'targetMap'; setUserColumns((cols) => { const nextCols = { ...cols }; const column = nextCols[flag]; if (!column.includes(col)) return cols; const idx = column.indexOf(col); // 这里只做赋值,不做深拷贝 // 因为字段映射的数组里的值和 column 字段的值是同一个引用,直接改这个值就可以做到都改了。如果做深拷贝则需要改两次值 Object.assign(column[idx], col); return nextCols; }); }; // 添加列 const handleAddCol = (col: IDataColumnsProps, flag: 'source' | 'target') => { setUserColumns((cols) => { const nextCols = { ...cols }; const columns = nextCols[flag]; if (checkExist(col.index) && columns.some((o) => o.index === col.index)) { message.error(`添加失败:索引值不能重复`); return cols; } if (checkExist(col.key) && columns.some((o) => o.key === col.key)) { message.error(`添加失败:字段名不能重复`); return cols; } columns.push(col); return nextCols; }); }; // 移除列 const handleRemoveCol = (col: IDataColumnsProps, flag: 'source' | 'target') => { setUserColumns((cols) => { const nextCols = { ...cols }; const columns = nextCols[flag]; if (!columns || !columns.includes(col)) return cols; const idx = columns.indexOf(col); columns.splice(idx, 1); return nextCols; }); }; const handleSettingChanged = (values: IChannelFormProps) => { const nextSettings = { ...values }; const isUnlimited = nextSettings.speed === UnlimitedSpeed; if (isUnlimited) { nextSettings.speed = '-1'; } if (nextSettings.isRestore === false) { nextSettings.restoreColumnName = undefined; } // 增量模式下,开启断点续传字段默认与增量字段保存一致 if (isIncrementMode && nextSettings.isRestore === true) { nextSettings.restoreColumnName = currentData!.sourceMap!.increColumn; } setCurrentData((d) => { const nextData = { ...d! }; nextData.settingMap = nextSettings; return nextData; }); }; const handleChannelSubmit = (next: boolean, values?: IChannelFormProps) => { if (!next) { setCurrentStep((s) => s - 1); return; } if (values) { // 存在值的话,则保存当前值 handleSettingChanged(values); } setCurrentStep((s) => s + 1); }; const handleSaveTab = () => { saveTask() .then((res) => res?.data?.id) .then((id) => { if (id !== undefined) { molecule.editor.updateTab({ id: current!.tab!.id, status: undefined, }); } }); }; // 获取当前任务的数据 const getJobData = () => { const taskId = current?.tab?.data.id; if (typeof taskId === 'undefined') return; const [, step] = getStepStatus(current?.tab?.data); setCurrentStep(step); const { id, sourceMap, targetMap, settingMap } = current?.tab?.data || {}; setCurrentData( { sourceMap, targetMap, settingMap, taskId: id, }, false, ); }; const getDataSourceList = () => { setLoading(true); return API.queryByTenantId({ tenantId: getTenantId() }) .then((res) => { if (res.code === 1) { setDataSourceList(res.data || []); } }) .finally(() => { setLoading(false); }); }; useEffect(() => { // Should first to get the datasource list // as there are lots of requests should get sourceType via sourceId and to check whether could request getDataSourceList().then(() => { getJobData(); }); }, [current?.activeTab]); // 是否是增量模式 const isIncrementMode = useMemo(() => { if (current?.tab?.data?.sourceMap?.syncModel !== undefined) { return current?.tab?.data?.sourceMap?.syncModel === DATA_SYNC_MODE.INCREMENT; } return false; }, [current]); const steps = [ { key: 'source', title: '数据来源', content: ( <Source isIncrementMode={isIncrementMode} sourceMap={currentData?.sourceMap} dataSourceList={dataSourceList} onFormValuesChanged={handleSourceChanged} onNext={() => setCurrentStep((s) => s + 1)} /> ), }, { key: 'target', title: '选择目标', content: ( <Target isIncrementMode={isIncrementMode} sourceMap={currentData?.sourceMap} targetMap={currentData?.targetMap} dataSourceList={dataSourceList} onFormValuesChanged={handleTargetChanged} onNext={(next) => setCurrentStep((s) => (next ? s + 1 : s - 1))} /> ), }, { key: 'keymap', title: '字段映射', content: currentData?.sourceMap && currentData.targetMap && ( <Keymap sourceMap={currentData.sourceMap} targetMap={currentData.targetMap} userColumns={userColumns} onColsChanged={handleColChanged} onLinesChanged={handleLinesChange} onNext={(next) => setCurrentStep((s) => (next ? s + 1 : s - 1))} /> ), }, { key: 'setting', title: '通道控制', content: currentData?.sourceMap && currentData.targetMap && ( <Channel isIncrementMode={isIncrementMode} sourceMap={currentData.sourceMap} targetMap={currentData.targetMap} setting={currentData.settingMap} onNext={handleChannelSubmit} onFormValuesChanged={handleSettingChanged} /> ), }, { key: 'preview', title: '预览保存', content: currentData && ( <Preview isIncrementMode={isIncrementMode} data={currentData} dataSourceList={dataSourceList} userColumns={userColumns} onStepTo={(step) => setCurrentStep((s) => (typeof step === 'number' ? step : s - 1)) } onSave={handleSaveTab} /> ), }, ]; return ( <Scrollable isShowShadow> <div className="dt-datasync"> <Spin spinning={loading}> <Steps size="small" current={currentStep}> {steps.map((item) => ( <Step key={item.title} title={item.title} /> ))} </Steps> <div className="dt-datasync-content"> {currentData && steps[currentStep].content} </div> </Spin> </div> </Scrollable> ); } export default connect(molecule.editor, DataSync);
the_stack
import * as fs from "fs"; import * as path from "path"; import * as os from "os"; import { execSync } from "child_process"; import { File, FileLink } from "../common/File"; import { Logger } from "../common/Logger"; import { Reader, IMountList, ProgressFunc, ProgressResult } from "../common/Reader"; import { Transform } from "stream"; import * as FileType from "file-type"; import * as jschardet from "jschardet"; import * as iconv from "iconv-lite"; import fswin from "fswin"; const log = Logger("FileReader"); interface Win32Attributes { CREATION_TIME: Date; LAST_ACCESS_TIME: Date; LAST_WRITE_TIME: Date; SIZE: number; IS_ARCHIVED: boolean; IS_COMPRESSED: boolean; IS_DEVICE: boolean; IS_DIRECTORY: boolean; IS_ENCRYPTED: boolean; IS_HIDDEN: boolean; IS_NOT_CONTENT_INDEXED: boolean; IS_OFFLINE: boolean; IS_READ_ONLY: boolean; IS_SPARSE_FILE: boolean; IS_SYSTEM: boolean; IS_TEMPORARY: boolean; IS_INTEGRITY_STREAM: boolean; IS_NO_SCRUB_DATA: boolean; IS_REPARSE_POINT: boolean; } const convertAttr = ( stats: fs.Stats ): string => { const fileMode: string[] = "----------".split(""); fileMode[0] = stats.isSocket() ? "s" : fileMode[0]; fileMode[0] = stats.isBlockDevice() ? "b" : fileMode[0]; fileMode[0] = stats.isCharacterDevice() ? "c" : fileMode[0]; fileMode[0] = stats.isFIFO() ? "p" : fileMode[0]; fileMode[0] = stats.isDirectory() ? "d" : fileMode[0]; fileMode[0] = stats.isSymbolicLink() ? "l" : fileMode[0]; fileMode[1] = stats.mode & 256 ? "r" : "-"; fileMode[2] = stats.mode & 128 ? "w" : "-"; fileMode[3] = stats.mode & 64 ? "x" : "-"; fileMode[4] = stats.mode & 32 ? "r" : "-"; fileMode[5] = stats.mode & 16 ? "w" : "-"; fileMode[6] = stats.mode & 8 ? "x" : "-"; fileMode[7] = stats.mode & 4 ? "r" : "-"; fileMode[8] = stats.mode & 2 ? "w" : "-"; fileMode[9] = stats.mode & 1 ? "x" : "-"; return fileMode.join(""); }; export function convertAttrToStatMode( file: File ): number { if ( file instanceof File && file.attr && file.attr.length === 10 ) { let mode = 0; mode = mode | (file.attr[1] === "r" ? 256 : 0); mode = mode | (file.attr[2] === "w" ? 128 : 0); mode = mode | (file.attr[3] === "x" ? 64 : 0); mode = mode | (file.attr[4] === "r" ? 32 : 0); mode = mode | (file.attr[5] === "w" ? 16 : 0); mode = mode | (file.attr[6] === "x" ? 8 : 0); mode = mode | (file.attr[7] === "r" ? 4 : 0); mode = mode | (file.attr[8] === "w" ? 2 : 0); mode = mode | (file.attr[9] === "x" ? 1 : 0); return mode; } return 0; } const convertAttrFsDirect = ( dirent: fs.Dirent ): string => { const fileMode: string[] = os.platform() === "win32" ? "------".split("") : "----------".split(""); fileMode[0] = dirent.isSymbolicLink() ? "l" : (dirent.isDirectory() ? "d" : "-"); return fileMode.join(""); }; const convertAttrWin32 = ( stat: Win32Attributes ): string => { const fileMode: string[] = "------".split(""); fileMode[0] = stat.IS_DIRECTORY ? "d" : "-"; fileMode[1] = stat.IS_ARCHIVED ? "a" : "-"; fileMode[2] = stat.IS_READ_ONLY ? "r" : "-"; fileMode[3] = stat.IS_HIDDEN ? "h" : "-"; fileMode[4] = stat.IS_SYSTEM ? "s" : "-"; return fileMode.join(""); }; const PASSWD_FILE = "/etc/passwd"; interface ISystemUserInfo { name?: string; uid?: number; gid?: number; fullname?: string; homepath?: string; sh?: string; } export class SystemUserInfo { private _userInfo: ISystemUserInfo[] = []; constructor() { this.reload(); } reload() { try { if ( fs.existsSync( PASSWD_FILE ) ) { const valueKeys = [ "name", "", "uid", "gid", "fullname", "homepath", "sh" ]; // root:x:0:0:root:/root:/bin/bash const buffer = fs.readFileSync( PASSWD_FILE, "utf8" ); const userInfos = []; buffer.split("\n").forEach( userInfoLine => { if ( !userInfoLine.startsWith("#" ) ) { const userInfoArr = userInfoLine.split(":"); const userInfo = {}; valueKeys.forEach( (key, i) => { if ( key ) { if ( [ "uid", "gid" ].indexOf(key) > -1 ) { userInfo[key] = parseInt(userInfoArr[i]); } else { userInfo[key] = userInfoArr[i]; } } }); userInfos.push( userInfo ); } }); this._userInfo = userInfos; } } catch( e ) { log.error( e ); this._userInfo = []; } } findUid( uid: number, key: string = null ): ISystemUserInfo | string | number { const item = this._userInfo.find( (item) => item.uid === uid ); return key ? (item && item[ key ]) : item; } findGid( gid: number, key: string = null ): ISystemUserInfo | string | number { const item = this._userInfo.find( (item) => item.gid === gid ); return key ? (item && item[ key ]) : item; } } export class FileReader extends Reader { protected _readerFsType = "file"; protected systemUserInfo = null; protected watcher = null; protected _isNotChangeDir = false; protected _curDir: File = null; constructor() { super(); this.systemUserInfo = new SystemUserInfo(); } async init(option: { isNotChangeDir?: boolean; defaultHomePath?: string } = null) { this._isNotChangeDir = option?.isNotChangeDir || false; this._curDir = await this.convertFile( option?.defaultHomePath || os.homedir(), { checkRealPath: true }); } destory() { if ( this.watcher ) { this.watcher.close(); this.watcher = null; } } async rootDir(): Promise<File> { return await this.convertFile( path.parse(fs.realpathSync(".")).root ); } async homeDir(): Promise<File> { return await this.convertFile( os.homedir() ); } async mountListWin10(): Promise<IMountList[]> { const mounts: IMountList[] = []; const convertBufferCode = ( bufferData: Buffer ): string => { let result = null; try { result = jschardet.detect( bufferData ); } catch ( e ) { log.error( e ); } log.info( "jschardet: %j", result ); try { let data = null; if ( result && result.encoding ) { if ( [ "utf8", "ascii" ].indexOf(result.encoding) > -1 ) { data = bufferData.toString("utf8"); } else { data = iconv.decode(bufferData, result.encoding); } } return data; } catch( e ) { log.error( e ); } return null; }; const result: Buffer = execSync("wmic logicaldisk get deviceid, volumename, description, drivetype, freespace, size /VALUE"); if ( !result ) { return mounts; } const convertInfo = convertBufferCode(result); if ( !convertInfo ) { return mounts; } const texts = convertInfo.split("\r\r\n"); const mountInfo = []; let device = null; for ( const item of texts ) { if ( !item && device ) { mountInfo.push( device ); device = null; } else { const text: string[] = item.split("="); if ( text[0] ) { device = device || {}; device[ text[0] ] = text.slice(1).join("="); } } } for ( const item of mountInfo ) { log.debug( "%s", item ); const mountFile = await this.convertFile( item.DeviceID + path.sep, { useThrow: false, checkRealPath: true } ); if ( mountFile ) { mounts.push( { device: item.VolumeName, description: item.Description, mountPath: mountFile, freesize: parseInt(item.FreeSpace || 0), size: parseInt(item.Size || 0), isCard: item.DriveType === "5", isUSB: item.DriveType === "2", isRemovable: item.DriveType === "2", isSystem: item.DriveType === "3" }); } } return mounts; } async mountListMac(): Promise<IMountList[]> { const mounts: IMountList[] = []; const result = execSync("mount", { encoding: "utf8" }); if ( !result ) { return mounts; } const items = result.split("\n"); for ( const item of items ) { const result = item.match( /(.*) on (.*) \((.*)\)/i ); if ( !result || result.length !== 4 ) { continue; } if ( result[3].match( "nobrowse" ) ) { continue; } const mountFile = await this.convertFile( result[2] ); mounts.push({ device: result[1], description: result[1] + "(" + result[3] + ")", mountPath: mountFile, freesize: 0, size: 0, isCard: false, isUSB: false, isRemovable: false, isSystem: false }); } return mounts; } async mountListLinux(): Promise<IMountList[]> { const mounts: IMountList[] = []; // -e7 filters out squashfs, which is used by Ubuntu's Snap packages const result = execSync("lsblk -e7 -Jbo PATH,TYPE,LABEL,PARTLABEL,UUID,PARTUUID,MOUNTPOINT,FSAVAIL,FSSIZE,SIZE,RM,HOTPLUG").toString(); if ( !result ) { return mounts; } const resultObj = JSON.parse(result); let items = resultObj.blockdevices.slice(); let item = null; while ( (item = items.pop()) ) { if ( item.children ) { items = items.concat( item.children ); continue; } if ( !item.mountpoint || item.mountpoint === "[SWAP]" ) { continue; } const mountFile = await this.convertFile( item.mountpoint ); if ( !mountFile ) { continue; } let uuidStr = ""; if ( item.uuid || item.partuuid) { uuidStr = " (" + ( item.uuid || item.partuuid ) + ")"; } mounts.push({ device: item.path, description: (item.label || item.partlabel || item.type) + uuidStr, mountPath: mountFile, freesize: item.fsavail || 0, size: item.fssize || item.size, isCard: item.hotplug, isUSB: item.rm && item.hotplug, isRemovable: item.rm, isSystem: !item.rm }); } return mounts; } async mountList(): Promise<IMountList[]> { if ( os.platform() === "win32" && parseInt(os.release()) >= 10 ) { return this.mountListWin10(); } else if ( os.platform() === "darwin" ) { return this.mountListMac(); } else { return this.mountListLinux(); } } static async convertFile( filePath: string, option?: { fileInfo?: any; useThrow?: boolean; checkRealPath?: boolean; virtualFile?: boolean } ): Promise<File> { const fileReader = new FileReader(); return await fileReader.convertFile( filePath, option ); } convertFile( filePath: string, option?: { fileInfo?: any; useThrow?: boolean; checkRealPath?: boolean; virtualFile?: boolean } ): Promise<File> { // eslint-disable-next-line no-async-promise-executor return new Promise( async (resolve, reject) => { const { fileInfo, useThrow, checkRealPath } = option || {}; const file = new File(); file.fstype = this._readerFsType; try { if ( filePath === "~" || filePath[0] === "~" ) { file.fullname = os.homedir() + filePath.substr(1); } else if ( filePath === ".." || filePath === "." ) { file.fullname = fs.realpathSync(path.join((await this.currentDir()).fullname, filePath)); } else { file.fullname = checkRealPath ? fs.realpathSync(filePath) : filePath; } const pathInfo = path.parse( file.fullname ); file.root = pathInfo.root; file.name = pathInfo.base || pathInfo.root; } catch( e ) { log.error( "convertfile - FAIL : [%s] %j", filePath, e); if ( useThrow ) { reject( e ); return; } resolve(null); return; } if ( option && option.virtualFile ) { file.dir = false; file.uid = -1; file.gid = -1; file.ctime = new Date(0); file.mtime = new Date(0); file.atime = new Date(0); resolve(file); return; } try { if ( process.platform === "win32" ) { const item: Win32Attributes = fswin.getAttributesSync(file.fullname); // log.debug( "%s, %j", fullPathname, JSON.stringify( item ) ); file.attr = convertAttrWin32( item ); file.dir = item.IS_DIRECTORY; file.size = item.SIZE; file.ctime = item.CREATION_TIME; file.mtime = item.LAST_WRITE_TIME; file.atime = item.LAST_ACCESS_TIME; } else { const stat = fs.lstatSync( file.fullname ); file.dir = stat.isDirectory(); file.size = stat.size; file.attr = convertAttr( stat ); file.uid = stat.uid; file.gid = stat.gid; file.owner = this.systemUserInfo.findUid(stat.uid, "name"); file.group = this.systemUserInfo.findGid(stat.gid, "name"); file.ctime = stat.ctime; file.mtime = stat.mtime; file.atime = stat.atime; } } catch ( e ) { log.error( "convertfile - FAIL 2 : [%s] %j", filePath, e); if ( fileInfo ) { file.dir = fileInfo.isDirectory(); file.attr = convertAttrFsDirect( fileInfo ); file.uid = -1; file.gid = -1; file.ctime = new Date(0); file.mtime = new Date(0); file.atime = new Date(0); } else { if ( useThrow ) { reject(e); return null; } resolve(null); return null; } } if ( (file.attr && file.attr[0] === "l") || (fileInfo && fileInfo.isSymbolicLink()) ) { try { const linkOrgName = fs.readlinkSync( file.fullname ); file.link = new FileLink( path.basename( linkOrgName ) ); const linkStat = fs.lstatSync( linkOrgName ); if ( linkStat && !linkStat.isSymbolicLink() ) { file.link.file = await this.convertFile( linkOrgName ); } } catch ( e ) { log.error( "convertfile - FAIL 3 : [%s] %j", filePath, e); } } resolve(file); }); } onWatch( eventFunc: (event?: string, name?: string) => void ) { if ( this.watcher ) { this.watcher.close(); this.watcher = null; } this.watchEventFunc = eventFunc; } async changeDir( dirFile: File ): Promise<void> { if ( dirFile && dirFile.fullname ) { process.chdir( dirFile.fullname ); } } async currentDir(): Promise<File> { if ( this._isNotChangeDir && this._curDir ) { return this._curDir; } return await this.convertFile(process.cwd()); } async readdir( dirFile: File, option?: { isExcludeHiddenFile?: boolean; noChangeDir?: boolean }, filter?: (file: File) => boolean ): Promise<File[]> { if ( !dirFile.dir ) { throw new Error(`Not directory. ${dirFile.name}`); } const fileItem: File[] = []; try { if ( !(option && option.noChangeDir) && !this._isNotChangeDir ) { process.chdir(dirFile.fullname); } const fileList: fs.Dirent[] = (fs as any).readdirSync( dirFile.fullname, { encoding: "utf8", withFileTypes: true } ); // log.info( "READDIR: PATH: [%s], FILES: %j", dirFile.fullname, fileList ); for ( const file of fileList ) { let dirPath = dirFile.fullname; if ( dirPath.substr(dirPath.length - 1, 1) !== path.sep) { dirPath += path.sep; } const item = await this.convertFile(dirPath + file.name, { fileInfo: file } ); // log.info( "dirInfo [%s][%s][%s]", dirPath, file.name, item.fullname ); if ( option && option.isExcludeHiddenFile ) { if ( process.platform !== "win32" && item.name !== ".." && item.name[0] === "." ) { continue; } } if ( item ) { const isPushItem = filter ? filter( item ) : true; if ( isPushItem ) { fileItem.push( item ); } } } if ( this._isNotChangeDir ) { this._curDir = dirFile; } if ( this.watcher ) { this.watcher.close(); this.watcher = null; } if ( this.watchEventFunc ) { this.watcher = fs.watch( dirFile.fullname, (event, eventName) => { this.watchEventFunc && this.watchEventFunc( event, eventName ); }); } } catch ( e ) { log.error( "READDIR () - ERROR %j", e ); throw e; } /* this.fileTypeUpdate(fileItem).finally( () => { resolve( fileItem ); }); */ return fileItem; } async fileTypeUpdate( fileItem: File[] ) { for ( const item of fileItem ) { if ( !item.dir && !item.link ) { try { const fileType = await FileType.fromFile( item.fullname ); if ( fileType ) { item.mimetype = fileType.mime; } } catch( e ) { log.debug( e ); } } } } sep() { return path.sep; } exist( source: File | string ): Promise<boolean> { return new Promise( resolve => { try { if ( source instanceof File ) { resolve(!!fs.lstatSync( source.fullname )); return; } resolve(!!fs.lstatSync( source )); } catch( e ) { log.error( e ); resolve( false ); } return; }); } async newFile(path: string | File, _progress?: ProgressFunc): Promise<void> { const name = path instanceof File ? path.fullname : path; return new Promise( (resolve, reject) => { const result: fs.WriteStream = fs.createWriteStream(name, { mode: 0o644, encoding: null, flags: "w", autoClose: true }); result.write( "", (err) => { if ( result ) { result.close(); } if ( err ) { log.error("NEWFILE ERROR: %s", err); reject( err ); } else { log.debug("NEWFILE: %s", name); resolve(); } }); }); } async mkdir( path: string | File, _progress?: ProgressFunc ): Promise<void> { return new Promise( (resolve, reject) => { if ( path instanceof File ) { if ( !path.dir ) { return; } fs.mkdir( path.fullname, { mode: convertAttrToStatMode(path) }, (err) => { if ( err ) { reject( err ); } else { resolve(); } }); } else { fs.mkdir( path, (err) => { if ( err ) { reject( err ); } else { resolve(); } }); } }); } rename( source: File, rename: string, _progress?: ProgressFunc ): Promise<void> { return new Promise( (resolve, reject) => { fs.rename( source.fullname, rename, (err) => { if ( err ) { reject( err ); } else { resolve(); } }); }); } copy(source: File | File[], sourceBaseDir: File, targetDir: File, progress?: ProgressFunc): Promise<void> { return new Promise( ( resolve, reject ) => { if ( Array.isArray(source) ) { reject( "Unsupport file array type !!!" ); return; } const srcFile = source; if ( source.link ) { try { if ( fs.existsSync(targetDir.fullname) ) { fs.unlinkSync(targetDir.fullname); } if ( source.link.file ) { fs.symlinkSync( source.link.file.fullname, targetDir.fullname, source.link.file.dir ? "dir" : "file" ); } else { fs.symlinkSync( source.link.name, targetDir.fullname ); } } catch( e ) { log.error( e ); reject( e ); return; } resolve(); return; } if ( srcFile.dir || targetDir.dir ) { reject("Unable to copy from a source directory."); return; } if ( srcFile.dirname === targetDir.fullname ) { log.debug( "source file and target file are the same." ); resolve(); return; } let chunkCopyLength = 0; const rd = fs.createReadStream(srcFile.fullname); const wr = fs.createWriteStream(targetDir.fullname); const rejectFunc = (err) => { rd.destroy(); wr.end(() => { fs.unlinkSync( targetDir.fullname ); }); log.debug( "COPY ERROR - " + err ); reject(err); }; rd.on("error", rejectFunc); wr.on("error", rejectFunc); wr.on("finish", () => { resolve(); }); const reportProgress = new Transform({ transform(chunk: Buffer, encoding, callback) { chunkCopyLength += chunk.length; const result = progress && progress( srcFile, chunkCopyLength, srcFile.size, chunk.length ); log.debug( "Copy to: %s => %s (%d / %d)", srcFile.fullname, targetDir.fullname, chunkCopyLength, srcFile.size ); if ( result === ProgressResult.USER_CANCELED ) { rd.destroy(); wr.end(() => { fs.unlinkSync( targetDir.fullname ); }); log.debug( "COPY - CANCEL" ); reject( "USER_CANCEL" ); return; } callback( null, chunk ); } }); rd.pipe( reportProgress ).pipe(wr); }); } remove( source: File ): Promise<void> { return new Promise( (resolve, reject) => { if ( source.dir ) { fs.rmdir( source.fullname, (err) => { if ( err ) { reject( err ); } else { resolve(); } }); } else { fs.unlink( source.fullname, (err) => { if ( err ) { reject( err ); } else { resolve(); } }); } }); } static async remove( file: File ) { const fileReader = new FileReader(); return await fileReader.remove( file ); } viewer( file: File, _progress?: ProgressFunc ): Promise<{ orgFile: File; tmpFile: File; endFunc: () => Promise<void> }> { return new Promise((resolve) => { resolve( { orgFile: file, tmpFile: null, endFunc: null } ); }); } createFile( fullname: string, option?: { virtualFile?: boolean } ): Promise<File> { if ( !(option && option.virtualFile) ) { fs.writeFileSync( fullname, "", { mode: 0o644 } ); return this.convertFile( fullname, { checkRealPath: true } ); } return this.convertFile( fullname, { virtualFile: true } ); } static createFile( fullname: string, option?: { virtualFile?: boolean } ): Promise<File> { const fileReader = new FileReader(); return fileReader.createFile( fullname, option ); } }
the_stack
import { format, isFunction } from 'util'; import { AzureFunctionsRpcMessages as rpc } from '../azure-functions-language-worker-protobuf/src/rpc'; import { augmentTriggerMetadata } from './augmenters'; import { CreateContextAndInputs, LogCallback, ResultCallback } from './Context'; import { toTypedData } from './converters'; import { IFunctionLoader } from './FunctionLoader'; import { IEventStream } from './GrpcService'; import { Context } from './public/Interfaces'; import { InternalException } from './utils/InternalException'; import { systemError, systemWarn } from './utils/Logger'; import LogCategory = rpc.RpcLog.RpcLogCategory; import LogLevel = rpc.RpcLog.Level; type InvocationRequestBefore = (context: Context, userFn: Function) => Function; type InvocationRequestAfter = (context: Context) => void; /** * The worker channel should have a way to handle all incoming gRPC messages. * This includes all incoming StreamingMessage types (exclude *Response types and RpcLog type) */ interface IWorkerChannel { startStream(requestId: string, msg: rpc.StartStream): void; workerInitRequest(requestId: string, msg: rpc.WorkerInitRequest): void; workerHeartbeat(requestId: string, msg: rpc.WorkerHeartbeat): void; workerTerminate(requestId: string, msg: rpc.WorkerTerminate): void; workerStatusRequest(requestId: string, msg: rpc.WorkerStatusRequest): void; fileChangeEventRequest(requestId: string, msg: rpc.FileChangeEventRequest): void; functionLoadRequest(requestId: string, msg: rpc.FunctionLoadRequest): void; invocationRequest(requestId: string, msg: rpc.InvocationRequest): void; invocationCancel(requestId: string, msg: rpc.InvocationCancel): void; functionEnvironmentReloadRequest(requestId: string, msg: rpc.IFunctionEnvironmentReloadRequest): void; registerBeforeInvocationRequest(beforeCb: InvocationRequestBefore): void; registerAfterInvocationRequest(afterCb: InvocationRequestAfter): void; } /** * Initializes handlers for incoming gRPC messages on the client */ export class WorkerChannel implements IWorkerChannel { private _eventStream: IEventStream; private _functionLoader: IFunctionLoader; private _workerId: string; private _v1WorkerBehavior: boolean; private _invocationRequestBefore: InvocationRequestBefore[]; private _invocationRequestAfter: InvocationRequestAfter[]; constructor(workerId: string, eventStream: IEventStream, functionLoader: IFunctionLoader) { this._workerId = workerId; this._eventStream = eventStream; this._functionLoader = functionLoader; // default value this._v1WorkerBehavior = false; this._invocationRequestBefore = []; this._invocationRequestAfter = []; // call the method with the matching 'event' name on this class, passing the requestId and event message eventStream.on('data', (msg) => { const event = <string>msg.content; const eventHandler = (<any>this)[event]; if (eventHandler) { eventHandler.apply(this, [msg.requestId, msg[event]]); } else { this.log({ message: `Worker ${workerId} had no handler for message '${event}'`, level: LogLevel.Error, logCategory: LogCategory.System, }); } }); eventStream.on('error', function (err) { systemError(`Worker ${workerId} encountered event stream error: `, err); throw new InternalException(err); }); // wrap event stream write to validate message correctness const oldWrite = eventStream.write; eventStream.write = function checkWrite(msg) { const msgError = rpc.StreamingMessage.verify(msg); if (msgError) { systemError(`Worker ${workerId} malformed message`, msgError); throw new InternalException(msgError); } oldWrite.apply(eventStream, [msg]); }; } /** * Captured logs or relevant details can use the logs property * @param requestId gRPC message request id * @param msg gRPC message content */ private log(log: rpc.IRpcLog) { this._eventStream.write({ rpcLog: log, }); } /** * Register a patching function to be run before User Function is executed. * Hook should return a patched version of User Function. */ public registerBeforeInvocationRequest(beforeCb: InvocationRequestBefore): void { this._invocationRequestBefore.push(beforeCb); } /** * Register a function to be run after User Function resolves. */ public registerAfterInvocationRequest(afterCb: InvocationRequestAfter): void { this._invocationRequestAfter.push(afterCb); } /** * Host sends capabilities/init data to worker and requests the worker to initialize itself * @param requestId gRPC message request id * @param msg gRPC message content */ public workerInitRequest(requestId: string, msg: rpc.WorkerInitRequest) { // TODO: add capability from host to go to "non-breaking" mode if (msg.capabilities && msg.capabilities.V2Compatable) { this._v1WorkerBehavior = true; } // Validate version const version = process.version; if (this._v1WorkerBehavior) { if (version.startsWith('v12.')) { systemWarn( 'The Node.js version you are using (' + version + ') is not fully supported with Azure Functions V2. We recommend using one the following major versions: 8, 10.' ); } else if (version.startsWith('v14.')) { const msg = 'Incompatible Node.js version' + ' (' + version + ').' + ' The version of the Azure Functions runtime you are using (v2) supports Node.js v8.x and v10.x.' + ' Refer to our documentation to see the Node.js versions supported by each version of Azure Functions: https://aka.ms/functions-node-versions'; systemError(msg); throw new InternalException(msg); } } else { if (version.startsWith('v8.')) { const msg = 'Incompatible Node.js version' + ' (' + version + ').' + ' The version of the Azure Functions runtime you are using (v3) supports Node.js v10.x and v12.x.' + ' Refer to our documentation to see the Node.js versions supported by each version of Azure Functions: https://aka.ms/functions-node-versions'; systemError(msg); throw new InternalException(msg); } } const workerCapabilities = { RpcHttpTriggerMetadataRemoved: 'true', RpcHttpBodyOnly: 'true', IgnoreEmptyValuedRpcHttpHeaders: 'true', UseNullableValueDictionaryForHttp: 'true', WorkerStatus: 'true', }; if (!this._v1WorkerBehavior) { workerCapabilities['TypedDataCollection'] = 'true'; } this._eventStream.write({ requestId: requestId, workerInitResponse: { result: this.getStatus(), capabilities: workerCapabilities, }, }); } /** * Worker responds after loading required metadata to load function with the load result * @param requestId gRPC message request id * @param msg gRPC message content */ public async functionLoadRequest(requestId: string, msg: rpc.FunctionLoadRequest) { if (msg.functionId && msg.metadata) { let err, errorMessage; try { await this._functionLoader.load(msg.functionId, msg.metadata); } catch (exception) { errorMessage = `Worker was unable to load function ${msg.metadata.name}: '${exception}'`; this.log({ message: errorMessage, level: LogLevel.Error, logCategory: LogCategory.System, }); err = exception; } this._eventStream.write({ requestId: requestId, functionLoadResponse: { functionId: msg.functionId, result: this.getStatus(err, errorMessage), }, }); } } /** * Host requests worker to invoke a Function * @param requestId gRPC message request id * @param msg gRPC message content */ public invocationRequest(requestId: string, msg: rpc.InvocationRequest) { // Repopulate triggerMetaData if http. if (this._v1WorkerBehavior) { augmentTriggerMetadata(msg); } const info = this._functionLoader.getInfo(<string>msg.functionId); const logCallback: LogCallback = (level, category, ...args) => { this.log({ invocationId: msg.invocationId, category: `${info.name}.Invocation`, message: format.apply(null, <[any, any[]]>args), level: level, logCategory: category, }); }; const resultCallback: ResultCallback = (err, result) => { const response: rpc.IInvocationResponse = { invocationId: msg.invocationId, result: this.getStatus(err), }; // explicitly set outputData to empty array to concat later response.outputData = []; // As legacy behavior, falsy values get serialized to `null` in AzFunctions. // This breaks Durable Functions expectations, where customers expect any // JSON-serializable values to be preserved by the framework, // so we check if we're serializing for durable and, if so, ensure falsy // values get serialized. const isDurableBinding = info?.bindings?.name?.type == 'activityTrigger'; try { if (result || (isDurableBinding && result != null)) { const returnBinding = info.getReturnBinding(); // Set results from return / context.done if (result.return || (isDurableBinding && result.return != null)) { if (this._v1WorkerBehavior) { response.returnValue = toTypedData(result.return); } else { // $return binding is found: return result data to $return binding if (returnBinding) { response.returnValue = returnBinding.converter(result.return); // $return binding is not found: read result as object of outputs } else { response.outputData = Object.keys(info.outputBindings) .filter((key) => result.return[key] !== undefined) .map( (key) => <rpc.IParameterBinding>{ name: key, data: info.outputBindings[key].converter(result.return[key]), } ); } // returned value does not match any output bindings (named or $return) // if not http, pass along value if (!response.returnValue && response.outputData.length == 0 && !info.hasHttpTrigger) { response.returnValue = toTypedData(result.return); } } } // Set results from context.bindings if (result.bindings) { response.outputData = response.outputData.concat( Object.keys(info.outputBindings) // Data from return prioritized over data from context.bindings .filter((key) => { const definedInBindings: boolean = result.bindings[key] !== undefined; const hasReturnValue = !!result.return; const hasReturnBinding = !!returnBinding; const definedInReturn: boolean = hasReturnValue && !hasReturnBinding && result.return[key] !== undefined; return definedInBindings && !definedInReturn; }) .map( (key) => <rpc.IParameterBinding>{ name: key, data: info.outputBindings[key].converter(result.bindings[key]), } ) ); } } } catch (e) { response.result = this.getStatus(e); } this._eventStream.write({ requestId: requestId, invocationResponse: response, }); this.runInvocationRequestAfter(context); }; const { context, inputs } = CreateContextAndInputs( info, msg, logCallback, resultCallback, this._v1WorkerBehavior ); let userFunction = this._functionLoader.getFunc(<string>msg.functionId); userFunction = this.runInvocationRequestBefore(context, userFunction); // catch user errors from the same async context in the event loop and correlate with invocation // throws from asynchronous work (setTimeout, etc) are caught by 'unhandledException' and cannot be correlated with invocation try { const result = userFunction(context, ...inputs); if (result && isFunction(result.then)) { result .then((result) => { (<any>context.done)(null, result, true); }) .catch((err) => { (<any>context.done)(err, null, true); }); } } catch (err) { resultCallback(err); } } /** * Worker sends the host information identifying itself */ public startStream(requestId: string, msg: rpc.StartStream): void { // Not yet implemented } /** * Message is empty by design - Will add more fields in future if needed */ public workerHeartbeat(requestId: string, msg: rpc.WorkerHeartbeat): void { // Not yet implemented } /** * Warning before killing the process after grace_period * Worker self terminates ..no response on this */ public workerTerminate(requestId: string, msg: rpc.WorkerTerminate): void { // Not yet implemented } /** * Worker sends the host empty response to evaluate the worker's latency */ public workerStatusRequest(requestId: string, msg: rpc.WorkerStatusRequest): void { const workerStatusResponse: rpc.IWorkerStatusResponse = {}; this._eventStream.write({ requestId: requestId, workerStatusResponse, }); } /** * Host notifies worker of file content change */ public fileChangeEventRequest(requestId: string, msg: rpc.FileChangeEventRequest): void { // Not yet implemented } /** * Host requests worker to cancel invocation */ public invocationCancel(requestId: string, msg: rpc.InvocationCancel): void { // Not yet implemented } /** * Environment variables from the current process */ public functionEnvironmentReloadRequest(requestId: string, msg: rpc.IFunctionEnvironmentReloadRequest): void { // Add environment variables from incoming const numVariables = (msg.environmentVariables && Object.keys(msg.environmentVariables).length) || 0; this.log({ message: `Reloading environment variables. Found ${numVariables} variables to reload.`, level: LogLevel.Information, logCategory: LogCategory.System, }); let error = null; try { process.env = Object.assign({}, msg.environmentVariables); // Change current working directory if (msg.functionAppDirectory) { this.log({ message: `Changing current working directory to ${msg.functionAppDirectory}`, level: LogLevel.Information, logCategory: LogCategory.System, }); process.chdir(msg.functionAppDirectory); } } catch (e) { error = e; } const functionEnvironmentReloadResponse: rpc.IFunctionEnvironmentReloadResponse = { result: this.getStatus(error), }; this._eventStream.write({ requestId: requestId, functionEnvironmentReloadResponse, }); } private getStatus(err?: any, errorMessage?: string): rpc.IStatusResult { const status: rpc.IStatusResult = { status: rpc.StatusResult.Status.Success, }; if (err) { status.status = rpc.StatusResult.Status.Failure; status.exception = { message: errorMessage || err.toString(), stackTrace: err.stack, }; } return status; } private runInvocationRequestBefore(context: Context, userFunction: Function): Function { let wrappedFunction = userFunction; for (const before of this._invocationRequestBefore) { wrappedFunction = before(context, wrappedFunction); } return wrappedFunction; } private runInvocationRequestAfter(context: Context) { for (const after of this._invocationRequestAfter) { after(context); } } }
the_stack
import React from 'react'; import {Box, Flex} from 'theme-ui'; import { colors, Button, Mentions, Menu, Upload, UploadChangeParam, UploadFile, Text, Tooltip, } from '../common'; import {Message, MessageType, User} from '../../types'; import {InfoCircleOutlined, PaperClipOutlined} from '../icons'; import {env} from '../../config'; import * as API from '../../api'; import * as Storage from '../../storage'; import {DashboardShortcutsRenderer} from './DashboardShortcutsModal'; import {formatServerError} from '../../utils'; import logger from '../../logger'; const {REACT_APP_FILE_UPLOADS_ENABLED} = env; const fileUploadsEnabled = (accountId?: string) => { const enabled = REACT_APP_FILE_UPLOADS_ENABLED || ''; switch (enabled) { case '1': case 'true': return true; default: return accountId && accountId.length && enabled.includes(accountId); } }; const AttachFileButton = ({ fileList, currentUser, onUpdateFileList, }: { fileList: any; currentUser: User; onUpdateFileList: (info: UploadChangeParam) => void; }) => { // Antd takes a url to make the post request and data that gets added to the request // (See https://ant.design/components/upload/ for more information) const action = '/api/upload'; // TODO: figure out a better way to set these! const data = {account_id: currentUser.account_id, user_id: currentUser.id}; return ( <Upload className="AttachFileButton" action={action} onChange={onUpdateFileList} data={data} fileList={fileList} > <Button icon={<PaperClipOutlined />} size="small"> Attach a file </Button> </Upload> ); }; const ConversationFooter = ({ sx = {}, currentUser, conversationId, onSendMessage, }: { sx?: any; currentUser?: User | null; conversationId: string; onSendMessage?: (message: Message) => void; }) => { const textAreaEl = React.useRef<any>(null); const [message, setMessage] = React.useState<string>( Storage.getMessageDraft(conversationId) || '' ); const [fileList, setFileList] = React.useState<Array<UploadFile>>([]); const [messageType, setMessageType] = React.useState<MessageType>('reply'); const [cannedResponses, setCannedResponses] = React.useState<Array<any>>([]); const [mentions, setMentions] = React.useState<Array<string>>([]); const [mentionableUsers, setMentionableUsers] = React.useState<Array<User>>( [] ); const [prefix, setMentionPrefix] = React.useState<string>('@'); const [isSendDisabled, setSendDisabled] = React.useState<boolean>(false); const [error, setErrorMessage] = React.useState<string | null>(null); React.useEffect(() => { const el = textAreaEl.current?.textarea; if (el && Storage.getMessageDraft(conversationId)) { el.selectionStart = Storage.getMessageDraft(conversationId).length; } Promise.all([API.fetchAccountUsers(), API.fetchCannedResponses()]).then( ([users, responses]) => { setMentionableUsers(users); setCannedResponses(responses); } ); }, [conversationId]); const isPrivateNote = messageType === 'note'; const accountId = currentUser?.account_id; const shouldDisplayUploadButton = fileUploadsEnabled(accountId); const handleSetMessageType = ({key}: any) => setMessageType(key); const handleChangeMessage = (text: string) => { setMessage(text); Storage.setMessageDraft(conversationId, text); }; const getPrefixIndex = (index: number) => { for (let i = index; i >= 0; i--) { if (message[i] === '/' || message[i] === '#') { return i; } } return -1; }; const handleSelectMentionOption = (option: any, prefix: string) => { switch (prefix) { case '@': return setMentions([...new Set([...mentions, option.value])]); case '#': case '/': const el = textAreaEl.current?.textarea; const y = el?.selectionStart ?? -1; const x = getPrefixIndex(y); const response = cannedResponses.find((r) => r.name === option.value); if (el && x !== -1 && y !== -1 && response && response.content) { const update = [ message.slice(0, x), response.content, message.slice(y), ].join(''); const newCursorIndex = x + response.content.length; setMessage(update); // Slight hack to get the cursor to move to the correct spot setTimeout(() => { el.selectionStart = newCursorIndex; }, 0); } return null; default: return null; } }; const handleSearchMentions = (str: string, prefix: string) => setMentionPrefix(prefix); const handleKeyDown = (e: any) => { const {key, metaKey} = e; // Not sure what the best UX is here, but we currently allow // sending the message by pressing "cmd/metaKey + Enter" if (metaKey && key === 'Enter') { handleSendMessage(); } }; const findUserByMentionValue = (mention: string) => { return mentionableUsers.find((user) => { const {email, display_name, full_name} = user; const value = display_name || full_name || email; return mention === value; }); }; const handleSendMessage = async (e?: any) => { e && e.preventDefault(); const formattedMessageBody = mentions.reduce((result, mention) => { return result.replaceAll(`@${mention}`, `**@${mention}**`); }, message); const mentionedUsers = mentions .filter((mention) => message.includes(`@${mention}`)) .map((mention) => findUserByMentionValue(mention)) .filter((user: User | undefined): user is User => !!user); const fileIds = fileList .map((f) => f.response?.data?.id) .filter((id) => !!id); const hasEmptyBody = !formattedMessageBody || formattedMessageBody.trim().length === 0; const hasNoAttachments = !fileIds || fileIds.length === 0; if (hasEmptyBody && hasNoAttachments) { return null; } try { const message = await API.createNewMessage({ body: formattedMessageBody, type: messageType, private: isPrivateNote, conversation_id: conversationId, file_ids: fileIds, mentioned_user_ids: mentionedUsers.map((user) => user.id), metadata: { mentions: mentionedUsers, }, }); setFileList([]); setMessage(''); setErrorMessage(null); Storage.removeMessageDraft(conversationId); onSendMessage && onSendMessage(message); } catch (err) { logger.error('Error sending message!', err); setErrorMessage(formatServerError(err)); } }; const onUpdateFileList = ({file, fileList, event}: UploadChangeParam) => { setFileList(fileList); // Disable send button when file upload is in progress if (event) { setSendDisabled(true); } // Enable send button again when the server has responded if (file && file.response) { setSendDisabled(false); } }; const getMentionOptions = () => { switch (prefix) { case '@': return mentionableUsers.map(({id, email, display_name, full_name}) => { const value = display_name || full_name || email; return ( <Mentions.Option key={id} value={value}> <Box> <Text>{value}</Text> </Box> <Box> <Text type="secondary">{email}</Text> </Box> </Mentions.Option> ); }); case '#': case '/': return cannedResponses.map(({name, content}) => { return ( <Mentions.Option key={name} value={name}> <Box> <Text>{name}</Text> </Box> <Box> <Text type="secondary">{content}</Text> </Box> </Mentions.Option> ); }); default: return []; } }; return ( <Box style={{flex: '0 0 auto'}}> <Box sx={{ bg: colors.white, px: 4, pt: 0, pb: 4, ...sx, }} > <Box px={2} pb={2} pt={1} sx={{ background: isPrivateNote ? colors.noteSecondary : colors.white, border: '1px solid #f5f5f5', borderRadius: 4, boxShadow: 'rgba(0, 0, 0, 0.1) 0px 0px 8px', }} > <form onSubmit={handleSendMessage}> <Box px={2} mb={2} sx={{position: 'relative'}}> <Menu mode="horizontal" style={{ border: 'none', lineHeight: '36px', fontWeight: 500, background: 'transparent', color: colors.secondary, }} defaultSelectedKeys={['reply']} selectedKeys={[messageType]} onClick={handleSetMessageType} > <Menu.Item key="reply" style={{padding: '0 4px', marginRight: 20}} > Reply </Menu.Item> <Menu.Item key="note" style={{padding: '0 4px', marginRight: 20}} > Note </Menu.Item> </Menu> <Box sx={{position: 'absolute', right: 0, top: 0, opacity: 0.8}}> <DashboardShortcutsRenderer> {(handleOpenModal) => ( <Tooltip placement="top" title="View keyboard shortcuts"> <Button type="text" size="small" icon={<InfoCircleOutlined />} onClick={handleOpenModal} /> </Tooltip> )} </DashboardShortcutsRenderer> </Box> </Box> <Box mb={2}> {/* NB: we use the `key` prop to auto-focus the textarea when toggling `messageType` */} <Mentions key={messageType} ref={textAreaEl} className="TextArea--transparent" placeholder={ isPrivateNote ? 'Type @ to mention a teammate and they will be notified.' : 'Type / to use a saved reply.' } autoSize={{minRows: 2, maxRows: 4}} autoFocus prefix={['@', '#', '/']} value={message} notFoundContent={ <Box py={1}> {prefix === '@' ? ( <Text type="secondary">Teammate not found.</Text> ) : ( <Text type="secondary"> Not found. Create a new saved reply{' '} <a href="/saved-replies" target="_blank" rel="noopener noreferrer" > here </a> . </Text> )} </Box> } onPressEnter={handleKeyDown} onChange={handleChangeMessage} onSelect={handleSelectMentionOption} onSearch={handleSearchMentions} > {getMentionOptions()} </Mentions> </Box> {shouldDisplayUploadButton ? ( <Flex sx={{ alignItems: 'flex-end', justifyContent: 'space-between', }} > {currentUser && ( <AttachFileButton fileList={fileList} currentUser={currentUser} onUpdateFileList={onUpdateFileList} /> )} <Flex sx={{alignItems: 'flex-end'}}> {error && ( <Box mx={3}> <Text type="danger"> {error.length < 60 ? `Failed to send: ${error}` : 'Message failed to send. Try again?'} </Text> </Box> )} <Button type="primary" htmlType="submit" disabled={isSendDisabled} > Send </Button> </Flex> </Flex> ) : ( <Flex sx={{justifyContent: 'flex-end'}}> <Button type="primary" htmlType="submit" disabled={isSendDisabled} > Send </Button> </Flex> )} </form> </Box> </Box> </Box> ); }; export default ConversationFooter;
the_stack
import ui, { start as uiStart, setCameraMode, setCameraVerticalAxis, createNodeElement, setupSelectedNode, createComponentElement, setInspectorPosition, setInspectorOrientation, setInspectorScale, setInspectorVisible, setInspectorLayer, setInspectorPrefabScene, setupInspectorLayers } from "./ui"; import engine, { start as engineStart, setupHelpers } from "./engine"; import * as async from "async"; const THREE = SupEngine.THREE; import { DuplicatedNode } from "../../data/SceneAsset"; import SceneSettingsResource from "../../data/SceneSettingsResource"; import GameSettingsResource from "../../../gameSettings/data/GameSettingsResource"; import { Node } from "../../data/SceneNodes"; import { Component } from "../../data/SceneComponents"; import SceneUpdater from "../../components/SceneUpdater"; export let data: { projectClient: SupClient.ProjectClient; sceneUpdater?: SceneUpdater; gameSettingsResource?: GameSettingsResource; sceneSettingsResource?: SceneSettingsResource; }; export let socket: SocketIOClient.Socket; socket = SupClient.connect(SupClient.query.project); socket.on("welcome", onWelcome); socket.on("disconnect", SupClient.onDisconnected); let sceneSettingSubscriber: SupClient.ResourceSubscriber; let gameSettingSubscriber: SupClient.ResourceSubscriber; // TODO const onEditCommands: { [command: string]: Function; } = {}; function onWelcome() { data = { projectClient: new SupClient.ProjectClient(socket, { subEntries: true }) }; loadPlugins((err) => { data.projectClient.subResource("sceneSettings", sceneSettingSubscriber); data.projectClient.subResource("gameSettings", gameSettingSubscriber); const subscriber: SupClient.AssetSubscriber = { onAssetReceived: onSceneAssetReceived, onAssetEdited: (assetId, command, ...args) => { if (onEditCommands[command] != null) onEditCommands[command](...args); }, onAssetTrashed: SupClient.onAssetTrashed }; data.sceneUpdater = new SceneUpdater( data.projectClient, { gameInstance: engine.gameInstance, actor: null }, { sceneAssetId: SupClient.query.asset, isInPrefab: false }, subscriber ); }); } function loadPlugins(callback: (err: Error) => void) { const i18nFiles: SupClient.i18n.File[] = []; i18nFiles.push({ root: `${window.location.pathname}/../..`, name: "sceneEditor" }); SupClient.fetch(`/systems/${SupCore.system.id}/plugins.json`, "json", (err: Error, pluginsInfo: SupCore.PluginsInfo) => { for (const pluginName of pluginsInfo.list) { const root = `/systems/${SupCore.system.id}/plugins/${pluginName}`; i18nFiles.push({ root, name: "componentEditors" }); } async.parallel([ (cb) => { SupClient.i18n.load(i18nFiles, cb); }, (cb) => { async.each(pluginsInfo.list, (pluginName, cb) => { const pluginPath = `/systems/${SupCore.system.id}/plugins/${pluginName}`; async.each(["data", "components", "componentConfigs", "componentEditors"], (name, cb) => { SupClient.loadScript(`${pluginPath}/bundles/${name}.js`, cb); }, cb); }, cb); } ], callback); }); } function startIfReady() { if (data.sceneUpdater != null && data.sceneUpdater.sceneAsset != null && data.sceneSettingsResource != null && data.gameSettingsResource != null) { engineStart(); uiStart(); setCameraMode(data.sceneSettingsResource.pub.defaultCameraMode); setCameraVerticalAxis(data.sceneSettingsResource.pub.defaultVerticalAxis); setupInspectorLayers(); } } sceneSettingSubscriber = { onResourceReceived: (resourceId: string, resource: SceneSettingsResource) => { data.sceneSettingsResource = resource; startIfReady(); }, onResourceEdited: (resourceId: string, command: string, propertyName: string) => { /* Ignore */ } }; gameSettingSubscriber = { onResourceReceived: (resourceId: string, resource: GameSettingsResource) => { data.gameSettingsResource = resource; startIfReady(); }, onResourceEdited: (resourceId: string, command: string, propertyName: string) => { if (propertyName === "customLayers") setupInspectorLayers(); } }; function onSceneAssetReceived(/*err: string, asset: SceneAsset*/) { // Clear tree view ui.nodesTreeView.clearSelection(); ui.nodesTreeView.treeRoot.innerHTML = ""; const box = { x: { min: Infinity, max: -Infinity }, y: { min: Infinity, max: -Infinity }, z: { min: Infinity, max: -Infinity }, }; const pos = new THREE.Vector3(); function walk(node: Node, parentNode: Node, parentElt: HTMLLIElement) { const liElt = createNodeElement(node); ui.nodesTreeView.append(liElt, "group", parentElt); if (node.children != null && node.children.length > 0) { liElt.classList.add("collapsed"); for (const child of node.children) walk(child, node, liElt); } // Compute scene bounding box data.sceneUpdater.bySceneNodeId[node.id].actor.getGlobalPosition(pos); box.x.min = Math.min(box.x.min, pos.x); box.x.max = Math.max(box.x.max, pos.x); box.y.min = Math.min(box.y.min, pos.y); box.y.max = Math.max(box.y.max, pos.y); box.z.min = Math.min(box.z.min, pos.z); box.z.max = Math.max(box.z.max, pos.z); } for (const node of data.sceneUpdater.sceneAsset.nodes.pub) walk(node, null, null); // Place camera so that it fits the scene if (data.sceneUpdater.sceneAsset.nodes.pub.length > 0) { const z = box.z.max + 10; engine.cameraActor.setLocalPosition(new THREE.Vector3((box.x.min + box.x.max) / 2, (box.y.min + box.y.max) / 2, z)); ui.camera2DZ.value = z.toString(); } startIfReady(); } const addNode = onEditCommands["addNode"] = (node: Node, parentId: string, index: number) => { const nodeElt = createNodeElement(node); let parentElt: HTMLLIElement; if (parentId != null) parentElt = ui.nodesTreeView.treeRoot.querySelector(`[data-id='${parentId}']`) as HTMLLIElement; ui.nodesTreeView.insertAt(nodeElt, "group", index, parentElt); }; onEditCommands["moveNode"] = (id: string, parentId: string, index: number) => { // Reparent tree node const nodeElt = ui.nodesTreeView.treeRoot.querySelector(`[data-id='${id}']`) as HTMLLIElement; const isInspected = ui.nodesTreeView.selectedNodes.length === 1 && nodeElt === ui.nodesTreeView.selectedNodes[0]; let parentElt: HTMLLIElement; if (parentId != null) parentElt = ui.nodesTreeView.treeRoot.querySelector(`[data-id='${parentId}']`) as HTMLLIElement; ui.nodesTreeView.insertAt(nodeElt, "group", index, parentElt); // Refresh inspector if (isInspected) { const node = data.sceneUpdater.sceneAsset.nodes.byId[id]; setInspectorPosition(<THREE.Vector3>node.position); setInspectorOrientation(<THREE.Quaternion>node.orientation); setInspectorScale(<THREE.Vector3>node.scale); } // TODO: Only refresh if selection is affected setupHelpers(); }; onEditCommands["setNodeProperty"] = (id: string, path: string, value: any) => { const nodeElt = ui.nodesTreeView.treeRoot.querySelector(`[data-id='${id}']`); const isInspected = ui.nodesTreeView.selectedNodes.length === 1 && nodeElt === ui.nodesTreeView.selectedNodes[0]; const node = data.sceneUpdater.sceneAsset.nodes.byId[id]; switch (path) { case "name": nodeElt.querySelector(".name").textContent = value; break; case "position": if (isInspected) setInspectorPosition(<THREE.Vector3>node.position); break; case "orientation": if (isInspected) setInspectorOrientation(<THREE.Quaternion>node.orientation); break; case "scale": if (isInspected) setInspectorScale(<THREE.Vector3>node.scale); break; case "visible": if (isInspected) setInspectorVisible(value); break; case "layer": if (isInspected) setInspectorLayer(value); break; case "prefab.sceneAssetId": if (isInspected) setInspectorPrefabScene(value); break; } // TODO: Only refresh if selection is affected setupHelpers(); }; onEditCommands["duplicateNode"] = (rootNode: Node, newNodes: DuplicatedNode[]) => { for (const newNode of newNodes) addNode(newNode.node, newNode.parentId, newNode.index); // TODO: Only refresh if selection is affected setupHelpers(); }; onEditCommands["removeNode"] = (id: string) => { const nodeElt = ui.nodesTreeView.treeRoot.querySelector(`[data-id='${id}']`) as HTMLLIElement; const isInspected = ui.nodesTreeView.selectedNodes.length === 1 && nodeElt === ui.nodesTreeView.selectedNodes[0]; ui.nodesTreeView.remove(nodeElt); if (isInspected) setupSelectedNode(); // TODO: Only refresh if selection is affected else setupHelpers(); }; onEditCommands["addComponent"] = (nodeComponent: Component, nodeId: string, index: number) => { const isInspected = ui.nodesTreeView.selectedNodes.length === 1 && nodeId === ui.nodesTreeView.selectedNodes[0].dataset["id"]; if (isInspected) { const componentElt = createComponentElement(nodeId, nodeComponent); // TODO: Take index into account ui.inspectorElt.querySelector(".components").appendChild(componentElt); } // TODO: Only refresh if selection is affected setupHelpers(); }; onEditCommands["editComponent"] = (nodeId: string, componentId: string, command: string, ...args: any[]) => { const isInspected = ui.nodesTreeView.selectedNodes.length === 1 && nodeId === ui.nodesTreeView.selectedNodes[0].dataset["id"]; if (isInspected) { const componentEditor = ui.componentEditors[componentId]; const commandFunction = (componentEditor as any)[`config_${command}`]; if (commandFunction != null) commandFunction.apply(componentEditor, args); } // TODO: Only refresh if selection is affected setupHelpers(); }; onEditCommands["removeComponent"] = (nodeId: string, componentId: string) => { const isInspected = ui.nodesTreeView.selectedNodes.length === 1 && nodeId === ui.nodesTreeView.selectedNodes[0].dataset["id"]; if (isInspected) { ui.componentEditors[componentId].destroy(); delete ui.componentEditors[componentId]; const componentElt = <HTMLDivElement>ui.inspectorElt.querySelector(`.components > div[data-component-id='${componentId}']`); componentElt.parentElement.removeChild(componentElt); } // TODO: Only refresh if selection is affected setupHelpers(); };
the_stack
import * as Clutter from 'clutter'; import { Text } from 'clutter'; import * as Gio from 'gio'; import * as GLib from 'glib'; import * as GObject from 'gobject'; import * as Shell from 'shell'; import { Async } from 'src/utils/async'; import { registerGObjectClass } from 'src/utils/gjs'; import { MatButton } from 'src/widget/material/button'; import * as St from 'st'; import { appDisplay, remoteSearch } from 'ui'; const DND = imports.ui.dnd; const ShellEntry = imports.ui.shellEntry; const ParentalControlsManager = imports.misc.parentalControlsManager; const SystemActions = imports.misc.systemActions; function getTermsForSearchString(searchString: string): string[] { searchString = searchString.replace(/^\s+/g, '').replace(/\s+$/g, ''); if (searchString === '') return []; return searchString.split(/\s+/); } const SEARCH_PROVIDERS_SCHEMA = 'org.gnome.desktop.search-providers'; /** Extension imports */ const Me = imports.misc.extensionUtils.getCurrentExtension(); type SearchProvider = | appDisplay.AppSearchProvider | remoteSearch.RemoteSearchProvider; @registerGObjectClass export class SearchResultHeader extends St.Bin { static metaInfo: GObject.MetaInfo = { GTypeName: 'SearchResultHeader', }; label: St.Label; constructor(text: string) { super({ style_class: 'subtitle-2 margin margin-top-x2 margin-bottom-x2 text-high-emphasis', }); this.label = new St.Label({ text: text, }); this.set_child(this.label); } } @registerGObjectClass export class SearchResultEntry extends MatButton { static metaInfo: GObject.MetaInfo = { GTypeName: 'SearchResultEntry', Signals: { activate: { param_types: [], accumulator: 0, }, }, }; layout = new St.BoxLayout(); icon: St.Icon | null; textLayout = new St.BoxLayout({ vertical: true, styleClass: 'margin-left-x2 margin-top margin-bottom margin-right-x2', y_align: Clutter.ActorAlign.CENTER, }); title: St.Label; description: St.Label | null; constructor( icon: St.Icon | null, title: string, description?: string, withMenu?: boolean ) { super({}); if (icon) { this.icon = icon; this.icon.set_style('margin: 12px'); this.layout.add_child(this.icon); } else { this.icon = null; } this.layout.add_child(this.textLayout); this.title = new St.Label({ text: title, }); this.textLayout.add_child(this.title); if (description) { this.description = new St.Label({ text: description, styleClass: 'caption', style: 'margin-top:2px', }); this.textLayout.add_child(this.description); } else { this.description = null; } this.set_child(this.layout); /* if (withMenu) { this.menuManager = new PopupMenu.PopupMenuManager(this); this.menu = new AppDisplay.AppIconMenu(this, St.Side.RIGHT); } */ } setSelected(selected: boolean) { if (selected) { this.add_style_class_name('highlighted'); } else { this.remove_style_class_name('highlighted'); } } } @registerGObjectClass export class SearchResultList extends St.BoxLayout { static metaInfo: GObject.MetaInfo = { GTypeName: 'SearchResultList', Signals: { 'result-selected-changed': { param_types: [SearchResultEntry.$gtype], accumulator: 0, }, }, }; searchEntry: St.Entry; text: Text; parentalControlsManager; providers: SearchProvider[] = []; searchSettings; terms: string[] = []; private searchTimeoutId = 0; startingSearch = false; private results: Record<string, string[]> = {}; isSubSearch = false; cancellable = new Gio.Cancellable(); clearIcon = new St.Icon({ style_class: 'search-entry-icon', icon_name: 'edit-clear-symbolic', }); iconClickedId = 0; resMetas: any; entrySelected: SearchResultEntry | null = null; constructor(searchEntry: St.Entry) { super({ style_class: 'search-result-list', vertical: true, }); this.searchEntry = searchEntry; ShellEntry.addContextMenu(this.searchEntry); this.text = this.searchEntry.clutter_text; this.text.connect('text-changed', this.onTextChanged.bind(this)); // Note: Clutter typedefs seem to be incorrect. According to the docs `ev` should be a Clutter.KeyEvent, but it actually seems to be a Clutter.Event. this.text.connect('key-press-event', this.onKeyPress.bind(this)); this.text.connect('key-focus-in', () => {}); this.text.connect('key-focus-out', () => {}); this.searchEntry.connect('popup-menu', () => { /* if (!this._searchActive) return; this._entry.menu.close(); this._searchResults.popupMenuDefault(); */ }); this.parentalControlsManager = ParentalControlsManager.getDefault(); this.parentalControlsManager.connect( 'app-filter-changed', this.reloadRemoteProviders.bind(this) ); this.searchSettings = new Gio.Settings({ schema_id: SEARCH_PROVIDERS_SCHEMA, }); this.searchSettings.connect( 'changed::disabled', this.reloadRemoteProviders.bind(this) ); this.searchSettings.connect( 'changed::enabled', this.reloadRemoteProviders.bind(this) ); this.searchSettings.connect( 'changed::disable-external', this.reloadRemoteProviders.bind(this) ); this.searchSettings.connect( 'changed::sort-order', this.reloadRemoteProviders.bind(this) ); this.registerProvider(new appDisplay.AppSearchProvider()); const appSystem = Shell.AppSystem.get_default(); appSystem.connect( 'installed-changed', this.reloadRemoteProviders.bind(this) ); this.reloadRemoteProviders(); } get resultEntryList() { return this.get_children().filter( (actor) => actor instanceof SearchResultEntry ) as SearchResultEntry[]; } registerProvider(provider: SearchProvider): void { provider.searchInProgress = false; // Filter out unwanted providers. if ( provider.isRemoteProvider && !this.parentalControlsManager.shouldShowApp(provider.appInfo) ) return; this.providers.push(provider); } reloadRemoteProviders(): void { const remoteProviders = this.providers.filter( (p) => p.isRemoteProvider ); remoteProviders.forEach((provider) => { this.unregisterProvider(provider); }); remoteSearch.loadRemoteSearchProviders( this.searchSettings, (providers) => { providers.forEach(this.registerProvider.bind(this)); } ); } unregisterProvider(provider: SearchProvider): void { const index = this.providers.indexOf(provider); this.providers.splice(index, 1); if (provider.display) provider.display.destroy(); } onTextChanged(): void { const terms = getTermsForSearchString(this.searchEntry.get_text()); const searchActive = terms.length > 0; this.setTerms(terms); if (searchActive) { this.searchEntry.set_secondary_icon(this.clearIcon); if (this.iconClickedId === 0) { this.iconClickedId = this.searchEntry.connect( 'secondary-icon-clicked', () => { this.reset(); } ); } } else { if (this.iconClickedId > 0) { this.searchEntry.disconnect(this.iconClickedId); this.iconClickedId = 0; } this.searchEntry.set_secondary_icon(null); this.searchCancelled(); } } onKeyPress(entry: Clutter.Actor, event: Clutter.Event) { const symbol = event.get_key_symbol(); if (symbol === Clutter.KEY_Escape) { this.resetAndClose(); return Clutter.EVENT_STOP; } else { let arrowNext, nextDirection; if (symbol === Clutter.KEY_Tab) { this.selectNext(); return Clutter.EVENT_STOP; } else if (symbol === Clutter.KEY_ISO_Left_Tab) { this.selectPrevious(); return Clutter.EVENT_STOP; } else if (symbol === Clutter.KEY_Down) { this.selectNext(); return Clutter.EVENT_STOP; } else if (symbol === Clutter.KEY_Up) { this.selectPrevious(); return Clutter.EVENT_STOP; } else if ( symbol === Clutter.KEY_Return || symbol === Clutter.KEY_KP_Enter ) { if (this.entrySelected !== null) { this.entrySelected.emit('primary-action'); } return Clutter.EVENT_STOP; } } return Clutter.EVENT_PROPAGATE; } private doSearch() { this.startingSearch = false; const previousResults = this.results; this.results = {}; this.entrySelected = null; this.remove_all_children(); this.providers.forEach((provider) => { provider.searchInProgress = true; const previousProviderResults = previousResults[provider.id]; if (this.isSubSearch && previousProviderResults) { provider.getSubsearchResultSet( previousProviderResults, this.terms, (results) => { this.gotResults(results, provider); }, this.cancellable ); } else { provider.getInitialResultSet( this.terms, (results) => { this.gotResults(results, provider); }, this.cancellable ); } }); this.clearSearchTimeout(); } private clearSearchTimeout() { if (this.searchTimeoutId > 0) { Async.clearTimeoutId(this.searchTimeoutId); this.searchTimeoutId = 0; } } private onSearchTimeout() { this.searchTimeoutId = 0; this.doSearch(); } private searchCancelled() { // Leave the entry focused when it doesn't have any text; // when replacing a selected search term, Clutter emits // two 'text-changed' signals, one for deleting the previous // text and one for the new one - the second one is handled // incorrectly when we remove focus // (https://bugzilla.gnome.org/show_bug.cgi?id=636341) */ if (this.text.text !== '') this.reset(); } setTerms(terms: string[]): void { // Check for the case of making a duplicate previous search before // setting state of the current search or cancelling the search. // This will prevent incorrect state being as a result of a duplicate // search while the previous search is still active. const searchString = terms.join(' '); const previousSearchString = this.terms.join(' '); if (searchString == previousSearchString) return; this.startingSearch = true; this.cancellable.cancel(); this.cancellable.reset(); if (terms.length == 0) { this.reset(); return; } let isSubSearch = false; if (this.terms.length > 0) isSubSearch = searchString.indexOf(previousSearchString) == 0; this.terms = terms; this.isSubSearch = isSubSearch; //this._updateSearchProgress(); if (this.searchTimeoutId == 0) this.searchTimeoutId = Async.addTimeout( GLib.PRIORITY_DEFAULT, 150, this.onSearchTimeout.bind(this) ); const escapedTerms = this.terms.map((term) => Shell.util_regex_escape(term) ); //this.emit('terms-changed'); } gotResults(results: string[], provider: SearchProvider) { this.results[provider.id] = results; this.updateResults(provider, results); } updateResults(provider: SearchProvider, results: string[]) { if (!results.length) return; if (provider.isRemoteProvider) { this.add_child(new SearchResultHeader(provider.appInfo.get_name())); } else { this.add_child(new SearchResultHeader(_('Applications'))); } // Note: The remote search provider also provides a description field, but the app search does not const onSearchMetas = ( resMetas: { id: string; name: string; description?: string; createIcon: (size: number) => St.Icon; }[] ) => { this.resMetas = resMetas; let moreEntry: SearchResultEntry | null = null; // const extraResults: SearchResultEntry[] = []; if (resMetas.length > 5) { const more = (moreEntry = new SearchResultEntry( new St.Icon({ icon_size: 32, gicon: Gio.icon_new_for_string( `${Me.path}/assets/icons/chevron-down-symbolic.svg` ), }), ngettext('%d more', '%d more', resMetas.length - 5).format( resMetas.length - 5 ), '', provider.id === 'applications' )); more.connect('primary-action', () => { extraResults.forEach((entry) => { this.insert_child_below(entry, more); }); this.remove_child(more); this.selectResult(extraResults[0]); }); } let numberOfRes = 0; for (const res of resMetas) { if (!res.name) return; numberOfRes++; let icon = res.createIcon(32); if (!icon && provider.isRemoteProvider) { icon = new St.Icon({ icon_size: 32, gicon: provider.appInfo.get_icon(), }); } const entry = new SearchResultEntry( icon, res.name, // The remote search provider also provides a description field, but the app search does not res.description, provider.id === 'applications' ); entry.connect('primary-action', () => { if (provider.isRemoteProvider) { provider.activateResult(res.id, this.terms); } else { const app = Shell.AppSystem.get_default().lookup_app( res.id ); if (app) { if (app.can_open_new_window()) { const { msWindow } = Me.msWindowManager.createNewMsWindow(app, { msWorkspace: Me.msWorkspaceManager.getActiveMsWorkspace(), focus: true, insert: true, }); Me.msWindowManager.openAppForMsWindow(msWindow); } else { app.activate(); } } else { SystemActions.getDefault().activateAction(res.id); } } this.resetAndClose(); }); if (numberOfRes <= 5) { this.addResult(entry); } else { extraResults.push(entry); } } if (moreEntry) { this.addResult(moreEntry); } }; if (provider.isRemoteProvider) { provider.getResultMetas(results, onSearchMetas, this.cancellable); } else { provider.getResultMetas(results, onSearchMetas); } /* display.updateSearch(results, terms, () => { provider.searchInProgress = false; this._maybeSetInitialSelection(); this._updateSearchProgress(); }); */ } addResult(resultEntry: SearchResultEntry): void { this.add_child(resultEntry); if (this.resultEntryList.length === 1) { this.selectResult(resultEntry); } } selectResult(entry: SearchResultEntry): void { if (this.entrySelected) { this.entrySelected.setSelected(false); } this.entrySelected = entry; this.entrySelected.setSelected(true); this.emit('result-selected-changed', this.entrySelected); } selectNext() { const currentIndex = this.entrySelected !== null ? this.resultEntryList.indexOf(this.entrySelected) : -1; const nextEntry = this.resultEntryList[currentIndex + 1]; if (nextEntry) { this.selectResult(nextEntry); } } selectPrevious() { const currentIndex = this.entrySelected !== null ? this.resultEntryList.indexOf(this.entrySelected) : -1; const previousEntry = this.resultEntryList[currentIndex - 1]; if (previousEntry) { this.selectResult(previousEntry); } } reset() { this.searchEntry.text = ''; this.terms = []; this.results = {}; this.entrySelected = null; this.remove_all_children(); this.clearSearchTimeout(); this.startingSearch = false; } resetAndClose() { this.reset(); Me.layout.toggleOverview(); } }
the_stack
import { jsx } from '@emotion/react' import React from 'react' import { DeviceInfo, deviceInfoList } from '../../common/devices' import { BASE_URL, FLOATING_PREVIEW_BASE_URL } from '../../common/env-vars' import { useEditorState } from '../editor/store/store-hook' import { SelectOption } from '../inspector/controls/select-control' import { isTextFile, TextFile, ProjectContents } from '../../core/shared/project-file-types' import { objectKeyParser, parseString } from '../../utils/value-parser-utils' import { eitherToMaybe } from '../../core/shared/either' import { shareURLForProject } from '../../core/shared/utils' import { getMainJSFilename } from '../../core/shared/project-contents-utils' import { ProjectContentTreeRoot } from '../assets' import { FlexRow, Button, //TODO: switch to functional component and make use of 'useColorTheme': colorTheme, FlexColumn, UtopiaTheme, SquareButton, LargerIcons, Subdued, PopupList, Icn, UIRow, } from '../../uuiui' import { setBranchNameFromURL } from '../../utils/branches' export const PreviewIframeId = 'preview-column-container' export interface ProjectContentsUpdateMessage { type: 'PROJECT_CONTENTS_UPDATE' projectContents: ProjectContentTreeRoot } export function projectContentsUpdateMessage( projectContents: ProjectContentTreeRoot, ): ProjectContentsUpdateMessage { return { type: 'PROJECT_CONTENTS_UPDATE', projectContents: projectContents, } } export function isProjectContentsUpdateMessage( data: unknown, ): data is ProjectContentsUpdateMessage { return ( data != null && typeof data === 'object' && !Array.isArray(data) && (data as ProjectContentsUpdateMessage).type === 'PROJECT_CONTENTS_UPDATE' ) } interface IntermediatePreviewColumnProps { id: string | null projectName: string connected: boolean packageJSONFile: TextFile | null } export interface PreviewColumnProps { id: string | null projectName: string connected: boolean editedFilename: string | null } export interface PreviewColumnState { selectedBackgroundOptionIndex: number running: boolean useDevice: boolean scale: number selectedScaleOption: number deviceInfo: DeviceInfo rotated: boolean refreshCount: number width: number height: number } export const PreviewColumn = React.memo(() => { const { id, projectName, connected, mainJSFilename } = useEditorState((store) => { return { id: store.editor.id, projectName: store.editor.projectName, connected: store.editor.preview.connected, mainJSFilename: getMainJSFilename(store.editor.projectContents), } }, 'PreviewColumn') return ( <PreviewColumnContent id={id} projectName={projectName} connected={connected} editedFilename={mainJSFilename} /> ) }) PreviewColumn.displayName = 'PreviewColumn' class PreviewColumnContent extends React.Component<PreviewColumnProps, PreviewColumnState> { scaleOptions: number[] scaleDropdownOptions: any backgroundOptions: any constructor(props: PreviewColumnProps) { super(props) this.scaleOptions = [0.25, 0.5, 0.67, 1, 1.25, 1.5, 2, 3, 4] this.backgroundOptions = [ { label: 'White', value: { backgroundColor: '#ffffff' }, }, { label: 'Checkerboard (light)', value: { backgroundImage: 'linear-gradient(45deg, #d4d4d4 25%, transparent 25%), linear-gradient(-45deg, #d4d4d4 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #d4d4d4 75%), linear-gradient(-45deg, transparent 75%, #d4d4d4 75%)', backgroundSize: '10px 10px', backgroundPosition: '0 0, 0 5px, 5px -5px, -5px 0px', }, }, { label: 'Light Grey', value: { backgroundColor: '#f4f4f4' }, }, { label: 'Mid Grey', value: { backgroundColor: '#888888' }, }, { label: 'Dark Grey', value: { backgroundColor: '#333' } }, { label: 'Black', value: { backgroundColor: '#000' } }, ] this.scaleDropdownOptions = this.scaleOptions.map((s) => ({ value: s, label: `${Math.round(s * 100)}%`, })) this.state = { selectedBackgroundOptionIndex: 0, running: true, useDevice: false, scale: 1, selectedScaleOption: 4, deviceInfo: deviceInfoList.iPhoneXS, rotated: false, refreshCount: 0, width: deviceInfoList.iPhoneXS.width as number, height: deviceInfoList.iPhoneXS.height as number, } } scaleDown = () => { this.setState((prevState) => ({ scale: Math.max(0.25, prevState.scale * 0.5) })) } scaleUp = () => { this.setState((prevState) => ({ scale: Math.min(8, prevState.scale * 2) })) } setSelectedValue = (selectedValue: SelectOption) => this.setState({ scale: selectedValue.value }) onRestartClick = () => { this.setState((prevState) => ({ refreshCount: prevState.refreshCount + 1, })) } handleKeyPress = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { e.stopPropagation() this.onRestartClick() } } toggleRunning = () => { this.setState((prevState) => ({ running: !prevState.running })) } render() { const ColorButtonGroup = () => ( <FlexRow css={{ marginLeft: 4, marginRight: 4, '& > *': { marginRight: 8, }, }} > {this.backgroundOptions.map((background: any, i: number) => ( <Button key={`colorbutton${i}`} // eslint-disable-next-line react/jsx-no-bind onClick={() => this.setState(() => ({ selectedBackgroundOptionIndex: i }))} > <div style={{ width: 18, height: 18, borderRadius: '50%', border: i === this.state.selectedBackgroundOptionIndex ? `1px solid ${colorTheme.primary.value}` : `1px solid ${colorTheme.secondaryBorder.value}`, ...background.value, }} /> </Button> ))} </FlexRow> ) function addInBranchNames(url: string): string { if (url === '') { return url } else { const parsedURL = new URL(url) setBranchNameFromURL(parsedURL.searchParams) return parsedURL.toString() } } let floatingPreviewURL = this.props.id == null ? '' : shareURLForProject(FLOATING_PREVIEW_BASE_URL, this.props.id, this.props.projectName) floatingPreviewURL = addInBranchNames(floatingPreviewURL) let iframePreviewURL = this.props.id == null ? '' : `${floatingPreviewURL}?embedded=true&refreshCount=${this.state.refreshCount}` iframePreviewURL = addInBranchNames(iframePreviewURL) let popoutPreviewURL = this.props.id == null ? '' : shareURLForProject(BASE_URL, this.props.id, this.props.projectName) popoutPreviewURL = addInBranchNames(popoutPreviewURL) const iFrame = ( <iframe key={PreviewIframeId} id={PreviewIframeId} width={this.state.useDevice ? this.state.width : '100%'} height={this.state.useDevice ? this.state.height : '100%'} src={iframePreviewURL} allow='autoplay' style={{ backgroundColor: 'transparent', width: this.state.useDevice ? this.state.width : '100%', height: this.state.useDevice ? this.state.height : '100%', borderWidth: 0, transform: `scale(${this.state.scale})`, transformOrigin: 'top left', }} /> ) return ( <FlexColumn style={{ height: '100%', overflow: 'scroll', }} > <UIRow rowHeight={'normal'} css={{ flexShrink: 0, paddingLeft: 4, paddingRight: 4, overflowX: 'scroll', '& > *': { marginRight: 8, }, }} > <SquareButton highlight onClick={this.onRestartClick}> <LargerIcons.Refresh /> </SquareButton> <input onKeyPress={this.handleKeyPress} value={popoutPreviewURL} css={{ fontSize: 11, borderRadius: '20px', height: 23, fontFamily: 'utopian-inter', transition: 'all .2s ease-in-out', padding: '2px 8px', border: '1px solid transparent', background: colorTheme.secondaryBackground.value, minWidth: 240, '&:focus': { background: 'white', border: `1px solid ${colorTheme.primary.value}`, }, }} /> {this.props.editedFilename == null ? null : ( <Subdued>{this.props.editedFilename}</Subdued> )} <SquareButton highlight onClick={this.toggleRunning}> {this.state.running ? <LargerIcons.StopButton /> : <LargerIcons.PlayButton />} </SquareButton> <a target='_blank' rel='noopener noreferrer' href={floatingPreviewURL}> <SquareButton highlight> <LargerIcons.ExternalLink /> </SquareButton> </a> </UIRow> <UIRow className='preview-menu' rowHeight={'normal'} style={{ borderBottom: `1px solid ${colorTheme.subduedBorder.value}`, flexShrink: 0, flexGrow: 0, }} > <UIRow rowHeight={'normal'} css={{ flexShrink: 0, paddingLeft: 4, paddingRight: 4, overflowX: 'scroll', '& > *': { marginRight: 8, }, }} > <SquareButton highlight disabled={!this.state.running || this.state.scale <= 0.25} onMouseUp={this.scaleDown} > <LargerIcons.MagnifyingGlassMinus /> </SquareButton> <PopupList style={{ minWidth: 56 }} value={{ value: this.state.scale, label: `${Math.round(this.state.scale * 100)}%`, }} onSubmitValue={this.setSelectedValue} options={this.scaleDropdownOptions} containerMode='noBorder' /> <SquareButton highlight disabled={!this.state.running || this.state.scale >= 4} onClick={this.scaleUp} > <LargerIcons.MagnifyingGlassPlus /> </SquareButton> <LargerIcons.Divider width={5} height={18} style={{ marginLeft: 4, marginRight: 8 }} /> <ColorButtonGroup /> </UIRow> </UIRow> <FlexRow style={{ ...this.backgroundOptions[this.state.selectedBackgroundOptionIndex].value, justifyContent: 'flex-start', alignItems: 'flex-start', flexGrow: 1, flexShrink: 0, }} > {this.state.running ? ( iFrame ) : ( <FlexColumn style={{ justifyContent: 'center', alignItems: 'center', flexGrow: 1, flexShrink: 0, height: '100%', backgroundColor: colorTheme.secondaryBackground.value, }} > <Button onClick={this.toggleRunning} spotlight> <Icn category='semantic' type='playbutton' width={24} height={24} /> </Button> <Subdued style={{ marginTop: 8 }}>Start Preview</Subdued> </FlexColumn> )} </FlexRow> </FlexColumn> ) } }
the_stack
import dedent from 'dedent'; import { format } from 'prettier/standalone'; import { collectCss } from '../helpers/collect-styles'; import { fastClone } from '../helpers/fast-clone'; import { getMemberObjectString, getStateObjectStringFromComponent, } from '../helpers/get-state-object-string'; import { mapRefs } from '../helpers/map-refs'; import { renderPreComponent } from '../helpers/render-imports'; import { stripStateAndPropsRefs } from '../helpers/strip-state-and-props-refs'; import { getProps } from '../helpers/get-props'; import { selfClosingTags } from '../parsers/jsx'; import { MitosisComponent } from '../types/mitosis-component'; import { MitosisNode } from '../types/mitosis-node'; import { Plugin, runPostCodePlugins, runPostJsonPlugins, runPreCodePlugins, runPreJsonPlugins, } from '../modules/plugins'; import isChildren from '../helpers/is-children'; import { stripMetaProperties } from '../helpers/strip-meta-properties'; import { removeSurroundingBlock } from '../helpers/remove-surrounding-block'; import { isMitosisNode } from '../helpers/is-mitosis-node'; import traverse from 'traverse'; import { getComponentsUsed } from '../helpers/get-components-used'; import { first, kebabCase, size } from 'lodash'; import { replaceIdentifiers } from '../helpers/replace-idenifiers'; import { filterEmptyTextNodes } from '../helpers/filter-empty-text-nodes'; import json5 from 'json5'; import { processHttpRequests } from '../helpers/process-http-requests'; export type ToVueOptions = { prettier?: boolean; plugins?: Plugin[]; vueVersion?: 2 | 3; cssNamespace?: string; namePrefix?: string; builderRegister?: boolean; }; function getContextNames(json: MitosisComponent) { return Object.keys(json.context.get); } // TODO: migrate all stripStateAndPropsRefs to use this here // to properly replace context refs function processBinding( code: string, _options: ToVueOptions, json: MitosisComponent, ): string { return replaceIdentifiers( stripStateAndPropsRefs(code, { includeState: true, includeProps: true, replaceWith: 'this.', }), getContextNames(json), (name) => `this.${name}`, ); } const NODE_MAPPERS: { [key: string]: | ((json: MitosisNode, options: ToVueOptions) => string) | undefined; } = { Fragment(json, options) { return json.children.map((item) => blockToVue(item, options)).join('\n'); }, For(json, options) { const keyValue = json.bindings.key || 'index'; const forValue = `(${ json.properties._forName }, index) in ${stripStateAndPropsRefs(json.bindings.each as string)}`; if (options.vueVersion! >= 3) { // TODO: tmk key goes on different element (parent vs child) based on Vue 2 vs Vue 3 return `<template :key="${keyValue}" v-for="${forValue}"> ${json.children.map((item) => blockToVue(item, options)).join('\n')} </template>`; } // Vue 2 can only handle one root element const firstChild = json.children.filter(filterEmptyTextNodes)[0]; if (!firstChild) { return ''; } firstChild.bindings.key = keyValue; firstChild.properties['v-for'] = forValue; return blockToVue(firstChild, options); }, Show(json, options) { const ifValue = stripStateAndPropsRefs(json.bindings.when as string); if (options.vueVersion! >= 3) { return ` <template v-if="${ifValue}"> ${json.children.map((item) => blockToVue(item, options)).join('\n')} </template> ${ !json.meta.else ? '' : ` <template v-else> ${blockToVue(json.meta.else as any, options)} </template> ` } `; } let ifString = ''; // Vue 2 can only handle one root element const firstChild = json.children.filter(filterEmptyTextNodes)[0]; if (firstChild) { firstChild.properties['v-if'] = ifValue; ifString = blockToVue(firstChild, options); } let elseString = ''; const elseBlock = json.meta.else; if (isMitosisNode(elseBlock)) { elseBlock.properties['v-else'] = ''; elseString = blockToVue(elseBlock, options); } return ` ${ifString} ${elseString} `; }, }; // TODO: Maybe in the future allow defining `string | function` as values const BINDING_MAPPERS: { [key: string]: string | undefined } = { innerHTML: 'v-html', }; // Transform <foo.bar key="value" /> to <component :is="foo.bar" key="value" /> function processDynamicComponents( json: MitosisComponent, options: ToVueOptions, ) { traverse(json).forEach((node) => { if (isMitosisNode(node)) { if (node.name.includes('.')) { node.bindings.is = node.name; node.name = 'component'; } } }); } function processForKeys(json: MitosisComponent, options: ToVueOptions) { traverse(json).forEach((node) => { if (isMitosisNode(node)) { if (node.name === 'For') { const firstChild = node.children[0]; if (firstChild && firstChild.bindings.key) { node.bindings.key = firstChild.bindings.key; delete firstChild.bindings.key; } } } }); } export const blockToVue = ( node: MitosisNode, options: ToVueOptions, ): string => { const nodeMapper = NODE_MAPPERS[node.name]; if (nodeMapper) { return nodeMapper(node, options); } if (isChildren(node)) { return `<slot></slot>`; } if (node.name === 'style') { // Vue doesn't allow <style>...</style> in templates, but does support the synonymous // <component is="style">...</component> node.name = 'component'; node.properties.is = 'style'; } if (node.properties._text) { return `${node.properties._text}`; } if (node.bindings._text) { return `{{${stripStateAndPropsRefs(node.bindings._text as string)}}}`; } let str = ''; str += `<${node.name} `; if (node.bindings._spread) { str += `v-bind="${stripStateAndPropsRefs( node.bindings._spread as string, )}"`; } for (const key in node.properties) { const value = node.properties[key]; str += ` ${key}="${value}" `; } for (const key in node.bindings) { if (key === '_spread') { continue; } const value = node.bindings[key] as string; if (key === 'class') { str += ` :class="_classStringToObject(${stripStateAndPropsRefs(value, { replaceWith: 'this.', })})" `; // TODO: support dynamic classes as objects somehow like Vue requires // https://vuejs.org/v2/guide/class-and-style.html continue; } // TODO: proper babel transform to replace. Util for this const useValue = stripStateAndPropsRefs(value); if (key.startsWith('on')) { let event = key.replace('on', '').toLowerCase(); if (event === 'change' && node.name === 'input') { event = 'input'; } // TODO: proper babel transform to replace. Util for this str += ` @${event}="${removeSurroundingBlock( useValue // TODO: proper reference parse and replacing .replace(/event\./g, '$event.'), )}" `; } else if (key === 'ref') { str += ` ref="${useValue}" `; } else if (BINDING_MAPPERS[key]) { str += ` ${BINDING_MAPPERS[key]}="${useValue}" `; } else { str += ` :${key}="${useValue}" `; } } if (selfClosingTags.has(node.name)) { return str + ' />'; } str += '>'; if (node.children) { str += node.children.map((item) => blockToVue(item, options)).join(''); } return str + `</${node.name}>`; }; function getContextInjectString( component: MitosisComponent, options: ToVueOptions, ) { let str = '{'; for (const key in component.context.get) { str += ` ${key}: "${component.context.get[key].name}", `; } str += '}'; return str; } function getContextProvideString( component: MitosisComponent, options: ToVueOptions, ) { let str = '{'; for (const key in component.context.set) { const { value, name } = component.context.set[key]; str += ` ${name}: ${ value ? getMemberObjectString(value, { valueMapper: (code) => stripStateAndPropsRefs(code, { replaceWith: '_this.' }), }) : null }, `; } str += '}'; return str; } export const componentToVue = ( component: MitosisComponent, options: ToVueOptions = {}, ) => { // Make a copy we can safely mutate, similar to babel's toolchain can be used component = fastClone(component); processHttpRequests(component); processDynamicComponents(component, options); processForKeys(component, options); if (options.plugins) { component = runPreJsonPlugins(component, options.plugins); } mapRefs(component, (refName) => `this.$refs.${refName}`); if (options.plugins) { component = runPostJsonPlugins(component, options.plugins); } const css = collectCss(component, { prefix: options.cssNamespace, }); let dataString = getStateObjectStringFromComponent(component, { data: true, functions: false, getters: false, }); const getterString = getStateObjectStringFromComponent(component, { data: false, getters: true, functions: false, valueMapper: (code) => processBinding(code.replace(/^get /, ''), options, component), }); let functionsString = getStateObjectStringFromComponent(component, { data: false, getters: false, functions: true, valueMapper: (code) => processBinding(code, options, component), }); const blocksString = JSON.stringify(component.children); // Component references to include in `component: { YourComponent, ... } const componentsUsed = Array.from(getComponentsUsed(component)) .filter( (name) => name.length && !name.includes('.') && name[0].toUpperCase() === name[0], ) // Strip out components that compile away .filter( (name) => !['For', 'Show', 'Fragment', component.name].includes(name), ); // Append refs to data as { foo, bar, etc } dataString = dataString.replace( /}$/, `${component.imports .map((thisImport) => Object.keys(thisImport.imports).join(',')) // Make sure actually used in template .filter((key) => Boolean(key && blocksString.includes(key))) // Don't include component imports .filter((key) => !componentsUsed.includes(key)) .join(',')}}`, ); const elementProps = getProps(component); stripMetaProperties(component); const template = component.children .map((item) => blockToVue(item, options)) .join('\n'); const includeClassMapHelper = template.includes('_classStringToObject'); if (includeClassMapHelper) { functionsString = functionsString.replace( /}\s*$/, `_classStringToObject(str) { const obj = {}; if (typeof str !== 'string') { return obj } const classNames = str.trim().split(/\\s+/); for (const name of classNames) { obj[name] = true; } return obj; } }`, ); } const builderRegister = Boolean( options.builderRegister && component.meta.registerComponent, ); let str = dedent` <template> ${template} </template> <script> ${renderPreComponent(component)} ${ !builderRegister ? '' : `import { registerComponent } from '@builder.io/sdk-vue'` } export default ${!builderRegister ? '' : 'registerComponent('}{ ${ !component.name ? '' : `name: '${ options.namePrefix ? options.namePrefix + '-' : '' }${kebabCase(component.name)}',` } ${ !componentsUsed.length ? '' : `components: { ${componentsUsed .map( (componentName) => `'${kebabCase( componentName, )}': async () => ${componentName}`, ) .join(',')} },` } ${ elementProps.size ? `props: ${JSON.stringify( Array.from(elementProps).filter( (prop) => prop !== 'children' && prop !== 'class', ), )},` : '' } ${ dataString.length < 4 ? '' : ` data: () => (${dataString}), ` } ${ size(component.context.set) ? `provide() { const _this = this; return ${getContextProvideString(component, options)} },` : '' } ${ size(component.context.get) ? `inject: ${getContextInjectString(component, options)},` : '' } ${ component.hooks.onMount ? `mounted() { ${processBinding(component.hooks.onMount, options, component)} },` : '' } ${ component.hooks.onUnMount ? `unmounted() { ${processBinding(component.hooks.onUnMount, options, component)} },` : '' } ${ getterString.length < 4 ? '' : ` computed: ${getterString}, ` } ${ functionsString.length < 4 ? '' : ` methods: ${functionsString}, ` } }${ !builderRegister ? '' : `, ${json5.stringify(component.meta.registerComponent || {})})` } </script> ${ !css.trim().length ? '' : `<style scoped> ${css} </style>` } `; if (options.plugins) { str = runPreCodePlugins(str, options.plugins); } if (true || options.prettier !== false) { try { str = format(str, { parser: 'vue', plugins: [ // To support running in browsers require('prettier/parser-html'), require('prettier/parser-postcss'), require('prettier/parser-babel'), ], }); } catch (err) { console.warn('Could not prettify', { string: str }, err); } } if (options.plugins) { str = runPostCodePlugins(str, options.plugins); } for (const pattern of removePatterns) { str = str.replace(pattern, ''); } return str; }; // Remove unused artifacts like empty script or style tags const removePatterns = [ `<script> export default {}; </script>`, `<style> </style>`, ];
the_stack
import {assert} from '../../../platform/assert-web.js'; import {HandleConnectionSpec} from '../../arcs-types/particle-spec.js'; import {Type} from '../../../types/lib-types.js'; import {RELAXATION_KEYWORD} from '../../manifest-ast-types/manifest-ast-nodes.js'; import {acceptedDirections} from '../../arcs-types/direction-util.js'; import {Handle} from './handle.js'; import {SlotConnection} from './slot-connection.js'; import {Particle} from './particle.js'; import {CloneMap, Recipe, VariableMap} from './recipe.js'; import {TypeChecker} from '../../type-checker.js'; import {compareArrays, compareComparables, compareStrings, compareBools, Comparable} from '../../../utils/lib-utils.js'; import {Direction} from '../../arcs-types/enums.js'; import {HandleConnection as PublicHandleConnection, IsValidOptions, RecipeComponent, ToStringOptions} from './recipe-interface.js'; export class HandleConnection implements Comparable<HandleConnection>, PublicHandleConnection { private readonly _recipe: Recipe; private _name: string; private _tags: string[] = []; private resolvedType?: Type = undefined; private _direction: Direction = 'any'; private _relaxed = false; private _particle: Particle; _handle?: Handle = undefined; constructor(name: string, particle: Particle) { assert(particle); assert(particle.recipe); this._recipe = particle.recipe; this._name = name; this._particle = particle; } get name(): string { return this._name; } // Parameter name? get recipe(): Recipe { return this._recipe; } get isOptional(): boolean { return this.spec !== null && this.spec.isOptional; } get spec(): HandleConnectionSpec { return this.particle.spec && this.particle.spec.handleConnectionMap.get(this.name); } get isInput(): boolean { return this.direction === 'reads' || this.direction === 'reads writes'; } get isOutput(): boolean { return this.direction === 'writes' || this.direction === 'reads writes'; } get handle(): Handle|undefined { return this._handle; } // Handle? get particle() { return this._particle; } // never null get relaxed() { return this._relaxed; } set relaxed(relaxed: boolean) { this._relaxed = relaxed; } get tags(): string[] { return this._tags; } set tags(tags: string[]) { this._tags = tags; } get type(): Type|undefined|null { if (this.resolvedType) { return this.resolvedType; } const spec = this.spec; // TODO: We need a global way to generate variables so that everything can // have proper type bounds. return spec ? spec.type : undefined; } set type(type: Type|undefined|null) { this.resolvedType = type; this._resetHandleType(); } get direction(): Direction { // TODO: Should take the most strict of the direction and the spec direction. if (this._direction !== 'any') { return this._direction; } const spec = this.spec; return spec ? spec.direction : 'any'; } set direction(direction: Direction) { if (direction === null) { throw new Error(`Invalid direction '${direction}' for handle connection '${this.getQualifiedName()}'`); } this._direction = direction; this._resetHandleType(); } _clone(particle: Particle, cloneMap: CloneMap): HandleConnection { if (cloneMap.has(this)) { return cloneMap.get(this) as HandleConnection; } const handleConnection = new HandleConnection(this._name, particle); handleConnection._tags = [...this._tags]; // Note: _resolvedType will be cloned later by the particle that references this connection. // Doing it there allows the particle to maintain variable associations across the particle // scope. handleConnection.resolvedType = this.resolvedType; handleConnection._direction = this._direction; handleConnection._relaxed = this._relaxed; if (this._handle != undefined) { handleConnection._handle = cloneMap.get(this._handle) as Handle; assert(handleConnection._handle !== undefined); handleConnection._handle.connections.push(handleConnection); } cloneMap.set(this, handleConnection); return handleConnection; } // Note: don't call this method directly, only called from particle cloning. cloneTypeWithResolutions(variableMap: VariableMap): void { if (this.resolvedType) { this.resolvedType = this.resolvedType._cloneWithResolutions(variableMap); } } _normalize(): void { this._tags.sort(); // TODO: type? Object.freeze(this); } _compareTo(other: HandleConnection): number { let cmp: number; if ((cmp = compareComparables(this._particle, other._particle)) !== 0) return cmp; if ((cmp = compareStrings(this._name, other._name)) !== 0) return cmp; if ((cmp = compareArrays(this._tags, other._tags, compareStrings)) !== 0) return cmp; if ((cmp = compareComparables(this._handle, other._handle)) !== 0) return cmp; // TODO(cypher1): add type comparison // if ((cmp = compareStrings(this._type, other._type)) != 0) return cmp; if ((cmp = compareStrings(this._direction, other._direction)) !== 0) return cmp; if ((cmp = compareBools(this._relaxed, other._relaxed)) !== 0) return cmp; return 0; } getQualifiedName(): string { return `${this.particle.name}::${this.name}`; } toSlotConnection(): SlotConnection { // TODO: Remove in SLANDLESv2 if (!this.handle || this.handle.fate !== '`slot') { return undefined; } const slandle: SlotConnection = new SlotConnection(this.name, this.particle); slandle.tags = this.tags; slandle.targetSlot = this.handle && this.handle.toSlot(); slandle.targetSlot.name = slandle.targetSlot.name || this.name; if (this.spec) { this.spec.dependentConnections.forEach(connSpec => { const conn = this.particle.getConnectionByName(connSpec.name); if (!conn) return; const slandleConn = conn.toSlotConnection(); if (!slandleConn) return; assert(!slandle.providedSlots[conn.spec.name], `provided slot '${conn.spec.name}' already exists`); slandle.providedSlots[conn.spec.name] = slandleConn.targetSlot; }); } return slandle; } _isValid(options: IsValidOptions): boolean { // Note: The following casts are necessary to catch invalid values that typescript does not manage to check). if (this.direction === null || this.direction === undefined) { if (options && options.errors) { options.errors.set(this, `Invalid direction '${this.direction}' for handle connection '${this.getQualifiedName()}'`); } return false; } if (this.particle.spec && this.name) { const connectionSpec = this.spec; if (!connectionSpec) { if (options && options.errors) { options.errors.set(this, `Connection ${this.name} is not defined by ${this.particle.name}.`); } return false; } if (!acceptedDirections(this.direction).includes(connectionSpec.direction)) { if (options && options.errors) { options.errors.set(this, `Direction '${this.direction}' for handle connection '${this.getQualifiedName()}' doesn't match particle spec's direction '${connectionSpec.direction}'`); } return false; } if (this.resolvedType) { if (!connectionSpec.isCompatibleType(this.resolvedType)) { if (options && options.errors) { options.errors.set(this, `Type '${this.resolvedType.toString()} for handle connection '${this.getQualifiedName()}' doesn't match particle spec's type '${connectionSpec.type.toString()}'`); } return false; } } else { this.resolvedType = connectionSpec.type; } } return true; } isResolved(options?): boolean { assert(Object.isFrozen(this)); let parent: HandleConnection; if (this.spec && this.spec.parentConnection) { parent = this.particle.connections[this.spec.parentConnection.name]; if (!parent) { if (options) { options.details = `parent connection '${this.spec.parentConnection.name}' missing`; } return false; } if (!parent.handle) { if (options) { options.details = `parent connection '${this.spec.parentConnection.name}' missing handle`; } return false; } } if (!this.handle) { if (this.isOptional) { // We're optional we don't need to resolve. return true; } // We're not optional we do need to resolve. if (options) { options.details = 'missing handle'; } return false; } if (!this.direction) { if (options) { options.details = 'missing direction'; } return false; } // TODO: This should use this._type, or possibly not consider type at all. if (!this.type) { if (options) { options.details = 'missing type'; } return false; } return true; } private _resetHandleType(): void { if (this._handle) { this._handle._type = undefined; } } connectToHandle(handle: Handle): void { assert(handle.recipe === this.recipe); this._handle = handle; this._resetHandleType(); this._handle.connections.push(this); } disconnectHandle(): void { const idx = this._handle.connections.indexOf(this); assert(idx >= 0); this._handle.connections.splice(idx, 1); this._handle = undefined; } toString(nameMap: Map<RecipeComponent, string>, options: ToStringOptions): string { const result: string[] = []; result.push(`${this.name || '*'}:`); // TODO(cypher1): support optionality. result.push(this.direction); result.push(this.relaxed ? RELAXATION_KEYWORD : ''); if (this.handle) { if (this.handle.immediateValue) { result.push(this.handle.immediateValue.name); } else { result.push(`${(nameMap && nameMap.get(this.handle)) || this.handle.localName}`); } } result.push(...this.tags.map(a => `#${a}`)); if (options && options.showUnresolved) { if (!this.isResolved(options)) { result.push(`// unresolved handle-connection: ${options.details}`); } } return result.filter(s => s !== '').join(' '); } // TODO: the logic is wrong :) findSpecsForUnnamedHandles() { return this.particle.spec.handleConnections.filter(specConn => { // filter specs with matching types that don't have handles bound to the corresponding handle connection. return !specConn.isOptional && TypeChecker.compareTypes({type: this.handle.type}, {type: specConn.type}) && !this.particle.getConnectionByName(specConn.name); }); } }
the_stack
import { ProgressBar } from '../progressbar'; import { lineCapRadius, completeAngle } from '../model/constant'; import { getPathArc, Pos, degreeToLocation } from '../utils/helper'; import { PathOption, LinearGradient, GradientColor } from '@syncfusion/ej2-svg-base'; import { RangeColorModel } from '../model'; /** * Progressbar Segment */ export class Segment { /** To render the linear segment */ public createLinearSegment( progress: ProgressBar, id: string, width: number, opacity: number, thickness: number, progressWidth: number ): Element { let locX: number = (progress.enableRtl) ? ((progress.cornerRadius === 'Round') ? (progress.progressRect.x + progress.progressRect.width) - ((lineCapRadius / 2) * thickness) : (progress.progressRect.x + progress.progressRect.width)) : ((progress.cornerRadius === 'Round') ? (progress.progressRect.x + (lineCapRadius / 2) * thickness) : progress.progressRect.x); const locY: number = (progress.progressRect.y + (progress.progressRect.height / 2)); const gapWidth: number = (progress.gapWidth || progress.themeStyle.linearGapWidth); const avlWidth: number = progressWidth / progress.segmentCount; let avlSegWidth: number = (progressWidth - ((progress.segmentCount - 1) * gapWidth)); avlSegWidth = (avlSegWidth - ((progress.cornerRadius === 'Round') ? progress.segmentCount * (lineCapRadius * thickness) : 0)) / progress.segmentCount; const gap: number = (progress.cornerRadius === 'Round') ? (gapWidth + (lineCapRadius * thickness)) : gapWidth; const segmentGroup: Element = progress.renderer.createGroup({ 'id': progress.element.id + id }); const count: number = Math.ceil(width / avlWidth); let segWidth: number; let color: string; let j: number = 0; let option: PathOption; let segmentPath: Element; let tolWidth: number = (progress.cornerRadius === 'Round') ? (width - (lineCapRadius * thickness)) : width; const linearThickness: number = progress.progressThickness || progress.themeStyle.linearProgressThickness; for (let i: number = 0; i < count; i++) { segWidth = (tolWidth < avlSegWidth) ? tolWidth : avlSegWidth; if (j < progress.segmentColor.length) { color = progress.segmentColor[j]; j++; } else { j = 0; color = progress.segmentColor[j]; j++; } option = new PathOption( progress.element.id + id + i, 'none', linearThickness, color, opacity, '0', this.getLinearSegmentPath(locX, locY, segWidth, progress.enableRtl) ); segmentPath = progress.renderer.drawPath(option); if (progress.cornerRadius === 'Round') { segmentPath.setAttribute('stroke-linecap', 'round'); } segmentGroup.appendChild(segmentPath); locX += (progress.enableRtl) ? -avlSegWidth - gap : avlSegWidth + gap; tolWidth -= avlSegWidth + gap; tolWidth = (tolWidth < 0) ? 0 : tolWidth; } return segmentGroup; } private getLinearSegmentPath(x: number, y: number, width: number, enableRtl: boolean): string { return 'M' + ' ' + x + ' ' + y + ' ' + 'L' + (x + ((enableRtl) ? -width : width)) + ' ' + y; } /** To render the circular segment */ public createCircularSegment( progress: ProgressBar, id: string, x: number, y: number, r: number, value: number, opacity: number, thickness: number, totalAngle: number, progressWidth: number ): Element { let start: number = progress.startAngle; let end: number = this.widthToAngle(progress.minimum, progress.maximum, value, progress.totalAngle); end -= (progress.cornerRadius === 'Round' && progress.totalAngle === completeAngle) ? this.widthToAngle(0, progressWidth, ((lineCapRadius / 2) * thickness), totalAngle) : 0; let size: number = (progressWidth - ( (progress.totalAngle === completeAngle) ? progress.segmentCount : progress.segmentCount - 1) * (progress.gapWidth || progress.themeStyle.circularGapWidth) ); size = (size - ((progress.cornerRadius === 'Round') ? (((progress.totalAngle === completeAngle) ? progress.segmentCount : progress.segmentCount - 1) * lineCapRadius * thickness) : 0)) / progress.segmentCount; let avlTolEnd: number = this.widthToAngle(0, progressWidth, (progressWidth / progress.segmentCount), totalAngle); avlTolEnd -= (progress.cornerRadius === 'Round' && progress.totalAngle === completeAngle) ? this.widthToAngle(0, progressWidth, ((lineCapRadius / 2) * thickness), totalAngle) : 0; const avlEnd: number = this.widthToAngle(0, progressWidth, size, totalAngle); let gap: number = this.widthToAngle( 0, progressWidth, (progress.gapWidth || progress.themeStyle.circularGapWidth), totalAngle ); gap += (progress.cornerRadius === 'Round') ? this.widthToAngle(0, progressWidth, (lineCapRadius * thickness), totalAngle) : 0; const segmentGroup: Element = progress.renderer.createGroup({ 'id': progress.element.id + id }); const gapCount: number = Math.floor(end / avlTolEnd); const count: number = Math.ceil((end - gap * gapCount) / avlEnd); let segmentPath: string; let circularSegment: Element; let segmentEnd: number; let avlSegEnd: number = (start + ((progress.enableRtl) ? -avlEnd : avlEnd)) % 360; let color: string; let j: number = 0; let option: PathOption; const circularThickness: number = progress.progressThickness || progress.themeStyle.circularProgressThickness; for (let i: number = 0; i < count; i++) { segmentEnd = (progress.enableRtl) ? ((progress.startAngle - end > avlSegEnd) ? progress.startAngle - end : avlSegEnd) : ((progress.startAngle + end < avlSegEnd) ? progress.startAngle + end : avlSegEnd ); segmentPath = getPathArc(x, y, r, start, segmentEnd, progress.enableRtl); if (j < progress.segmentColor.length) { color = progress.segmentColor[j]; j++; } else { j = 0; color = progress.segmentColor[j]; j++; } option = new PathOption( progress.element.id + id + i, 'none', circularThickness, color, opacity, '0', segmentPath ); circularSegment = progress.renderer.drawPath(option); if (progress.cornerRadius === 'Round') { circularSegment.setAttribute('stroke-linecap', 'round'); } segmentGroup.appendChild(circularSegment); start = segmentEnd + ((progress.enableRtl) ? -gap : gap); avlSegEnd += (progress.enableRtl) ? -avlEnd - gap : avlEnd + gap; } return segmentGroup; } private widthToAngle(min: number, max: number, value: number, totalAngle: number): number { const angle: number = ((value - min) / (max - min)) * totalAngle; return angle; } public createLinearRange(totalWidth: number, progress: ProgressBar): Element { const posX: number = progress.progressRect.x + ((progress.enableRtl) ? progress.progressRect.width : 0); const startY: number = (progress.progressRect.y + (progress.progressRect.height / 2)); const rangeGroup: Element = progress.renderer.createGroup({ 'id': progress.element.id + '_LinearRangeGroup' }); const range: RangeColorModel[] = progress.rangeColors; const thickness: number = progress.progressThickness || progress.themeStyle.linearProgressThickness; const opacity: number = progress.themeStyle.progressOpacity; const rangeMin: number = progress.minimum; const rangeMax: number = progress.value; const gradX: number = (progress.enableRtl) ? 0.1 : -0.1; let gradient: Element; let validRange: boolean; let rangePath: Element; let option: PathOption; let startPos: number; let endPos: number; let startX: number; let endX: number; let color: string; let endColor: string; for (let i: number = 0; i < range.length; i++) { validRange = (range[i].start >= rangeMin && range[i].start <= rangeMax && range[i].end >= rangeMin && range[i].end <= rangeMax); startPos = totalWidth * progress.calculateProgressRange(range[i].start, rangeMin, rangeMax); endPos = totalWidth * progress.calculateProgressRange(range[i].end, rangeMin, rangeMax); startX = posX + ((progress.enableRtl) ? -startPos : startPos); endX = posX + ((progress.enableRtl) ? -endPos : endPos); startX = (validRange) ? ((progress.isGradient && i > 0) ? startX + gradX : startX) : posX; endX = (validRange) ? endX : posX; color = (progress.isGradient) ? 'url(#lineRangeGrad_' + i + ')' : range[i].color; option = new PathOption( progress.element.id + '_LinearRange_' + i, 'none', thickness, color, opacity, '0', 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + endX + ' ' + startY ); rangePath = progress.renderer.drawPath(option); rangeGroup.appendChild(rangePath); if (progress.isGradient) { if (range.length - 1 === i) { endColor = range[i].color; } else { endColor = range[i + 1].color; } gradient = this.setLinearGradientColor(i, range[i].color, endColor, startX, endX, progress); rangeGroup.appendChild(gradient); } } return rangeGroup; } public createCircularRange(centerX: number, centerY: number, radius: number, progress: ProgressBar): Element { const rangeGroup: Element = progress.renderer.createGroup({ 'id': progress.element.id + '_CircularRangeGroup' }); const range: RangeColorModel[] = progress.rangeColors; const thickness: number = progress.progressThickness || progress.themeStyle.linearProgressThickness; const opacity: number = progress.themeStyle.progressOpacity; const rangeMin: number = progress.minimum; const rangeMax: number = progress.value; const start: number = progress.startAngle; const tolAngle: number = this.widthToAngle(progress.minimum, progress.maximum, progress.value, progress.totalAngle); let gradient: Element; let startAngle: number; let endAngle: number; let rangePath: Element; let isValidRange: boolean; let option: PathOption; let color: string; let endColor: string; for (let i: number = 0; i < range.length; i++) { isValidRange = (range[i].start >= rangeMin && range[i].start <= rangeMax && range[i].end >= rangeMin && range[i].end <= rangeMax); startAngle = this.widthToAngle(rangeMin, rangeMax, range[i].start, tolAngle); endAngle = this.widthToAngle(rangeMin, rangeMax, range[i].end, tolAngle); startAngle = (isValidRange) ? (start + ((progress.enableRtl) ? -startAngle : startAngle)) % 360 : start; endAngle = (isValidRange) ? (start + ((progress.enableRtl) ? -endAngle : endAngle)) % 360 : start; color = (progress.isGradient) ? 'url(#circleRangeGrad_' + i + ')' : range[i].color; option = new PathOption( progress.element.id + '_CircularRange_' + i, 'none', thickness, color, opacity, '0', getPathArc(centerX, centerY, radius, startAngle, endAngle, progress.enableRtl) ); rangePath = progress.renderer.drawPath(option); rangeGroup.appendChild(rangePath); if (progress.isGradient) { if (range.length - 1 === i) { endColor = range[i].color; } else { endColor = range[i + 1].color; } gradient = this.setCircularGradientColor( i, range[i].color, endColor, startAngle, endAngle, radius, centerX, centerY, progress ); rangeGroup.appendChild(gradient); } } return rangeGroup; } private setLinearGradientColor( id: number, startColor: string, endColor: string, start: number, end: number, progress: ProgressBar ): Element { const stopColor: GradientColor[] = []; const option: LinearGradient = { id: 'lineRangeGrad_' + id + '', x1: start.toString(), x2: end.toString() }; stopColor[0] = { color: startColor, colorStop: '50%' }; stopColor[1] = { color: endColor, colorStop: '100%' }; const linearGradient: Element = progress.renderer.drawGradient('linearGradient', option, stopColor); linearGradient.firstElementChild.setAttribute('gradientUnits', 'userSpaceOnUse'); return linearGradient; } private setCircularGradientColor( id: number, startColor: string, endColor: string, start: number, end: number, rad: number, x: number, y: number, progress: ProgressBar ): Element { const stopColor: GradientColor[] = []; const pos1: Pos = degreeToLocation(x, y, rad, start); const pos2: Pos = degreeToLocation(x, y, rad, end); const option: LinearGradient = { id: 'circleRangeGrad_' + id + '', x1: pos1.x.toString(), x2: pos2.x.toString(), y1: pos1.y.toString(), y2: pos2.y.toString() }; stopColor[0] = { color: startColor, colorStop: '50%' }; stopColor[1] = { color: endColor, colorStop: '100%' }; const linearGradient: Element = progress.renderer.drawGradient('linearGradient', option, stopColor); linearGradient.firstElementChild.setAttribute('gradientUnits', 'userSpaceOnUse'); return linearGradient; } }
the_stack
import { COMMA, DOWN_ARROW, ENTER } from '@angular/cdk/keycodes'; import { Component, ElementRef, OnDestroy, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { FormControl } from '@angular/forms'; import { select, Store } from '@ngrx/store'; import { from, Observable, of, Subject, Subscription } from 'rxjs'; import { catchError, debounceTime, filter, switchMap, take, tap, withLatestFrom } from 'rxjs/operators'; import { AssetTypes } from '../../../core/asset'; import { NoteSnippetTypes } from '../../../core/note'; import { toPromise } from '../../../libs/rx'; import { MenuEvent, MenuService, NativeDialog, nativeDialogFileFilters, NativeDialogProperties } from '../../shared'; import { ConfirmDialog } from '../../shared/confirm-dialog'; import { Stack, StackViewer } from '../../stack'; import { AutocompleteTriggerDirective } from '../../ui/autocomplete'; import { ChipInputEvent } from '../../ui/chips'; import { NoteCollectionService } from '../note-collection'; import { NoteContentFileAlreadyExistsError } from '../note-errors'; import { NoteStateWithRoot } from '../note.state'; import { NoteCodeSnippetActionDialog } from './note-code-snippet-action-dialog/note-code-snippet-action-dialog'; import { NoteSnippetContent } from './note-content.model'; import { NoteEditorService } from './note-editor.service'; import { NoteEditorState } from './note-editor.state'; import { NoteSnippetEditorInsertImageEvent, NoteSnippetEditorNewSnippetEvent, NoteSnippetEditorRef, } from './note-snippet-editor'; import { NoteSnippetListManager } from './note-snippet-list-manager'; @Component({ selector: 'gd-note-editor', templateUrl: './note-editor.component.html', styleUrls: ['./note-editor.component.scss'], host: { 'class': 'NoteEditor', }, }) export class NoteEditorComponent implements OnInit, OnDestroy { private get filteredMenuMessages(): Observable<MenuEvent> { return this.menu.onMessage().pipe( filter(event => [ MenuEvent.NEW_CODE_SNIPPET, MenuEvent.NEW_TEXT_SNIPPET, MenuEvent.INSERT_IMAGE, ].includes(event)), ); } searchedStacks: Stack[] = []; stacks: Stack[] = []; readonly stacksChanged = new Subject<Stack[]>(); readonly stackInputControl = new FormControl(''); readonly stackSearchControl = new FormControl(''); readonly stackInputSeparatorKeyCodes = [ENTER, COMMA]; readonly titleInputControl = new FormControl(''); @ViewChild('scrollable') scrollable: ElementRef<HTMLElement>; @ViewChild('snippetsList') snippetsList: ElementRef<HTMLElement>; @ViewChild('titleTextarea') titleTextarea: ElementRef<HTMLTextAreaElement>; @ViewChild('stackAutoTrigger') stackAutocompleteTrigger: AutocompleteTriggerDirective; private listTopFocusOutSubscription = Subscription.EMPTY; private menuMessageSubscription = Subscription.EMPTY; private selectedNoteChangedSubscription = Subscription.EMPTY; private titleChangesSubscription = Subscription.EMPTY; private stacksChangesSubscription = Subscription.EMPTY; private stackAutocompleteSearchSubscription = Subscription.EMPTY; constructor( private snippetListManager: NoteSnippetListManager, public _viewContainerRef: ViewContainerRef, private menu: MenuService, private store: Store<NoteStateWithRoot>, private actionDialog: NoteCodeSnippetActionDialog, private nativeDialog: NativeDialog, private editorService: NoteEditorService, private collectionService: NoteCollectionService, private confirmDialog: ConfirmDialog, private stackViewer: StackViewer, ) { } get stackNames(): string[] { return this.stacks.map(stack => stack.name); } ngOnInit(): void { this.snippetListManager .setContainerElement(this.snippetsList.nativeElement) .setViewContainerRef(this._viewContainerRef); this.subscribeListTopFocusOut(); this.subscribeMenuMessage(); this.subscribeSelectedNoteChanged(); this.subscribeStackAutocompleteSearch(); this.subscribeStacksChanges(); this.subscribeTitleChanges(); } ngOnDestroy(): void { this.listTopFocusOutSubscription.unsubscribe(); this.menuMessageSubscription.unsubscribe(); this.selectedNoteChangedSubscription.unsubscribe(); this.titleChangesSubscription.unsubscribe(); this.stacksChangesSubscription.unsubscribe(); this.stackAutocompleteSearchSubscription.unsubscribe(); } moveFocusToSnippetEditor(event: KeyboardEvent): void { const { keyCode } = event; if (keyCode === DOWN_ARROW || keyCode === ENTER) { event.preventDefault(); this.snippetListManager.focusTo(0); } } addStack(event: ChipInputEvent): void { const name = event.value; const stack = this.stackViewer.getStackWithSafe(name); if (!this.stacks.some(s => s.name === name)) { this.stacks.push(stack); this.stacksChanged.next(this.stacks); } this.stackSearchControl.patchValue(''); } removeStack(stack: Stack): void { const index = this.stacks.findIndex(s => s.name === stack.name); if (index !== -1) { this.stacks.splice(index, 1); this.stacksChanged.next(this.stacks); // Close panel is expected behavior. this.stackAutocompleteTrigger.closePanel(); } } private createNewTextSnippet(ref: NoteSnippetEditorRef<any>): void { const snippet: NoteSnippetContent = { type: NoteSnippetTypes.TEXT, value: '', }; const event = new NoteSnippetEditorNewSnippetEvent(ref, { snippet }); this.snippetListManager.handleSnippetRefEvent(event); } private createNewCodeSnippet(ref: NoteSnippetEditorRef<any>): void { this.actionDialog.open({ actionType: 'create' }).afterClosed().subscribe((result) => { if (result) { const snippet: NoteSnippetContent = { type: NoteSnippetTypes.CODE, value: '', codeLanguageId: result.codeLanguageId, codeFileName: result.codeFileName, }; const event = new NoteSnippetEditorNewSnippetEvent(ref, { snippet }); this.snippetListManager.handleSnippetRefEvent(event); } }); } private async insertImageAtSnippet(ref: NoteSnippetEditorRef<any>): Promise<void> { if (ref._config.type !== NoteSnippetTypes.TEXT) { return; } const result = await toPromise(this.nativeDialog.showOpenDialog({ message: 'Choose an image:', properties: NativeDialogProperties.OPEN_FILE, fileFilters: [nativeDialogFileFilters.IMAGES], })); if (!result.isSelected) { return; } const currentSelectedNote = await toPromise( this.collectionService.getSelectedNote().pipe(take(1)), ); if (!currentSelectedNote) { return; } const { contentFilePath } = currentSelectedNote; const asset = await toPromise(this.editorService.copyAssetFile( AssetTypes.IMAGE, contentFilePath, result.filePaths[0], )); if (asset) { const event = new NoteSnippetEditorInsertImageEvent(ref, { fileName: asset.fileNameWithoutExtension, filePath: asset.relativePathToWorkspaceDir, }); this.snippetListManager.handleSnippetRefEvent(event); } } private handleNoteTitleChangeError(error: Error, titleToChange: string): void { let message: string; if (error instanceof NoteContentFileAlreadyExistsError) { message = `Note file with the same file already exists. Please use a different title.`; } else { message = error && error.message ? error.message : 'Unknown Error'; } // FIXME LATER: I think this is not good handling. We need to think about UX. this.confirmDialog.open({ isAlert: true, title: `Cannot update note title to: "${titleToChange}"`, body: message, }); } private subscribeListTopFocusOut(): void { this.listTopFocusOutSubscription = this.snippetListManager.topFocusOut() .subscribe(() => { if (this.titleTextarea) { this.titleTextarea.nativeElement.focus(); } }); } private subscribeMenuMessage(): void { this.menuMessageSubscription = this.filteredMenuMessages.pipe( withLatestFrom(this.store.pipe(select(state => state.note.editor))), ).subscribe(([event, editorState]) => { const { activeSnippetIndex } = editorState as NoteEditorState; if (activeSnippetIndex === null) { return; } const ref = this.snippetListManager.getSnippetRefByIndex(activeSnippetIndex); // If snippet is not exists, just ignore. if (!ref) { return; } switch (event as MenuEvent) { case MenuEvent.NEW_TEXT_SNIPPET: this.createNewTextSnippet(ref); break; case MenuEvent.NEW_CODE_SNIPPET: this.createNewCodeSnippet(ref); break; case MenuEvent.INSERT_IMAGE: this.insertImageAtSnippet(ref); break; } }); } private subscribeSelectedNoteChanged(): void { this.selectedNoteChangedSubscription = this.collectionService.getSelectedNote() .subscribe((note) => { if (note) { this.titleInputControl.setValue(note.title, { emitEvent: false }); this.stacks = note.stackIds.map(name => this.stackViewer.getStackWithSafe(name)); } }); } private subscribeTitleChanges(): void { this.titleChangesSubscription = this.titleInputControl.valueChanges.pipe( debounceTime(250), withLatestFrom(this.collectionService.getSelectedNote()), switchMap(([newTitle, note]) => from(this.collectionService.changeNoteTitle(note, newTitle)).pipe( catchError((error) => { this.handleNoteTitleChangeError(error, newTitle); return of(null); }), ), ), ).subscribe(); } private subscribeStacksChanges(): void { this.stacksChangesSubscription = this.stacksChanged.pipe( debounceTime(250), withLatestFrom(this.collectionService.getSelectedNote()), tap(([stacks, note]) => this.collectionService.changeNoteStacks(note, stacks.map(stack => stack.name)), ), ).subscribe(); } private subscribeStackAutocompleteSearch(): void { this.stackAutocompleteSearchSubscription = this.stackSearchControl.valueChanges .pipe(debounceTime(50)) .subscribe((value) => { this.searchedStacks = this.stackViewer .search(value as string) .filter(stack => !this.stackNames.includes(stack.name)); }); } }
the_stack
import { BotAdapter } from './botAdapter'; import { BotCallbackHandlerKey, TurnContext } from './turnContext'; import { INVOKE_RESPONSE_KEY } from './activityHandlerBase'; import { delay } from 'botbuilder-stdlib'; import { v4 as uuid } from 'uuid'; import { AuthenticateRequestResult, AuthenticationConstants, BotFrameworkAuthentication, ClaimsIdentity, ConnectorClient, ConnectorFactory, UserTokenClient, } from 'botframework-connector'; import { Activity, ActivityEventNames, ActivityEx, ActivityTypes, Channels, ConversationParameters, ConversationReference, DeliveryModes, InvokeResponse, ResourceResponse, StatusCodes, } from 'botframework-schema'; export abstract class CloudAdapterBase extends BotAdapter { readonly ConnectorFactoryKey = Symbol('ConnectorFactory'); readonly UserTokenClientKey = Symbol('UserTokenClient'); /** * Create a new [CloudAdapterBase](xref:botbuilder.CloudAdapterBase) instance. * * @param botFrameworkAuthentication A [BotFrameworkAuthentication](xref:botframework-connector.BotFrameworkAuthentication) used for validating and creating tokens. */ constructor(protected readonly botFrameworkAuthentication: BotFrameworkAuthentication) { super(); if (!botFrameworkAuthentication) { throw new TypeError('`botFrameworkAuthentication` parameter required'); } } /** * @inheritdoc */ async sendActivities(context: TurnContext, activities: Partial<Activity>[]): Promise<ResourceResponse[]> { if (!context) { throw new TypeError('`context` parameter required'); } if (!activities) { throw new TypeError('`activities` parameter required'); } if (!activities.length) { throw new Error('Expecting one or more activities, but the array was empty.'); } return Promise.all( activities.map(async (activity) => { delete activity.id; if (activity.type === 'delay') { await delay(typeof activity.value === 'number' ? activity.value : 1000); } else if (activity.type === ActivityTypes.InvokeResponse) { context.turnState.set(INVOKE_RESPONSE_KEY, activity); } else if (activity.type === ActivityTypes.Trace && activity.channelId !== Channels.Emulator) { // no-op } else { const connectorClient = context.turnState.get<ConnectorClient>(this.ConnectorClientKey); if (!connectorClient) { throw new Error('Unable to extract ConnectorClient from turn context.'); } if (activity.replyToId) { return connectorClient.conversations.replyToActivity( activity.conversation.id, activity.replyToId, activity ); } else { return connectorClient.conversations.sendToConversation(activity.conversation.id, activity); } } return { id: activity.id ?? '' }; }) ); } /** * @inheritdoc */ async updateActivity(context: TurnContext, activity: Partial<Activity>): Promise<ResourceResponse | void> { if (!context) { throw new TypeError('`context` parameter required'); } if (!activity) { throw new TypeError('`activity` parameter required'); } const connectorClient = context.turnState.get<ConnectorClient>(this.ConnectorClientKey); if (!connectorClient) { throw new Error('Unable to extract ConnectorClient from turn context.'); } const response = await connectorClient.conversations.updateActivity( activity.conversation.id, activity.id, activity ); return response?.id ? { id: response.id } : undefined; } /** * @inheritdoc */ async deleteActivity(context: TurnContext, reference: Partial<ConversationReference>): Promise<void> { if (!context) { throw new TypeError('`context` parameter required'); } if (!reference) { throw new TypeError('`reference` parameter required'); } const connectorClient = context.turnState.get<ConnectorClient>(this.ConnectorClientKey); if (!connectorClient) { throw new Error('Unable to extract ConnectorClient from turn context.'); } await connectorClient.conversations.deleteActivity(reference.conversation.id, reference.activityId); } /** * @inheritdoc * * @deprecated */ async continueConversation( reference: Partial<ConversationReference>, logic: (context: TurnContext) => Promise<void> ): Promise<void> { throw new Error( '`CloudAdapterBase.continueConversation` is deprecated, please use `CloudAdapterBase.continueConversationAsync`' ); } /** * @internal */ async continueConversationAsync( botAppIdOrClaimsIdentity: string | ClaimsIdentity, reference: Partial<ConversationReference>, logicOrAudience: ((context: TurnContext) => Promise<void>) | string, maybeLogic?: (context: TurnContext) => Promise<void> ): Promise<void> { const botAppId = typeof botAppIdOrClaimsIdentity === 'string' ? botAppIdOrClaimsIdentity : undefined; const claimsIdentity = typeof botAppIdOrClaimsIdentity !== 'string' ? botAppIdOrClaimsIdentity : this.createClaimsIdentity(botAppId); const audience = typeof logicOrAudience === 'string' ? logicOrAudience : undefined; const logic = typeof logicOrAudience === 'function' ? logicOrAudience : maybeLogic; return this.processProactive(claimsIdentity, ActivityEx.getContinuationActivity(reference), audience, logic); } /** * @inheritdoc */ async createConversationAsync( botAppId: string, channelId: string, serviceUrl: string, audience: string, conversationParameters: ConversationParameters, logic: (context: TurnContext) => Promise<void> ): Promise<void> { if (typeof serviceUrl !== 'string' || !serviceUrl) { throw new TypeError('`serviceUrl` must be a non-empty string'); } if (!conversationParameters) throw new TypeError('`conversationParameters` must be defined'); if (!logic) throw new TypeError('`logic` must be defined'); // Create a ClaimsIdentity, to create the connector and for adding to the turn context. const claimsIdentity = this.createClaimsIdentity(botAppId); claimsIdentity.claims.push({ type: AuthenticationConstants.ServiceUrlClaim, value: serviceUrl }); // Create the connector factory. const connectorFactory = this.botFrameworkAuthentication.createConnectorFactory(claimsIdentity); // Create the connector client to use for outbound requests. const connectorClient = await connectorFactory.create(serviceUrl, audience); // Make the actual create conversation call using the connector. const createConversationResult = await connectorClient.conversations.createConversation(conversationParameters); // Create the create activity to communicate the results to the application. const createActivity = this.createCreateActivity( createConversationResult.id, channelId, serviceUrl, conversationParameters ); // Create a UserTokenClient instance for the application to use. (For example, in the OAuthPrompt.) const userTokenClient = await this.botFrameworkAuthentication.createUserTokenClient(claimsIdentity); // Create a turn context and run the pipeline. const context = this.createTurnContext( createActivity, claimsIdentity, undefined, connectorClient, userTokenClient, logic, connectorFactory ); // Run the pipeline. await this.runMiddleware(context, logic); } private createCreateActivity( createdConversationId: string | undefined, channelId: string, serviceUrl: string, conversationParameters: ConversationParameters ): Partial<Activity> { // Create a conversation update activity to represent the result. const activity = ActivityEx.createEventActivity(); activity.name = ActivityEventNames.CreateConversation; activity.channelId = channelId; activity.serviceUrl = serviceUrl; activity.id = createdConversationId ?? uuid(); activity.conversation = { conversationType: undefined, id: createdConversationId, isGroup: conversationParameters.isGroup, name: undefined, tenantId: conversationParameters.tenantId, }; activity.channelData = conversationParameters.channelData; activity.recipient = conversationParameters.bot; return activity; } /** * The implementation for continue conversation. * * @param claimsIdentity The [ClaimsIdentity](xref:botframework-connector.ClaimsIdentity) for the conversation. * @param continuationActivity The continuation [Activity](xref:botframework-schema.Activity) used to create the [TurnContext](xref:botbuilder-core.TurnContext). * @param audience The audience for the call. * @param logic The function to call for the resulting bot turn. * @returns a Promise representing the async operation */ protected async processProactive( claimsIdentity: ClaimsIdentity, continuationActivity: Partial<Activity>, audience: string | undefined, logic: (context: TurnContext) => Promise<void> ): Promise<void> { // Create the connector factory and the inbound request, extracting parameters and then create a connector for outbound requests. const connectorFactory = this.botFrameworkAuthentication.createConnectorFactory(claimsIdentity); // Create the connector client to use for outbound requests. const connectorClient = await connectorFactory.create(continuationActivity.serviceUrl, audience); // Create a UserTokenClient instance for the application to use. (For example, in the OAuthPrompt.) const userTokenClient = await this.botFrameworkAuthentication.createUserTokenClient(claimsIdentity); // Create a turn context and run the pipeline. const context = this.createTurnContext( continuationActivity, claimsIdentity, audience, connectorClient, userTokenClient, logic, connectorFactory ); // Run the pipeline. await this.runMiddleware(context, logic); } /** * The implementation for processing an Activity sent to this bot. * * @param authHeader The authorization header from the http request. * @param activity The [Activity](xref:botframework-schema.Activity) to process. * @param logic The function to call for the resulting bot turn. * @returns a Promise resolving to an invoke response, or undefined. */ protected processActivity( authHeader: string, activity: Activity, logic: (context: TurnContext) => Promise<void> ): Promise<InvokeResponse | undefined>; /** * The implementation for processing an Activity sent to this bot. * * @param authenticateRequestResult The [AuthenticateRequestResult](xref:botframework-connector.AuthenticateRequestResult) for this turn. * @param activity The [Activity](xref:botframework-schema.Activity) to process. * @param logic The function to call for the resulting bot turn. * @returns a Promise resolving to an invoke response, or undefined. */ protected processActivity( authenticateRequestResult: AuthenticateRequestResult, activity: Activity, logic: (context: TurnContext) => Promise<void> ): Promise<InvokeResponse | undefined>; /** * @internal */ protected async processActivity( authHeaderOrAuthenticateRequestResult: string | AuthenticateRequestResult, activity: Activity, logic: (context: TurnContext) => Promise<void> ): Promise<InvokeResponse | undefined> { // Authenticate the inbound request, extracting parameters and create a ConnectorFactory for creating a Connector for outbound requests. const authenticateRequestResult = typeof authHeaderOrAuthenticateRequestResult === 'string' ? await this.botFrameworkAuthentication.authenticateRequest( activity, authHeaderOrAuthenticateRequestResult ) : authHeaderOrAuthenticateRequestResult; // Set the callerId on the activity. activity.callerId = authenticateRequestResult.callerId; // Create the connector client to use for outbound requests. const connectorClient = await authenticateRequestResult.connectorFactory?.create( activity.serviceUrl, authenticateRequestResult.audience ); if (!connectorClient) { throw new Error('Unable to extract ConnectorClient from turn context.'); } // Create a UserTokenClient instance for the application to use. (For example, it would be used in a sign-in prompt.) const userTokenClient = await this.botFrameworkAuthentication.createUserTokenClient( authenticateRequestResult.claimsIdentity ); // Create a turn context and run the pipeline. const context = this.createTurnContext( activity, authenticateRequestResult.claimsIdentity, authenticateRequestResult.audience, connectorClient, userTokenClient, logic, authenticateRequestResult.connectorFactory ); // Run the pipeline. await this.runMiddleware(context, logic); // If there are any results they will have been left on the TurnContext. return this.processTurnResults(context); } /** * This is a helper to create the ClaimsIdentity structure from an appId that will be added to the TurnContext. * It is intended for use in proactive and named-pipe scenarios. * * @param botAppId The bot's application id. * @returns a [ClaimsIdentity](xref:botframework-connector.ClaimsIdentity) with the audience and appId claims set to the botAppId. */ protected createClaimsIdentity(botAppId = ''): ClaimsIdentity { return new ClaimsIdentity([ { type: AuthenticationConstants.AudienceClaim, value: botAppId, }, { type: AuthenticationConstants.AppIdClaim, value: botAppId, }, ]); } private createTurnContext( activity: Partial<Activity>, claimsIdentity: ClaimsIdentity, oauthScope: string | undefined, connectorClient: ConnectorClient, userTokenClient: UserTokenClient, logic: (context: TurnContext) => Promise<void>, connectorFactory: ConnectorFactory ): TurnContext { const context = new TurnContext(this, activity); context.turnState.set(this.BotIdentityKey, claimsIdentity); context.turnState.set(this.ConnectorClientKey, connectorClient); context.turnState.set(this.UserTokenClientKey, userTokenClient); context.turnState.set(BotCallbackHandlerKey, logic); context.turnState.set(this.ConnectorFactoryKey, connectorFactory); context.turnState.set(this.OAuthScopeKey, oauthScope); return context; } private processTurnResults(context: TurnContext): InvokeResponse | undefined { // Handle ExpectedReplies scenarios where all activities have been buffered and sent back at once in an invoke response. if (context.activity.deliveryMode === DeliveryModes.ExpectReplies) { return { status: StatusCodes.OK, body: { activities: context.bufferedReplyActivities, }, }; } // Handle Invoke scenarios where the bot will return a specific body and return code. if (context.activity.type === ActivityTypes.Invoke) { const activityInvokeResponse = context.turnState.get<Activity>(INVOKE_RESPONSE_KEY); if (!activityInvokeResponse) { return { status: StatusCodes.NOT_IMPLEMENTED }; } return activityInvokeResponse.value; } // No body to return. return undefined; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A description of the conditions under which some aspect of your system is * considered to be "unhealthy" and the ways to notify people or services * about this state. * * To get more information about AlertPolicy, see: * * * [API documentation](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.alertPolicies) * * How-to Guides * * [Official Documentation](https://cloud.google.com/monitoring/alerts/) * * ## Example Usage * ### Monitoring Alert Policy Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const alertPolicy = new gcp.monitoring.AlertPolicy("alert_policy", { * combiner: "OR", * conditions: [{ * conditionThreshold: { * aggregations: [{ * alignmentPeriod: "60s", * perSeriesAligner: "ALIGN_RATE", * }], * comparison: "COMPARISON_GT", * duration: "60s", * filter: "metric.type=\"compute.googleapis.com/instance/disk/write_bytes_count\" AND resource.type=\"gce_instance\"", * }, * displayName: "test condition", * }], * displayName: "My Alert Policy", * userLabels: { * foo: "bar", * }, * }); * ``` * * ## Import * * AlertPolicy can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:monitoring/alertPolicy:AlertPolicy default {{name}} * ``` */ export class AlertPolicy extends pulumi.CustomResource { /** * Get an existing AlertPolicy 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?: AlertPolicyState, opts?: pulumi.CustomResourceOptions): AlertPolicy { return new AlertPolicy(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:monitoring/alertPolicy:AlertPolicy'; /** * Returns true if the given object is an instance of AlertPolicy. 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 AlertPolicy { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === AlertPolicy.__pulumiType; } /** * How to combine the results of multiple conditions to * determine if an incident should be opened. * Possible values are `AND`, `OR`, and `AND_WITH_MATCHING_RESOURCE`. */ public readonly combiner!: pulumi.Output<string>; /** * A list of conditions for the policy. The conditions are combined by * AND or OR according to the combiner field. If the combined conditions * evaluate to true, then an incident is created. A policy can have from * one to six conditions. * Structure is documented below. */ public readonly conditions!: pulumi.Output<outputs.monitoring.AlertPolicyCondition[]>; /** * A read-only record of the creation of the alerting policy. If provided in a call to create or update, this field will be * ignored. */ public /*out*/ readonly creationRecords!: pulumi.Output<outputs.monitoring.AlertPolicyCreationRecord[]>; /** * A short name or phrase used to identify the * condition in dashboards, notifications, and * incidents. To avoid confusion, don't use the same * display name for multiple conditions in the same * policy. */ public readonly displayName!: pulumi.Output<string>; /** * Documentation that is included with notifications and incidents related * to this policy. Best practice is for the documentation to include information * to help responders understand, mitigate, escalate, and correct the underlying * problems detected by the alerting policy. Notification channels that have * limited capacity might not show this documentation. * Structure is documented below. */ public readonly documentation!: pulumi.Output<outputs.monitoring.AlertPolicyDocumentation | undefined>; /** * Whether or not the policy is enabled. The default is true. */ public readonly enabled!: pulumi.Output<boolean | undefined>; /** * - * The unique resource name for this condition. * Its syntax is: * projects/[PROJECT_ID]/alertPolicies/[POLICY_ID]/conditions/[CONDITION_ID] * [CONDITION_ID] is assigned by Stackdriver Monitoring when * the condition is created as part of a new or updated alerting * policy. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * Identifies the notification channels to which notifications should be * sent when incidents are opened or closed or when new violations occur * on an already opened incident. Each element of this array corresponds * to the name field in each of the NotificationChannel objects that are * returned from the notificationChannels.list method. The syntax of the * entries in this field is * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]` */ public readonly notificationChannels!: pulumi.Output<string[] | undefined>; /** * 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>; /** * This field is intended to be used for organizing and identifying the AlertPolicy * objects.The field can contain up to 64 entries. Each key and value is limited * to 63 Unicode characters or 128 bytes, whichever is smaller. Labels and values * can contain only lowercase letters, numerals, underscores, and dashes. Keys * must begin with a letter. */ public readonly userLabels!: pulumi.Output<{[key: string]: string} | undefined>; /** * Create a AlertPolicy 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: AlertPolicyArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AlertPolicyArgs | AlertPolicyState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AlertPolicyState | undefined; inputs["combiner"] = state ? state.combiner : undefined; inputs["conditions"] = state ? state.conditions : undefined; inputs["creationRecords"] = state ? state.creationRecords : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["documentation"] = state ? state.documentation : undefined; inputs["enabled"] = state ? state.enabled : undefined; inputs["name"] = state ? state.name : undefined; inputs["notificationChannels"] = state ? state.notificationChannels : undefined; inputs["project"] = state ? state.project : undefined; inputs["userLabels"] = state ? state.userLabels : undefined; } else { const args = argsOrState as AlertPolicyArgs | undefined; if ((!args || args.combiner === undefined) && !opts.urn) { throw new Error("Missing required property 'combiner'"); } if ((!args || args.conditions === undefined) && !opts.urn) { throw new Error("Missing required property 'conditions'"); } if ((!args || args.displayName === undefined) && !opts.urn) { throw new Error("Missing required property 'displayName'"); } inputs["combiner"] = args ? args.combiner : undefined; inputs["conditions"] = args ? args.conditions : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["documentation"] = args ? args.documentation : undefined; inputs["enabled"] = args ? args.enabled : undefined; inputs["notificationChannels"] = args ? args.notificationChannels : undefined; inputs["project"] = args ? args.project : undefined; inputs["userLabels"] = args ? args.userLabels : undefined; inputs["creationRecords"] = undefined /*out*/; inputs["name"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(AlertPolicy.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering AlertPolicy resources. */ export interface AlertPolicyState { /** * How to combine the results of multiple conditions to * determine if an incident should be opened. * Possible values are `AND`, `OR`, and `AND_WITH_MATCHING_RESOURCE`. */ combiner?: pulumi.Input<string>; /** * A list of conditions for the policy. The conditions are combined by * AND or OR according to the combiner field. If the combined conditions * evaluate to true, then an incident is created. A policy can have from * one to six conditions. * Structure is documented below. */ conditions?: pulumi.Input<pulumi.Input<inputs.monitoring.AlertPolicyCondition>[]>; /** * A read-only record of the creation of the alerting policy. If provided in a call to create or update, this field will be * ignored. */ creationRecords?: pulumi.Input<pulumi.Input<inputs.monitoring.AlertPolicyCreationRecord>[]>; /** * A short name or phrase used to identify the * condition in dashboards, notifications, and * incidents. To avoid confusion, don't use the same * display name for multiple conditions in the same * policy. */ displayName?: pulumi.Input<string>; /** * Documentation that is included with notifications and incidents related * to this policy. Best practice is for the documentation to include information * to help responders understand, mitigate, escalate, and correct the underlying * problems detected by the alerting policy. Notification channels that have * limited capacity might not show this documentation. * Structure is documented below. */ documentation?: pulumi.Input<inputs.monitoring.AlertPolicyDocumentation>; /** * Whether or not the policy is enabled. The default is true. */ enabled?: pulumi.Input<boolean>; /** * - * The unique resource name for this condition. * Its syntax is: * projects/[PROJECT_ID]/alertPolicies/[POLICY_ID]/conditions/[CONDITION_ID] * [CONDITION_ID] is assigned by Stackdriver Monitoring when * the condition is created as part of a new or updated alerting * policy. */ name?: pulumi.Input<string>; /** * Identifies the notification channels to which notifications should be * sent when incidents are opened or closed or when new violations occur * on an already opened incident. Each element of this array corresponds * to the name field in each of the NotificationChannel objects that are * returned from the notificationChannels.list method. The syntax of the * entries in this field is * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]` */ notificationChannels?: pulumi.Input<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>; /** * This field is intended to be used for organizing and identifying the AlertPolicy * objects.The field can contain up to 64 entries. Each key and value is limited * to 63 Unicode characters or 128 bytes, whichever is smaller. Labels and values * can contain only lowercase letters, numerals, underscores, and dashes. Keys * must begin with a letter. */ userLabels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; } /** * The set of arguments for constructing a AlertPolicy resource. */ export interface AlertPolicyArgs { /** * How to combine the results of multiple conditions to * determine if an incident should be opened. * Possible values are `AND`, `OR`, and `AND_WITH_MATCHING_RESOURCE`. */ combiner: pulumi.Input<string>; /** * A list of conditions for the policy. The conditions are combined by * AND or OR according to the combiner field. If the combined conditions * evaluate to true, then an incident is created. A policy can have from * one to six conditions. * Structure is documented below. */ conditions: pulumi.Input<pulumi.Input<inputs.monitoring.AlertPolicyCondition>[]>; /** * A short name or phrase used to identify the * condition in dashboards, notifications, and * incidents. To avoid confusion, don't use the same * display name for multiple conditions in the same * policy. */ displayName: pulumi.Input<string>; /** * Documentation that is included with notifications and incidents related * to this policy. Best practice is for the documentation to include information * to help responders understand, mitigate, escalate, and correct the underlying * problems detected by the alerting policy. Notification channels that have * limited capacity might not show this documentation. * Structure is documented below. */ documentation?: pulumi.Input<inputs.monitoring.AlertPolicyDocumentation>; /** * Whether or not the policy is enabled. The default is true. */ enabled?: pulumi.Input<boolean>; /** * Identifies the notification channels to which notifications should be * sent when incidents are opened or closed or when new violations occur * on an already opened incident. Each element of this array corresponds * to the name field in each of the NotificationChannel objects that are * returned from the notificationChannels.list method. The syntax of the * entries in this field is * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]` */ notificationChannels?: pulumi.Input<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>; /** * This field is intended to be used for organizing and identifying the AlertPolicy * objects.The field can contain up to 64 entries. Each key and value is limited * to 63 Unicode characters or 128 bytes, whichever is smaller. Labels and values * can contain only lowercase letters, numerals, underscores, and dashes. Keys * must begin with a letter. */ userLabels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import options from '../../util/options'; import Settings from '../../Settings'; import Math from '../../common/Math'; import Vec2 from '../../common/Vec2'; import Vec3 from '../../common/Vec3'; import Mat33 from '../../common/Mat33'; import Rot from '../../common/Rot'; import Joint, { JointOpt, JointDef } from '../Joint'; import Body from '../Body'; import { TimeStep } from "../Solver"; /** * Weld joint definition. You need to specify local anchor points where they are * attached and the relative body angle. The position of the anchor points is * important for computing the reaction torque. * * @prop {float} frequencyHz * @prop {float} dampingRatio * * @prop {Vec2} localAnchorA * @prop {Vec2} localAnchorB * @prop {float} referenceAngle */ export interface WeldJointOpt extends JointOpt { /** * The mass-spring-damper frequency in Hertz. Rotation only. Disable softness * with a value of 0. */ frequencyHz?: number; /** * The damping ratio. 0 = no damping, 1 = critical damping. */ dampingRatio?: number; /** * The bodyB angle minus bodyA angle in the reference state (radians). */ referenceAngle?: number; } /** * Weld joint definition. You need to specify local anchor points where they are * attached and the relative body angle. The position of the anchor points is * important for computing the reaction torque. */ export interface WeldJointDef extends JointDef, WeldJointOpt { /** * The local anchor point relative to bodyA's origin. */ localAnchorA: Vec2; /** * The local anchor point relative to bodyB's origin. */ localAnchorB: Vec2; } const DEFAULTS = { frequencyHz : 0.0, dampingRatio : 0.0, }; /** * A weld joint essentially glues two bodies together. A weld joint may distort * somewhat because the island constraint solver is approximate. */ export default class WeldJoint extends Joint { static TYPE: 'weld-joint' = 'weld-joint'; /** @internal */ m_type: 'weld-joint'; /** @internal */ m_localAnchorA: Vec2; /** @internal */ m_localAnchorB: Vec2; /** @internal */ m_referenceAngle: number; /** @internal */ m_frequencyHz: number; /** @internal */ m_dampingRatio: number; /** @internal */ m_impulse: Vec3; /** @internal */ m_bias: number; /** @internal */ m_gamma: number; // Solver temp /** @internal */ m_rA: Vec2; /** @internal */ m_rB: Vec2; /** @internal */ m_localCenterA: Vec2; /** @internal */ m_localCenterB: Vec2; /** @internal */ m_invMassA: number; /** @internal */ m_invMassB: number; /** @internal */ m_invIA: number; /** @internal */ m_invIB: number; /** @internal */ m_mass: Mat33; constructor(def: WeldJointDef); constructor(def: WeldJointOpt, bodyA: Body, bodyB: Body, anchor: Vec2); constructor(def: WeldJointDef, bodyA?: Body, bodyB?: Body, anchor?: Vec2) { // @ts-ignore if (!(this instanceof WeldJoint)) { return new WeldJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); super(def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = WeldJoint.TYPE; this.m_localAnchorA = Vec2.clone(anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero()); this.m_localAnchorB = Vec2.clone(anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero()); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = new Vec3(); this.m_bias = 0.0; this.m_gamma = 0.0; // Solver temp this.m_rA; // Vec2 this.m_rB; // Vec2 this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_invMassA; // float this.m_invMassB; // float this.m_invIA; // float this.m_invIB; // float this.m_mass = new Mat33(); // Point-to-point constraint // C = p2 - p1 // Cdot = v2 - v1 // / = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-I -r1_skew I r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Angle constraint // C = angle2 - angle1 - referenceAngle // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 } /** @internal */ _serialize(): object { return { type: this.m_type, bodyA: this.m_bodyA, bodyB: this.m_bodyB, collideConnected: this.m_collideConnected, frequencyHz: this.m_frequencyHz, dampingRatio: this.m_dampingRatio, localAnchorA: this.m_localAnchorA, localAnchorB: this.m_localAnchorB, referenceAngle: this.m_referenceAngle, }; } /** @internal */ static _deserialize(data: any, world: any, restore: any): WeldJoint { data = {...data}; data.bodyA = restore(Body, data.bodyA, world); data.bodyB = restore(Body, data.bodyB, world); const joint = new WeldJoint(data); return joint; } /** @internal */ _setAnchors(def: { anchorA?: Vec2, localAnchorA?: Vec2, anchorB?: Vec2, localAnchorB?: Vec2, }): void { if (def.anchorA) { this.m_localAnchorA.set(this.m_bodyA.getLocalPoint(def.anchorA)); } else if (def.localAnchorA) { this.m_localAnchorA.set(def.localAnchorA); } if (def.anchorB) { this.m_localAnchorB.set(this.m_bodyB.getLocalPoint(def.anchorB)); } else if (def.localAnchorB) { this.m_localAnchorB.set(def.localAnchorB); } } /** * The local anchor point relative to bodyA's origin. */ getLocalAnchorA(): Vec2 { return this.m_localAnchorA; } /** * The local anchor point relative to bodyB's origin. */ getLocalAnchorB(): Vec2 { return this.m_localAnchorB; } /** * Get the reference angle. */ getReferenceAngle(): number { return this.m_referenceAngle; } /** * Set frequency in Hz. */ setFrequency(hz: number): void { this.m_frequencyHz = hz; } /** * Get frequency in Hz. */ getFrequency(): number { return this.m_frequencyHz; } /** * Set damping ratio. */ setDampingRatio(ratio: number): void { this.m_dampingRatio = ratio; } /** * Get damping ratio. */ getDampingRatio(): number { return this.m_dampingRatio; } /** * Get the anchor point on bodyA in world coordinates. */ getAnchorA(): Vec2 { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); } /** * Get the anchor point on bodyB in world coordinates. */ getAnchorB(): Vec2 { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); } /** * Get the reaction force on bodyB at the joint anchor in Newtons. */ getReactionForce(inv_dt: number): Vec2 { return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt); } /** * Get the reaction torque on bodyB in N*m. */ getReactionTorque(inv_dt: number): number { return inv_dt * this.m_impulse.z; } initVelocityConstraints(step: TimeStep): void { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; const aA = this.m_bodyA.c_position.a; const vA = this.m_bodyA.c_velocity.v; let wA = this.m_bodyA.c_velocity.w; const aB = this.m_bodyB.c_position.a; const vB = this.m_bodyB.c_velocity.v; let wB = this.m_bodyB.c_velocity.w; const qA = Rot.neo(aA); const qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] const mA = this.m_invMassA; const mB = this.m_invMassB; const iA = this.m_invIA; const iB = this.m_invIB; const K = new Mat33(); K.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; K.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; K.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; K.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0.0) { K.getInverse22(this.m_mass); let invM = iA + iB; // float const m = invM > 0.0 ? 1.0 / invM : 0.0; // float const C = aB - aA - this.m_referenceAngle; // float // Frequency const omega = 2.0 * Math.PI * this.m_frequencyHz; // float // Damping coefficient const d = 2.0 * m * this.m_dampingRatio * omega; // float // Spring stiffness const k = m * omega * omega; // float // magic formulas const h = step.dt; // float this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0.0 ? 1.0 / this.m_gamma : 0.0; this.m_bias = C * h * k * this.m_gamma; invM += this.m_gamma; this.m_mass.ez.z = invM != 0.0 ? 1.0 / invM : 0.0; } else if (K.ez.z == 0.0) { K.getInverse22(this.m_mass); this.m_gamma = 0.0; this.m_bias = 0.0; } else { K.getSymInverse33(this.m_mass); this.m_gamma = 0.0; this.m_bias = 0.0; } if (step.warmStarting) { // Scale impulses to support a variable time step. this.m_impulse.mul(step.dtRatio); const P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_impulse.z); } else { this.m_impulse.setZero(); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; } solveVelocityConstraints(step: TimeStep): void { const vA = this.m_bodyA.c_velocity.v; let wA = this.m_bodyA.c_velocity.w; const vB = this.m_bodyB.c_velocity.v; let wB = this.m_bodyB.c_velocity.w; const mA = this.m_invMassA; const mB = this.m_invMassB; // float const iA = this.m_invIA; const iB = this.m_invIB; // float if (this.m_frequencyHz > 0.0) { const Cdot2 = wB - wA; // float const impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z); // float this.m_impulse.z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; const Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); // Vec2 const impulse1 = Vec2.neg(Mat33.mulVec2(this.m_mass, Cdot1)); // Vec2 this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; const P = Vec2.clone(impulse1); // Vec2 vA.subMul(mA, P); wA -= iA * Vec2.cross(this.m_rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(this.m_rB, P); } else { const Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); // Vec2 const Cdot2 = wB - wA; // float const Cdot = new Vec3(Cdot1.x, Cdot1.y, Cdot2); // Vec3 const impulse = Vec3.neg(Mat33.mulVec3(this.m_mass, Cdot)); // Vec3 this.m_impulse.add(impulse); const P = Vec2.neo(impulse.x, impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; } /** * This returns true if the position errors are within tolerance. */ solvePositionConstraints(step: TimeStep): boolean { const cA = this.m_bodyA.c_position.c; let aA = this.m_bodyA.c_position.a; const cB = this.m_bodyB.c_position.c; let aB = this.m_bodyB.c_position.a; const qA = Rot.neo(aA); const qB = Rot.neo(aB); const mA = this.m_invMassA; const mB = this.m_invMassB; const iA = this.m_invIA; const iB = this.m_invIB; const rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); const rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); let positionError: number; let angularError: number; const K = new Mat33(); K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.ez.x = -rA.y * iA - rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.ez.y = rA.x * iA + rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0.0) { const C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); // Vec2 positionError = C1.length(); angularError = 0.0; const P = Vec2.neg(K.solve22(C1)); // Vec2 cA.subMul(mA, P); aA -= iA * Vec2.cross(rA, P); cB.addMul(mB, P); aB += iB * Vec2.cross(rB, P); } else { const C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); const C2 = aB - aA - this.m_referenceAngle; // float positionError = C1.length(); angularError = Math.abs(C2); const C = new Vec3(C1.x, C1.y, C2); let impulse = new Vec3(); if (K.ez.z > 0.0) { impulse = Vec3.neg(K.solve33(C)); } else { const impulse2 = Vec2.neg(K.solve22(C1)); impulse.set(impulse2.x, impulse2.y, 0.0); } const P = Vec2.neo(impulse.x, impulse.y); cA.subMul(mA, P); aA -= iA * (Vec2.cross(rA, P) + impulse.z); cB.addMul(mB, P); aB += iB * (Vec2.cross(rB, P) + impulse.z); } this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A configuration for an external identity provider. * * To get more information about WorkloadIdentityPoolProvider, see: * * * [API documentation](https://cloud.google.com/iam/docs/reference/rest/v1beta/projects.locations.workloadIdentityPools.providers) * * How-to Guides * * [Managing workload identity providers](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#managing_workload_identity_providers) * * ## Example Usage * ### Iam Workload Identity Pool Provider Aws Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const pool = new gcp.iam.WorkloadIdentityPool("pool", {workloadIdentityPoolId: "example-pool"}, { * provider: google_beta, * }); * const example = new gcp.iam.WorkloadIdentityPoolProvider("example", { * workloadIdentityPoolId: pool.workloadIdentityPoolId, * workloadIdentityPoolProviderId: "example-prvdr", * aws: { * accountId: "999999999999", * }, * }, { * provider: google_beta, * }); * ``` * ### Iam Workload Identity Pool Provider Aws Full * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const pool = new gcp.iam.WorkloadIdentityPool("pool", {workloadIdentityPoolId: "example-pool"}, { * provider: google_beta, * }); * const example = new gcp.iam.WorkloadIdentityPoolProvider("example", { * workloadIdentityPoolId: pool.workloadIdentityPoolId, * workloadIdentityPoolProviderId: "example-prvdr", * displayName: "Name of provider", * description: "AWS identity pool provider for automated test", * disabled: true, * attributeCondition: "attribute.aws_role==\"arn:aws:sts::999999999999:assumed-role/stack-eu-central-1-lambdaRole\"", * attributeMapping: { * "google.subject": "assertion.arn", * "attribute.aws_account": "assertion.account", * "attribute.environment": "assertion.arn.contains(\":instance-profile/Production\") ? \"prod\" : \"test\"", * }, * aws: { * accountId: "999999999999", * }, * }, { * provider: google_beta, * }); * ``` * ### Iam Workload Identity Pool Provider Oidc Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const pool = new gcp.iam.WorkloadIdentityPool("pool", {workloadIdentityPoolId: "example-pool"}, { * provider: google_beta, * }); * const example = new gcp.iam.WorkloadIdentityPoolProvider("example", { * workloadIdentityPoolId: pool.workloadIdentityPoolId, * workloadIdentityPoolProviderId: "example-prvdr", * attributeMapping: { * "google.subject": "assertion.sub", * }, * oidc: { * issuerUri: "https://sts.windows.net/azure-tenant-id", * }, * }, { * provider: google_beta, * }); * ``` * ### Iam Workload Identity Pool Provider Oidc Full * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const pool = new gcp.iam.WorkloadIdentityPool("pool", {workloadIdentityPoolId: "example-pool"}, { * provider: google_beta, * }); * const example = new gcp.iam.WorkloadIdentityPoolProvider("example", { * workloadIdentityPoolId: pool.workloadIdentityPoolId, * workloadIdentityPoolProviderId: "example-prvdr", * displayName: "Name of provider", * description: "OIDC identity pool provider for automated test", * disabled: true, * attributeCondition: "\"e968c2ef-047c-498d-8d79-16ca1b61e77e\" in assertion.groups", * attributeMapping: { * "google.subject": "\"azure::\" + assertion.tid + \"::\" + assertion.sub", * "attribute.tid": "assertion.tid", * "attribute.managed_identity_name": ` { * "8bb39bdb-1cc5-4447-b7db-a19e920eb111":"workload1", * "55d36609-9bcf-48e0-a366-a3cf19027d2a":"workload2" * }[assertion.oid] * `, * }, * oidc: { * allowedAudiences: [ * "https://example.com/gcp-oidc-federation", * "example.com/gcp-oidc-federation", * ], * issuerUri: "https://sts.windows.net/azure-tenant-id", * }, * }, { * provider: google_beta, * }); * ``` * * ## Import * * WorkloadIdentityPoolProvider can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:iam/workloadIdentityPoolProvider:WorkloadIdentityPoolProvider default projects/{{project}}/locations/global/workloadIdentityPools/{{workload_identity_pool_id}}/providers/{{workload_identity_pool_provider_id}} * ``` * * ```sh * $ pulumi import gcp:iam/workloadIdentityPoolProvider:WorkloadIdentityPoolProvider default {{project}}/{{workload_identity_pool_id}}/{{workload_identity_pool_provider_id}} * ``` * * ```sh * $ pulumi import gcp:iam/workloadIdentityPoolProvider:WorkloadIdentityPoolProvider default {{workload_identity_pool_id}}/{{workload_identity_pool_provider_id}} * ``` */ export class WorkloadIdentityPoolProvider extends pulumi.CustomResource { /** * Get an existing WorkloadIdentityPoolProvider 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?: WorkloadIdentityPoolProviderState, opts?: pulumi.CustomResourceOptions): WorkloadIdentityPoolProvider { return new WorkloadIdentityPoolProvider(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:iam/workloadIdentityPoolProvider:WorkloadIdentityPoolProvider'; /** * Returns true if the given object is an instance of WorkloadIdentityPoolProvider. 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 WorkloadIdentityPoolProvider { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === WorkloadIdentityPoolProvider.__pulumiType; } /** * [A Common Expression Language](https://opensource.google/projects/cel) expression, in * plain text, to restrict what otherwise valid authentication credentials issued by the * provider should not be accepted. * The expression must output a boolean representing whether to allow the federation. * The following keywords may be referenced in the expressions: * * `assertion`: JSON representing the authentication credential issued by the provider. * * `google`: The Google attributes mapped from the assertion in the `attributeMappings`. * * `attribute`: The custom attributes mapped from the assertion in the `attributeMappings`. * The maximum length of the attribute condition expression is 4096 characters. If * unspecified, all valid authentication credential are accepted. * The following example shows how to only allow credentials with a mapped `google.groups` * value of `admins`: * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` */ public readonly attributeCondition!: pulumi.Output<string | undefined>; /** * Maps attributes from authentication credentials issued by an external identity provider * to Google Cloud attributes, such as `subject` and `segment`. * Each key must be a string specifying the Google Cloud IAM attribute to map to. * The following keys are supported: * * `google.subject`: The principal IAM is authenticating. You can reference this value * in IAM bindings. This is also the subject that appears in Cloud Logging logs. * Cannot exceed 127 characters. * * `google.groups`: Groups the external identity belongs to. You can grant groups * access to resources using an IAM `principalSet` binding; access applies to all * members of the group. * You can also provide custom attributes by specifying `attribute.{custom_attribute}`, * where `{custom_attribute}` is the name of the custom attribute to be mapped. You can * define a maximum of 50 custom attributes. The maximum length of a mapped attribute key * is 100 characters, and the key may only contain the characters [a-z0-9_]. * You can reference these attributes in IAM policies to define fine-grained access for a * workload to Google Cloud resources. For example: * * `google.subject`: * `principal://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/subject/{value}` * * `google.groups`: * `principalSet://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/group/{value}` * * `attribute.{custom_attribute}`: * `principalSet://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/attribute.{custom_attribute}/{value}` * Each value must be a [Common Expression Language](https://opensource.google/projects/cel) * function that maps an identity provider credential to the normalized attribute specified * by the corresponding map key. * You can use the `assertion` keyword in the expression to access a JSON representation of * the authentication credential issued by the provider. * The maximum length of an attribute mapping expression is 2048 characters. When evaluated, * the total size of all mapped attributes must not exceed 8KB. * For AWS providers, the following rules apply: * - If no attribute mapping is defined, the following default mapping applies: * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` * - If any custom attribute mappings are defined, they must include a mapping to the * `google.subject` attribute. * For OIDC providers, the following rules apply: * - Custom attribute mappings must be defined, and must include a mapping to the * `google.subject` attribute. For example, the following maps the `sub` claim of the * incoming credential to the `subject` attribute on a Google token. * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` */ public readonly attributeMapping!: pulumi.Output<{[key: string]: string} | undefined>; /** * An Amazon Web Services identity provider. Not compatible with the property oidc. * Structure is documented below. */ public readonly aws!: pulumi.Output<outputs.iam.WorkloadIdentityPoolProviderAws | undefined>; /** * A description for the provider. Cannot exceed 256 characters. */ public readonly description!: pulumi.Output<string | undefined>; /** * Whether the provider is disabled. You cannot use a disabled provider to exchange tokens. * However, existing tokens still grant access. */ public readonly disabled!: pulumi.Output<boolean | undefined>; /** * A display name for the provider. Cannot exceed 32 characters. */ public readonly displayName!: pulumi.Output<string | undefined>; /** * The resource name of the provider as * 'projects/{project_number}/locations/global/workloadIdentityPools/{workload_identity_pool_id}/providers/{workload_identity_pool_provider_id}'. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * An OpenId Connect 1.0 identity provider. Not compatible with the property aws. * Structure is documented below. */ public readonly oidc!: pulumi.Output<outputs.iam.WorkloadIdentityPoolProviderOidc | undefined>; /** * 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>; /** * The state of the provider. * STATE_UNSPECIFIED: State unspecified. * ACTIVE: The provider is active, and may be used to * validate authentication credentials. * DELETED: The provider is soft-deleted. Soft-deleted providers are permanently * deleted after approximately 30 days. You can restore a soft-deleted provider using UndeleteWorkloadIdentityPoolProvider. * You cannot reuse the ID of a soft-deleted provider until it is permanently deleted. */ public /*out*/ readonly state!: pulumi.Output<string>; /** * The ID used for the pool, which is the final component of the pool resource name. This * value should be 4-32 characters, and may contain the characters [a-z0-9-]. The prefix * `gcp-` is reserved for use by Google, and may not be specified. */ public readonly workloadIdentityPoolId!: pulumi.Output<string>; /** * The ID for the provider, which becomes the final component of the resource name. This * value must be 4-32 characters, and may contain the characters [a-z0-9-]. The prefix * `gcp-` is reserved for use by Google, and may not be specified. */ public readonly workloadIdentityPoolProviderId!: pulumi.Output<string>; /** * Create a WorkloadIdentityPoolProvider 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: WorkloadIdentityPoolProviderArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: WorkloadIdentityPoolProviderArgs | WorkloadIdentityPoolProviderState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as WorkloadIdentityPoolProviderState | undefined; inputs["attributeCondition"] = state ? state.attributeCondition : undefined; inputs["attributeMapping"] = state ? state.attributeMapping : undefined; inputs["aws"] = state ? state.aws : undefined; inputs["description"] = state ? state.description : undefined; inputs["disabled"] = state ? state.disabled : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["name"] = state ? state.name : undefined; inputs["oidc"] = state ? state.oidc : undefined; inputs["project"] = state ? state.project : undefined; inputs["state"] = state ? state.state : undefined; inputs["workloadIdentityPoolId"] = state ? state.workloadIdentityPoolId : undefined; inputs["workloadIdentityPoolProviderId"] = state ? state.workloadIdentityPoolProviderId : undefined; } else { const args = argsOrState as WorkloadIdentityPoolProviderArgs | undefined; if ((!args || args.workloadIdentityPoolId === undefined) && !opts.urn) { throw new Error("Missing required property 'workloadIdentityPoolId'"); } if ((!args || args.workloadIdentityPoolProviderId === undefined) && !opts.urn) { throw new Error("Missing required property 'workloadIdentityPoolProviderId'"); } inputs["attributeCondition"] = args ? args.attributeCondition : undefined; inputs["attributeMapping"] = args ? args.attributeMapping : undefined; inputs["aws"] = args ? args.aws : undefined; inputs["description"] = args ? args.description : undefined; inputs["disabled"] = args ? args.disabled : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["oidc"] = args ? args.oidc : undefined; inputs["project"] = args ? args.project : undefined; inputs["workloadIdentityPoolId"] = args ? args.workloadIdentityPoolId : undefined; inputs["workloadIdentityPoolProviderId"] = args ? args.workloadIdentityPoolProviderId : undefined; inputs["name"] = undefined /*out*/; inputs["state"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(WorkloadIdentityPoolProvider.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering WorkloadIdentityPoolProvider resources. */ export interface WorkloadIdentityPoolProviderState { /** * [A Common Expression Language](https://opensource.google/projects/cel) expression, in * plain text, to restrict what otherwise valid authentication credentials issued by the * provider should not be accepted. * The expression must output a boolean representing whether to allow the federation. * The following keywords may be referenced in the expressions: * * `assertion`: JSON representing the authentication credential issued by the provider. * * `google`: The Google attributes mapped from the assertion in the `attributeMappings`. * * `attribute`: The custom attributes mapped from the assertion in the `attributeMappings`. * The maximum length of the attribute condition expression is 4096 characters. If * unspecified, all valid authentication credential are accepted. * The following example shows how to only allow credentials with a mapped `google.groups` * value of `admins`: * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` */ attributeCondition?: pulumi.Input<string>; /** * Maps attributes from authentication credentials issued by an external identity provider * to Google Cloud attributes, such as `subject` and `segment`. * Each key must be a string specifying the Google Cloud IAM attribute to map to. * The following keys are supported: * * `google.subject`: The principal IAM is authenticating. You can reference this value * in IAM bindings. This is also the subject that appears in Cloud Logging logs. * Cannot exceed 127 characters. * * `google.groups`: Groups the external identity belongs to. You can grant groups * access to resources using an IAM `principalSet` binding; access applies to all * members of the group. * You can also provide custom attributes by specifying `attribute.{custom_attribute}`, * where `{custom_attribute}` is the name of the custom attribute to be mapped. You can * define a maximum of 50 custom attributes. The maximum length of a mapped attribute key * is 100 characters, and the key may only contain the characters [a-z0-9_]. * You can reference these attributes in IAM policies to define fine-grained access for a * workload to Google Cloud resources. For example: * * `google.subject`: * `principal://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/subject/{value}` * * `google.groups`: * `principalSet://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/group/{value}` * * `attribute.{custom_attribute}`: * `principalSet://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/attribute.{custom_attribute}/{value}` * Each value must be a [Common Expression Language](https://opensource.google/projects/cel) * function that maps an identity provider credential to the normalized attribute specified * by the corresponding map key. * You can use the `assertion` keyword in the expression to access a JSON representation of * the authentication credential issued by the provider. * The maximum length of an attribute mapping expression is 2048 characters. When evaluated, * the total size of all mapped attributes must not exceed 8KB. * For AWS providers, the following rules apply: * - If no attribute mapping is defined, the following default mapping applies: * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` * - If any custom attribute mappings are defined, they must include a mapping to the * `google.subject` attribute. * For OIDC providers, the following rules apply: * - Custom attribute mappings must be defined, and must include a mapping to the * `google.subject` attribute. For example, the following maps the `sub` claim of the * incoming credential to the `subject` attribute on a Google token. * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` */ attributeMapping?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * An Amazon Web Services identity provider. Not compatible with the property oidc. * Structure is documented below. */ aws?: pulumi.Input<inputs.iam.WorkloadIdentityPoolProviderAws>; /** * A description for the provider. Cannot exceed 256 characters. */ description?: pulumi.Input<string>; /** * Whether the provider is disabled. You cannot use a disabled provider to exchange tokens. * However, existing tokens still grant access. */ disabled?: pulumi.Input<boolean>; /** * A display name for the provider. Cannot exceed 32 characters. */ displayName?: pulumi.Input<string>; /** * The resource name of the provider as * 'projects/{project_number}/locations/global/workloadIdentityPools/{workload_identity_pool_id}/providers/{workload_identity_pool_provider_id}'. */ name?: pulumi.Input<string>; /** * An OpenId Connect 1.0 identity provider. Not compatible with the property aws. * Structure is documented below. */ oidc?: pulumi.Input<inputs.iam.WorkloadIdentityPoolProviderOidc>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The state of the provider. * STATE_UNSPECIFIED: State unspecified. * ACTIVE: The provider is active, and may be used to * validate authentication credentials. * DELETED: The provider is soft-deleted. Soft-deleted providers are permanently * deleted after approximately 30 days. You can restore a soft-deleted provider using UndeleteWorkloadIdentityPoolProvider. * You cannot reuse the ID of a soft-deleted provider until it is permanently deleted. */ state?: pulumi.Input<string>; /** * The ID used for the pool, which is the final component of the pool resource name. This * value should be 4-32 characters, and may contain the characters [a-z0-9-]. The prefix * `gcp-` is reserved for use by Google, and may not be specified. */ workloadIdentityPoolId?: pulumi.Input<string>; /** * The ID for the provider, which becomes the final component of the resource name. This * value must be 4-32 characters, and may contain the characters [a-z0-9-]. The prefix * `gcp-` is reserved for use by Google, and may not be specified. */ workloadIdentityPoolProviderId?: pulumi.Input<string>; } /** * The set of arguments for constructing a WorkloadIdentityPoolProvider resource. */ export interface WorkloadIdentityPoolProviderArgs { /** * [A Common Expression Language](https://opensource.google/projects/cel) expression, in * plain text, to restrict what otherwise valid authentication credentials issued by the * provider should not be accepted. * The expression must output a boolean representing whether to allow the federation. * The following keywords may be referenced in the expressions: * * `assertion`: JSON representing the authentication credential issued by the provider. * * `google`: The Google attributes mapped from the assertion in the `attributeMappings`. * * `attribute`: The custom attributes mapped from the assertion in the `attributeMappings`. * The maximum length of the attribute condition expression is 4096 characters. If * unspecified, all valid authentication credential are accepted. * The following example shows how to only allow credentials with a mapped `google.groups` * value of `admins`: * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` */ attributeCondition?: pulumi.Input<string>; /** * Maps attributes from authentication credentials issued by an external identity provider * to Google Cloud attributes, such as `subject` and `segment`. * Each key must be a string specifying the Google Cloud IAM attribute to map to. * The following keys are supported: * * `google.subject`: The principal IAM is authenticating. You can reference this value * in IAM bindings. This is also the subject that appears in Cloud Logging logs. * Cannot exceed 127 characters. * * `google.groups`: Groups the external identity belongs to. You can grant groups * access to resources using an IAM `principalSet` binding; access applies to all * members of the group. * You can also provide custom attributes by specifying `attribute.{custom_attribute}`, * where `{custom_attribute}` is the name of the custom attribute to be mapped. You can * define a maximum of 50 custom attributes. The maximum length of a mapped attribute key * is 100 characters, and the key may only contain the characters [a-z0-9_]. * You can reference these attributes in IAM policies to define fine-grained access for a * workload to Google Cloud resources. For example: * * `google.subject`: * `principal://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/subject/{value}` * * `google.groups`: * `principalSet://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/group/{value}` * * `attribute.{custom_attribute}`: * `principalSet://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/attribute.{custom_attribute}/{value}` * Each value must be a [Common Expression Language](https://opensource.google/projects/cel) * function that maps an identity provider credential to the normalized attribute specified * by the corresponding map key. * You can use the `assertion` keyword in the expression to access a JSON representation of * the authentication credential issued by the provider. * The maximum length of an attribute mapping expression is 2048 characters. When evaluated, * the total size of all mapped attributes must not exceed 8KB. * For AWS providers, the following rules apply: * - If no attribute mapping is defined, the following default mapping applies: * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` * - If any custom attribute mappings are defined, they must include a mapping to the * `google.subject` attribute. * For OIDC providers, the following rules apply: * - Custom attribute mappings must be defined, and must include a mapping to the * `google.subject` attribute. For example, the following maps the `sub` claim of the * incoming credential to the `subject` attribute on a Google token. * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` */ attributeMapping?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * An Amazon Web Services identity provider. Not compatible with the property oidc. * Structure is documented below. */ aws?: pulumi.Input<inputs.iam.WorkloadIdentityPoolProviderAws>; /** * A description for the provider. Cannot exceed 256 characters. */ description?: pulumi.Input<string>; /** * Whether the provider is disabled. You cannot use a disabled provider to exchange tokens. * However, existing tokens still grant access. */ disabled?: pulumi.Input<boolean>; /** * A display name for the provider. Cannot exceed 32 characters. */ displayName?: pulumi.Input<string>; /** * An OpenId Connect 1.0 identity provider. Not compatible with the property aws. * Structure is documented below. */ oidc?: pulumi.Input<inputs.iam.WorkloadIdentityPoolProviderOidc>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The ID used for the pool, which is the final component of the pool resource name. This * value should be 4-32 characters, and may contain the characters [a-z0-9-]. The prefix * `gcp-` is reserved for use by Google, and may not be specified. */ workloadIdentityPoolId: pulumi.Input<string>; /** * The ID for the provider, which becomes the final component of the resource name. This * value must be 4-32 characters, and may contain the characters [a-z0-9-]. The prefix * `gcp-` is reserved for use by Google, and may not be specified. */ workloadIdentityPoolProviderId: pulumi.Input<string>; }
the_stack
import * as assert from 'assert'; import { Application, HTTPRequest, HTTPResponse } from '../src'; import { FaaSHTTPContext } from '@midwayjs/faas-typings'; import * as mm from 'mm'; describe('test http parser', () => { it('should parser tencent apigw event', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/scf_apigw.json'), require('./resource/scf_ctx.json') ); const res = new HTTPResponse(); const context = app.createContext(req, res); assert(context.toJSON().request); // alias assert(context.req !== context.request); assert(context.res !== context.response); assert(context.header === context.headers); assert(context.headers === context.request.headers); // request assert(context.method === 'POST'); assert(context.request.method === 'POST'); assert(context.path === '/test/value'); assert(context.request.path === '/test/value'); assert(context.url === '/test/value?foo=bar&bob=alice'); assert(context.request.url === '/test/value?foo=bar&bob=alice'); assert(context.ip === '10.0.2.14'); assert(context.request.ip === '10.0.2.14'); assert.deepStrictEqual(context.query, { bob: 'alice', foo: 'bar', }); assert.deepStrictEqual(context.request.query, { bob: 'alice', foo: 'bar', }); assert.deepStrictEqual( context.request.body, JSON.stringify({ test: 'body', }) ); // get request header assert.deepStrictEqual(context.get('User-Agent'), 'User Agent String'); // set response header context.set('X-FaaS-Duration', 2100); assert.deepStrictEqual(context.response.get('X-FaaS-Duration'), '2100'); // set response status assert(context.status === 200); context.status = 400; assert(context.status === 400); // set string context.body = 'hello world'; assert(context.body === 'hello world'); assert(context.response.body === 'hello world'); assert(context.type === 'text/plain'); // set json context.body = { a: 1, }; assert(context.type === 'application/json'); assert.deepStrictEqual(context.accepts(), [ 'text/html', 'application/xml', 'application/json', ]); assert.deepStrictEqual(context.acceptsEncodings(), ['identity']); assert.deepStrictEqual(context.acceptsCharsets(), ['*']); assert.deepStrictEqual(context.acceptsLanguages(), ['en-US', 'en', 'cn']); assert.deepStrictEqual( context.host, 'service-3ei3tii4-251000691.ap-guangzhou.apigateway.myqloud.com' ); assert.deepStrictEqual( context.hostname, 'service-3ei3tii4-251000691.ap-guangzhou.apigateway.myqloud.com' ); context.type = 'html'; assert.deepStrictEqual( context.response.get('Content-Type'), 'text/html; charset=utf-8' ); // ctx.params assert.deepStrictEqual(context.params['path'], 'value'); assert.deepStrictEqual(context.is('html', 'application/*'), false); assert.deepStrictEqual(context.response.get('ETag'), ''); const cacheTime = 1587543474000; // set etag context.set({ Etag: '1234', 'Last-Modified': new Date(cacheTime), }); assert.deepStrictEqual(context.response.get('ETag').length, 4); assert.deepStrictEqual(context.response.lastModified.getTime(), cacheTime); context.lastModified = new Date(cacheTime + 1000); assert.deepStrictEqual( context.response.lastModified.getTime(), cacheTime + 1000 ); // ctx.length assert.deepStrictEqual(context.length, 7); context.length = 100; assert.deepStrictEqual(context.length, 100); assert.deepStrictEqual(context.response.get('Content-Length'), '100'); // context.cookies.set('bbb', '11111'); // context.cookies.set('ccc', '22'); // assert(context.res.headers['set-cookie'].length === 2); }); it('body should undefined when method not post', () => { const app = new Application(); const req = require('./resource/fc_http.json'); req.headers['Content-Type'] = 'application/json'; const res = new HTTPResponse(); const context = app.createContext(req, res); assert(!context.request.body); }); it('should parser fc http event', () => { const app = new Application(); const req = Object.assign(require('./resource/fc_http.json'), { body: Buffer.from( JSON.stringify({ a: '1', }) ), }); const res = new HTTPResponse(); const context = app.createContext(req, res); // alias assert(context.req !== context.request); assert(context.res !== context.response); assert(context.header === context.headers); assert(context.headers === context.request.headers); // request assert(context.method === 'GET'); assert(context.request.method === 'GET'); assert(context.path === '/daily/'); assert(context.request.path === '/daily/'); assert(context.url === '/daily/?a=1'); assert(context.request.url === '/daily/?a=1'); assert(context.ip === '127.0.0.1'); assert(context.request.ip === '127.0.0.1'); assert.deepStrictEqual(context.query, { a: '1', }); assert.deepStrictEqual(context.request.query, { a: '1', }); assert.deepStrictEqual(context.request.body, undefined); assert(context.cookies.get('_ga') === 'GA1.2.690852134.1546410522'); // get request header assert.deepStrictEqual( context.get('User-Agent'), 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36' ); // set response header context.set('X-FaaS-Duration', 2100); assert.deepStrictEqual(context.response.get('X-FaaS-Duration'), '2100'); // set response status assert(context.status === 200); context.status = 400; assert(context.status === 400); // set string context.body = 'hello world'; assert(context.body === 'hello world'); assert(context.response.body === 'hello world'); assert(context.type === 'text/plain'); // set json context.body = { a: 1, }; assert(context.type === 'application/json'); assert.deepStrictEqual(context.host, ''); }); it('should parser aliyun apigw event', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/fc_apigw.json'), require('./resource/fc_ctx.json') ); const res = new HTTPResponse(); const context = app.createContext(req, res); // alias assert(context.req !== context.request); assert(context.res !== context.response); assert(context.header === context.headers); assert(context.headers === context.req.headers); // request assert(context.method === 'POST'); assert(context.request.method === 'POST'); assert(context.path === '/api'); assert(context.request.path === '/api'); assert(context.url === '/api?name=test'); assert(context.request.url === '/api?name=test'); assert(context.ip === ''); assert(context.request.ip === ''); assert.deepStrictEqual(context.query, { name: 'test', }); assert.deepStrictEqual(context.request.query, { name: 'test', }); assert.deepStrictEqual( context.request.body, JSON.stringify({ test: 'body', }) ); // get request header assert(context.get('User-Agent'), 'User Agent String'); // set response header context.set('X-FaaS-Duration', 2100); assert(context.response.get('X-FaaS-Duration'), '2100'); // set response status assert(context.status === 200); context.status = 400; assert(context.status === 400); // set string context.body = 'hello world'; assert(context.body === 'hello world'); assert(context.response.body === 'hello world'); assert(context.type === 'text/plain'); // set json context.body = { a: 1, }; assert(context.type === 'application/json'); assert.deepStrictEqual( context.host, 'service-3ei3tii4-251000691.ap-guangzhou.apigateway.myqloud.com' ); }); describe('test aliyun apigw post type', () => { it('should parse text/html and got string body', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/fc_apigw_post_text.json'), require('./resource/fc_ctx.json') ); const res = new HTTPResponse(); const context = app.createContext(req, res); // alias assert(context.req !== context.request); assert(context.res !== context.response); assert(context.header === context.headers); assert(context.headers === context.req.headers); // request assert(context.method === 'POST'); assert(context.request.method === 'POST'); assert(context.path === '/api/321'); assert(context.request.path === '/api/321'); // test parser body, it's string because content-type is text/html assert(context.request.body === '{"c":"b"}'); }); it('should parse application/json and got json body', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/fc_apigw_post_json.json'), require('./resource/fc_ctx.json') ); const res = new HTTPResponse(); const context = app.createContext(req, res); // alias assert(context.req !== context.request); assert(context.res !== context.response); assert(context.header === context.headers); assert(context.headers === context.req.headers); // request assert(context.method === 'POST'); assert(context.request.method === 'POST'); assert(context.path === '/api/321'); assert(context.request.path === '/api/321'); // test parser body, it's string because content-type is text/html assert.deepStrictEqual(context.request.body, { c: 'b' }); }); it('should parse application/json and got json body(https)', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/fc_apigw_post_json_https.json'), require('./resource/fc_ctx.json') ); const res = new HTTPResponse(); const context = app.createContext(req, res); // alias assert(context.req !== context.request); assert(context.res !== context.response); assert(context.header === context.headers); assert(context.headers === context.req.headers); // request assert(context.method === 'POST'); assert(context.request.method === 'POST'); assert(context.path === '/api/321'); assert(context.request.path === '/api/321'); // test parser body, it's string because content-type is text/html assert.deepStrictEqual(context.request.body, { c: 'b' }); assert(context.request.secure); }); it('should parse form-urlencoded and got json body', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/fc_apigw_post_form.json'), require('./resource/fc_ctx.json') ); const res = new HTTPResponse(); const context = app.createContext(req, res); // alias assert(context.req !== context.request); assert(context.res !== context.response); assert(context.header === context.headers); assert(context.headers === context.req.headers); // request assert(context.method === 'POST'); assert(context.request.method === 'POST'); assert(context.path === '/api/321'); assert(context.request.path === '/api/321'); // test parser body, it's string because content-type is text/html assert.deepStrictEqual(context.request.body, { c: 'b' }); }); it('should parse json by gw filter', () => { // 网关过滤后的结果 const app = new Application(); const req = new HTTPRequest( require('./resource/fc_apigw_post_gw_filter.json'), require('./resource/fc_ctx.json') ); const res = new HTTPResponse(); const context = app.createContext(req, res); // alias assert(context.req !== context.request); assert(context.res !== context.response); assert(context.header === context.headers); assert(context.headers === context.req.headers); // request assert(context.method === 'POST'); assert(context.request.method === 'POST'); assert(context.path === '/api/321'); assert(context.request.path === '/api/321'); // test parser body, it's string because content-type is text/html assert.deepStrictEqual(context.request.body, '{"c":"b"}'); }); }); it('should test callback', async () => { const app = new Application(); // app.use(async (ctx, next) => { // ctx.aaa = 'test'; // await next(); // }); const req = new HTTPRequest( require('./resource/scf_apigw.json'), require('./resource/scf_ctx.json') ); const res = new HTTPResponse(); const respond = app.callback(); const ctx: FaaSHTTPContext = await new Promise(resolve => { respond(req, res, ctx => { resolve(ctx); }); }); // assert((ctx as any).aaa === 'test'); assert.deepStrictEqual( ctx.originContext, require('./resource/scf_ctx.json') ); assert.deepStrictEqual( ctx.originEvent, require('./resource/scf_apigw.json') ); const n = Date.now(); ctx.etag = n + ''; assert(ctx.etag === '"' + n + '"'); assert((ctx as any).logger === console); assert(ctx.request.accepts('html') === 'html'); assert(ctx.accept); ctx.append('X-FaaS-Time', '444'); assert(ctx.response.headers['x-faas-time']); ctx.remove('X-FaaS-Time'); assert(!ctx.response.headers['x-faas-time']); ctx.type = 'html'; assert(ctx.response.headers['content-type']); ctx.body = null; assert(!ctx.response.headers['content-type']); ctx.body = '22'; assert(ctx.status === 204); }); it('should set status first time', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/scf_apigw.json'), require('./resource/scf_ctx.json') ); const res = new HTTPResponse(); const ctx = app.createContext(req, res); ctx.body = '123'; assert(ctx.status === 200); }); it('should set body use buffer', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/scf_apigw.json'), require('./resource/scf_ctx.json') ); const res = new HTTPResponse(); const ctx = app.createContext(req, res); ctx.body = Buffer.from('123'); assert(ctx.status === 200); }); it('should set body use stream', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/scf_apigw.json'), require('./resource/scf_ctx.json') ); const res = new HTTPResponse(); const ctx = app.createContext(req, res); try { ctx.body = { pipe: () => {} }; } catch (err) { assert(err.message === 'unsupport pipe value'); } }); it('set req url', () => { const req = new HTTPRequest( require('./resource/scf_apigw.json'), require('./resource/scf_ctx.json') ); req.url = '/api/123?name=test'; assert(req.path === '/api/123'); assert((req.query as any).name === 'test'); }); it('should test redirect', () => { const app = new Application(); const req = new HTTPRequest( require('./resource/scf_apigw.json'), require('./resource/scf_ctx.json') ); const res = new HTTPResponse(); const ctx: FaaSHTTPContext = app.createContext(req, res); ctx.redirect('http://google.com'); assert.equal(ctx.response.header.location, 'http://google.com'); assert.equal(ctx.status, 302); // should auto fix not encode url ctx.redirect('http://google.com/😓'); assert.equal(ctx.status, 302); assert.equal( ctx.response.headers.location, 'http://google.com/%F0%9F%98%93' ); // should redirect to Referer ctx.request.headers.referrer = '/login'; ctx.redirect('back'); assert.equal(ctx.response.header.location, '/login'); // should default to alt delete ctx.request.header['referrer']; ctx.remove('referer'); ctx.remove('location'); ctx.redirect('back', '/index.html'); assert.equal(ctx.response.header.location, '/index.html'); // should default redirect to / ctx.remove('location'); ctx.redirect('back'); assert.equal(ctx.response.header.location, '/'); // should respond with html const url = 'http://google.com'; ctx.header.accept = 'text/html'; ctx.redirect(url); assert.equal( ctx.response.header['content-type'], 'text/html; charset=utf-8' ); assert.equal(ctx.body, `Redirecting to <a href="${url}">${url}</a>.`); // should escape the url let url1 = '<script>'; ctx.header.accept = 'text/html'; ctx.redirect(url1); url1 = escape(url1); assert.equal( ctx.response.header['content-type'], 'text/html; charset=utf-8' ); assert.equal(ctx.body, `Redirecting to <a href="${url1}">${url1}</a>.`); // should respond with text const url2 = 'http://google.com'; ctx.header.accept = 'text/plain'; ctx.redirect(url); assert.equal(ctx.body, `Redirecting to ${url2}.`); // should not change the status code const url3 = 'http://google.com'; ctx.status = 301; ctx.header.accept = 'text/plain'; ctx.redirect('http://google.com'); assert.equal(ctx.status, 301); assert.equal(ctx.body, `Redirecting to ${url3}.`); // should change the status code const url4 = 'http://google.com'; ctx.status = 304; ctx.header.accept = 'text/plain'; ctx.redirect('http://google.com'); assert.equal(ctx.status, 302); assert.equal(ctx.body, `Redirecting to ${url4}.`); // should overwrite content-type ctx.body = {}; const url5 = 'http://google.com'; ctx.header.accept = 'text/plain'; ctx.redirect('http://google.com'); assert.equal(ctx.status, 302); assert.equal(ctx.body, `Redirecting to ${url5}.`); assert.equal(ctx.type, 'text/plain'); }); describe('test onerror', () => { it('test throw error', () => { const app = new Application(); assert.throws( () => { app.onerror('foo'); }, TypeError, 'non-error thrown: foo' ); }); it('test emit error', () => { const app = new Application(); const err = new Error('mock stack null'); err.stack = null; app.onerror(err); let msg = ''; mm(console, 'error', input => { if (input) msg = input; }); app.onerror(err); assert(msg === ' Error: mock stack null'); }); it('should test ctx.throw', function () { const app = new Application(); const req = new HTTPRequest( require('./resource/scf_apigw.json'), require('./resource/scf_ctx.json') ); const res = new HTTPResponse(); const ctx: FaaSHTTPContext = app.createContext(req, res); try { ctx.throw(403, 'throw error'); } catch (er) { // got err } assert('run here'); }); }); }); function escape(html) { return String(html) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); }
the_stack
import { resets, brandBackground } from '@guardian/source-foundations'; import { getFontsCss } from '@root/src/lib/fonts-css'; import { ASSET_ORIGIN } from '@root/src/lib/assets'; import he from 'he'; export const htmlTemplate = ({ title = 'The Guardian', description, linkedData, loadableConfigScripts, priorityScriptTags, lowPriorityScriptTags, css, html, windowGuardian, gaPath, fontFiles = [], ampLink, openGraphData, twitterData, keywords, }: { title?: string; description: string; linkedData: { [key: string]: any }; loadableConfigScripts: string[]; priorityScriptTags: string[]; lowPriorityScriptTags: string[]; css: string; html: string; fontFiles?: string[]; windowGuardian: string; gaPath: { modern: string; legacy: string }; ampLink?: string; openGraphData: { [key: string]: string }; twitterData: { [key: string]: string }; keywords: string; }): string => { const favicon = process.env.NODE_ENV === 'production' ? 'favicon-32x32.ico' : 'favicon-32x32-dev-yellow.ico'; const fontPreloadTags = fontFiles.map( (fontFile) => `<link rel="preload" href="${fontFile}" as="font" crossorigin>`, ); const generateMetaTags = ( dataObject: { [key: string]: string }, attributeName: 'name' | 'property', ) => { if (dataObject) { return Object.entries(dataObject) .map( ([id, value]) => `<meta ${attributeName}="${id}" content="${value}"/>`, ) .join('\n'); } return ''; }; const openGraphMetaTags = generateMetaTags(openGraphData, 'property'); // Opt out of having information from our website used for personalization of content and suggestions for Twitter users, including ads // See https://developer.twitter.com/en/docs/twitter-for-websites/webpage-properties/overview const twitterSecAndPrivacyMetaTags = `<meta name="twitter:dnt" content="on">`; const twitterMetaTags = generateMetaTags(twitterData, 'name'); // Duplicated prefetch and preconnect tags from DCP: // Documented here: https://github.com/guardian/frontend/pull/12935 // Preconnect should be used for the most crucial third party domains // "use preconnect when you know for sure that you’re going to be accessing a resource" // - https://www.smashingmagazine.com/2019/04/optimization-performance-resource-hints/ // DNS-prefetch should be used for other third party domains that we are likely to connect to but not sure (ads) // Preconnecting to too many URLs can reduce page performance // DNS-prefetch can also be used as a fallback for IE11 // More information on preconnecting: // https://css-tricks.com/using-relpreconnect-to-establish-network-connections-early-and-increase-performance/ // More information on prefetching: // https://developer.mozilla.org/en-US/docs/Web/Performance/dns-prefetch const staticPreconnectUrls = [ `${ASSET_ORIGIN}`, `https://i.guim.co.uk`, `https://j.ophan.co.uk`, `https://ophan.theguardian.com`, ]; const staticPrefetchUrls = [ ...staticPreconnectUrls, `https://api.nextgen.guardianapps.co.uk`, `https://hits-secure.theguardian.com`, `https://interactive.guim.co.uk`, `https://phar.gu-web.net`, `https://static.theguardian.com`, `https://support.theguardian.com`, ]; const allStaticPreconnectUrls = process.env.NODE_ENV === 'production' ? [...staticPreconnectUrls, 'https://sourcepoint.theguardian.com'] : staticPreconnectUrls; const preconnectTags = allStaticPreconnectUrls.map( (src) => `<link rel="preconnect" href="${src}">`, ); const prefetchTags = staticPrefetchUrls.map( (src) => `<link rel="dns-prefetch" href="${src}">`, ); const weAreHiringMessage = ` <!-- We are hiring, ever thought about joining us? https://workforus.theguardian.com/careers/product-engineering/ GGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGG GG GGGGGGGGGGGGG GGGGGGGGGGGG GGGGGGGGG GGGGGGGGGG GGGGGGGGGGG GGGGGGGGGGGGG GGGGGGGGG GGGGGGGGGG GGGGGGGGGGGGGGGGG GGGGGGGGGGG GGGGGGGGG GGGGGGGGGGGGGGGGGGG GGGGGGGGGGGG GGGGGGGGG GGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGG GGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGG GGGGGGGGGGGG GGGGGGGGGGGGG GGGGGGG GGGGGGGGGGGGG GGGGGGGGGGGGGG GGGGGGGG GGGGGGGGGGGGG GGGGGGGGGGGGGG GGGGGGGG GGGGGGGGGGGGG GGGGGGGGGGGGG GGGGGGGG GGGGGGGGGGGG GGGGGGGGGGGG GGGGGGGGG GGGGGGGGGGG GGGGGGGGGGG GGGGGGGGGG GGGGGGGGGG GGGGGGGGG GGGGGGGGGGG GGGGGGGG GGGGGGGGGG GGGGGGGGGGGGGG GGGGG GGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGG GGGGG GGG GGG G G G G G G G G GGGGGG GG GGGGG GGGG G G G G G G G G G G G G G GGGGG G G G G G GGGGG G G G G GGGG G G G G G G G GGGGGG GGGGG G G G G G G G G G G G G G G GGGGGGG GGG GGG G GGGGGG G G G G GGGG --->`; return `<!doctype html> <html lang="en"> <head> ${weAreHiringMessage} <title>${title}</title> <meta name="description" content="${he.encode(description)}" /> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <meta name="theme-color" content="${brandBackground.primary}" /> <link rel="icon" href="https://static.guim.co.uk/images/${favicon}"> ${preconnectTags.join('\n')} ${prefetchTags.join('\n')} <script type="application/ld+json"> ${JSON.stringify(linkedData)} </script> <!-- TODO make this conditional when we support more content types --> ${ampLink ? `<link rel="amphtml" href="${ampLink}">` : ''} ${fontPreloadTags.join('\n')} ${openGraphMetaTags} ${twitterSecAndPrivacyMetaTags} ${twitterMetaTags} <!-- This tag enables pages to be featured in Google Discover as large previews See: https://developers.google.com/search/docs/advanced/mobile/google-discover?hl=en&visit_id=637424198370039526-3805703503&rd=1 --> <meta name="robots" content="max-image-preview:large"> <script> window.guardian = ${windowGuardian}; window.guardian.queue = []; // Queue for functions to be fired by polyfill.io callback </script> <script type="module"> window.guardian.mustardCut = true; window.guardian.gaPath = "${gaPath.modern}"; </script> <script nomodule> // Browser fails mustard check window.guardian.mustardCut = false; window.guardian.gaPath = "${gaPath.legacy}"; </script> <script> // Noop monkey patch perf.mark and perf.measure if not supported if(window.performance !== undefined && window.performance.mark === undefined) { window.performance.mark = function(){}; window.performance.measure = function(){}; } </script> <script> // this is a global that's called at the bottom of the pf.io response, // once the polyfills have run. This may be useful for debugging. // mainly to support browsers that don't support async=false or defer function guardianPolyfilled() { window.guardian.polyfilled = true; if (window.guardian.mustardCut === false) { window.guardian.queue.forEach(function(startup) { startup() }) } } // We've got contracts to abide by with the Ophan tracker // Setting pageViewId here ensures we're not getting race-conditions at all window.guardian.config.ophan = { // This is duplicated from // https://github.com/guardian/ophan/blob/master/tracker-js/assets/coffee/ophan/transmit.coffee // Please do not change this without talking to the Ophan project first. pageViewId: new Date().getTime().toString(36) + 'xxxxxxxxxxxx'.replace(/x/g, function() { return Math.floor(Math.random() * 36).toString(36); }), }; </script> <script> // Set the browserId from the bwid cookie on the ophan object created above // This will need to be replaced later with an async request to an endpoint (function (window, document) { function getCookieValue(name) { var nameEq = name + "=", cookies = document.cookie.split(';'), value = null; cookies.forEach(function (cookie) { while (cookie.charAt(0) === ' ') { cookie = cookie.substring(1, cookie.length); } if (cookie.indexOf(nameEq) === 0) { value = cookie.substring(nameEq.length, cookie.length); } }); return value; } window.guardian.config.ophan.browserId = getCookieValue("bwid"); })(window, document); </script> <script> window.curlConfig = { baseUrl: '${ASSET_ORIGIN}assets', apiName: 'require' }; window.curl = window.curlConfig; </script> <noscript> <img src="https://sb.scorecardresearch.com/p?c1=2&c2=6035250&cv=2.0&cj=1&cs_ucfr=0&comscorekw=${encodeURIComponent( keywords, ).replace(/%20/g, '+')}" /> </noscript> ${loadableConfigScripts.join('\n')} ${priorityScriptTags.join('\n')} <style class="webfont">${getFontsCss()}</style> <style>${resets.resetCSS}</style> ${css} <link rel="stylesheet" media="print" href="${ASSET_ORIGIN}static/frontend/css/print.css"> </head> <body> ${html} ${[...lowPriorityScriptTags].join('\n')} </body> </html>`; };
the_stack
import {Context} from '@loopback/core'; import {anOpenApiSpec, anOperationSpec} from '@loopback/openapi-spec-builder'; import { ControllerSpec, get, ParameterObject, RequestBodyObject, } from '@loopback/openapi-v3'; import { Client, createClientForHandler, createUnexpectedHttpErrorLogger, expect, } from '@loopback/testlab'; import express from 'express'; import HttpErrors from 'http-errors'; import {is} from 'type-is'; import { BodyParser, createBodyParserBinding, DefaultSequence, FindRouteProvider, HttpHandler, InvokeMethodProvider, JsonBodyParser, ParseParamsProvider, RawBodyParser, RejectProvider, Request, RequestBodyParser, RestBindings, StreamBodyParser, TextBodyParser, UrlEncodedBodyParser, writeResultToResponse, } from '../..'; import {aRestServerConfig} from '../helpers'; const SequenceActions = RestBindings.SequenceActions; describe('HttpHandler', () => { let client: Client; beforeEach(givenHandler); beforeEach(givenClient); context('with a simple HelloWorld controller', () => { beforeEach(function setupHelloController() { const spec = anOpenApiSpec() .withOperationReturningString('get', '/hello', 'greet') .build(); class HelloController { public async greet(): Promise<string> { return 'Hello world!'; } } givenControllerClass(HelloController, spec); }); it('handles simple "GET /hello" requests', () => { return client .get('/hello') .expect(200) .expect('content-type', 'text/plain') .expect('Hello world!'); }); }); context('with a controller with operations at different paths/verbs', () => { beforeEach(function setupHelloController() { const spec = anOpenApiSpec() .withOperationReturningString('get', '/hello', 'hello') .withOperationReturningString('get', '/bye', 'bye') .withOperationReturningString('post', '/hello', 'postHello') .build(); class HelloController { public async hello(): Promise<string> { return 'hello'; } public async bye(): Promise<string> { return 'bye'; } public async postHello(): Promise<string> { return 'hello posted'; } } givenControllerClass(HelloController, spec); }); it('executes hello() for "GET /hello"', () => { return client.get('/hello').expect('hello'); }); it('executes bye() for "GET /bye"', () => { return client.get('/bye').expect('bye'); }); it('executes postHello() for "POST /hello', () => { return client.post('/hello').expect('hello posted'); }); it('returns 404 for path not handled', () => { logErrorsExcept(404); return client.get('/unknown-path').expect(404); }); it('returns 404 for verb not handled', () => { logErrorsExcept(404); return client.post('/bye').expect(404); }); }); context('with an operation echoing a string parameter from query', () => { beforeEach(function setupEchoController() { const spec = anOpenApiSpec() .withOperation('get', '/echo', { 'x-operation-name': 'echo', parameters: [ // the type cast is not required, but improves Intellisense <ParameterObject>{ name: 'msg', in: 'query', type: 'string', }, ], responses: { '200': { schema: { type: 'string', }, description: '', }, }, }) .build(); class EchoController { public async echo(msg: string): Promise<string> { return msg; } } givenControllerClass(EchoController, spec); }); it('returns "hello" for "?msg=hello"', () => { return client.get('/echo?msg=hello').expect('hello'); }); it('url-decodes the parameter value', () => { return client.get('/echo?msg=hello%20world').expect('hello world'); }); it('ignores other query fields', () => { return client.get('/echo?msg=hello&ignoreKey=ignoreMe').expect('hello'); }); }); context('with a path-parameter route', () => { beforeEach(givenRouteParamController); it('returns "admin" for "/users/admin"', () => { return client.get('/users/admin').expect('admin'); }); function givenRouteParamController() { const spec = anOpenApiSpec() .withOperation('get', '/users/{username}', { 'x-operation-name': 'getUserByUsername', parameters: [ <ParameterObject>{ name: 'username', in: 'path', description: 'The name of the user to look up.', required: true, type: 'string', }, ], responses: { 200: { schema: { type: 'string', }, description: '', }, }, }) .build(); class RouteParamController { public async getUserByUsername(userName: string): Promise<string> { return userName; } } givenControllerClass(RouteParamController, spec); } }); context('with a header-parameter route', () => { beforeEach(givenHeaderParamController); it('returns the value sent in the header', () => { return client .get('/show-authorization') .set('authorization', 'admin') .expect('admin'); }); function givenHeaderParamController() { const spec = anOpenApiSpec() .withOperation('get', '/show-authorization', { 'x-operation-name': 'showAuthorization', parameters: [ <ParameterObject>{ name: 'Authorization', in: 'header', description: 'Authorization credentials.', required: true, type: 'string', }, ], responses: { 200: { schema: { type: 'string', }, description: '', }, }, }) .build(); class RouteParamController { async showAuthorization(auth: string): Promise<string> { return auth; } } givenControllerClass(RouteParamController, spec); } }); context('with a body request route', () => { let bodyParamControllerInvoked = false; beforeEach(() => { bodyParamControllerInvoked = false; }); beforeEach(givenBodyParamController); it('returns the value sent in json-encoded body', () => { return client .post('/show-body') .send({key: 'value'}) .expect(200, {key: 'value'}); }); it('allows url-encoded request body', () => { return client .post('/show-body') .send('key=value') .expect(200, {key: 'value'}); }); it('returns 400 for malformed JSON body', () => { logErrorsExcept(400); return client .post('/show-body') .set('content-type', 'application/json') .send('malformed-json') .expect(400, { error: { message: 'Unexpected token m in JSON at position 0', name: 'SyntaxError', statusCode: 400, }, }); }); it('rejects unsupported request body', () => { logErrorsExcept(415); return client .post('/show-body') .set('content-type', 'application/xml') .send('<key>value</key>') .expect(415, { error: { code: 'UNSUPPORTED_MEDIA_TYPE', message: 'Content-type application/xml is not supported.', name: 'UnsupportedMediaTypeError', statusCode: 415, }, }); }); it('rejects unmatched request body', () => { logErrorsExcept(415); return client .post('/show-body') .set('content-type', 'text/plain') .send('<key>value</key>') .expect(415, { error: { code: 'UNSUPPORTED_MEDIA_TYPE', message: 'Content-type text/plain does not match [application/json' + ',application/x-www-form-urlencoded,application/xml].', name: 'UnsupportedMediaTypeError', statusCode: 415, }, }); }); it('rejects over-limit request form body', () => { logErrorsExcept(413); return client .post('/show-body') .set('content-type', 'application/x-www-form-urlencoded') .send('key=' + givenLargeRequest()) .expect(413, { error: { statusCode: 413, name: 'PayloadTooLargeError', message: 'request entity too large', }, }) .catch(ignorePipeError) .then(() => expect(bodyParamControllerInvoked).be.false()); }); it('rejects over-limit request json body', () => { logErrorsExcept(413); return client .post('/show-body') .set('content-type', 'application/json') .send({key: givenLargeRequest()}) .expect(413, { error: { statusCode: 413, name: 'PayloadTooLargeError', message: 'request entity too large', }, }) .catch(ignorePipeError) .then(() => expect(bodyParamControllerInvoked).be.false()); }); it('allows customization of request body parser options', () => { const body = {key: givenLargeRequest()}; rootContext .bind(RestBindings.REQUEST_BODY_PARSER_OPTIONS) .to({limit: '4mb'}); // Set limit to 4MB return client .post('/show-body') .set('content-type', 'application/json') .send(body) .expect(200, body); }); it('allows request body parser extensions', () => { const body = '<key>value</key>'; /** * A mock-up xml parser */ class XmlBodyParser implements BodyParser { name = 'xml'; supports(mediaType: string) { return !!is(mediaType, 'xml'); } async parse(request: Request) { return {value: {key: 'value'}}; } } // Register a request body parser for xml rootContext.add(createBodyParserBinding(XmlBodyParser)); return client .post('/show-body') .set('content-type', 'application/xml') .send(body) .expect(200, {key: 'value'}); }); /** * Ignore the EPIPE and ECONNRESET errors. * See https://github.com/nodejs/node/issues/12339 * @param err */ function ignorePipeError(err: HttpErrors.HttpError) { // The server side can close the socket before the client // side can send out all data. For example, `response.end()` // is called before all request data has been processed due // to size limit. // On Windows, ECONNRESET is sometimes emitted instead of EPIPE. if (err?.code !== 'EPIPE' && err?.code !== 'ECONNRESET') throw err; } function givenLargeRequest() { const data = Buffer.alloc(2 * 1024 * 1024, 'A', 'utf-8'); return data.toString(); } function givenBodyParamController() { const spec = anOpenApiSpec() .withOperation('post', '/show-body', { 'x-operation-name': 'showBody', requestBody: <RequestBodyObject>{ description: 'Any object value.', required: true, content: { 'application/json': { schema: {type: 'object'}, }, 'application/x-www-form-urlencoded': { schema: {type: 'object'}, }, 'application/xml': { schema: {type: 'object'}, }, }, }, responses: { 200: { content: { 'application/json': { schema: { type: 'object', }, }, }, description: '', }, }, }) .build(); class RouteParamController { async showBody(data: object): Promise<object> { bodyParamControllerInvoked = true; return data; } } givenControllerClass(RouteParamController, spec); } }); context('response serialization', () => { it('converts object result to a JSON response', () => { const spec = anOpenApiSpec() .withOperation('get', '/object', { 'x-operation-name': 'getObject', responses: { '200': {schema: {type: 'object'}, description: ''}, }, }) .build(); class TestController { public async getObject(): Promise<object> { return {key: 'value'}; } } givenControllerClass(TestController, spec); return client .get('/object') .expect(200) .expect('content-type', /^application\/json($|;)/) .expect('{"key":"value"}'); }); }); context('error handling', () => { it('handles errors thrown by controller constructor', () => { const spec = anOpenApiSpec() .withOperationReturningString('get', '/hello', 'greet') .build(); class ThrowingController { constructor() { throw new Error('Thrown from constructor.'); } } givenControllerClass(ThrowingController, spec); logErrorsExcept(500); return client.get('/hello').expect(500, { error: { message: 'Internal Server Error', statusCode: 500, }, }); }); it('handles invocation of an unknown method', async () => { const spec = anOpenApiSpec() .withOperation( 'get', '/hello', anOperationSpec().withOperationName('unknownMethod'), ) .build(); class TestController {} givenControllerClass(TestController, spec); logErrorsExcept(404); await client.get('/hello').expect(404, { error: { message: 'Controller method not found: get /hello => TestController.unknownMethod', name: 'NotFoundError', statusCode: 404, }, }); }); it('handles errors thrown from the method', async () => { const spec = anOpenApiSpec() .withOperation( 'get', '/hello', anOperationSpec().withOperationName('hello'), ) .build(); class TestController { @get('/hello') hello() { throw new HttpErrors.BadRequest('Bad hello'); } } givenControllerClass(TestController, spec); logErrorsExcept(400); await client.get('/hello').expect(400, { error: { message: 'Bad hello', name: 'BadRequestError', statusCode: 400, }, }); }); it('handles 500 error thrown from the method', async () => { const spec = anOpenApiSpec() .withOperation( 'get', '/hello', anOperationSpec().withOperationName('hello'), ) .build(); class TestController { @get('/hello') hello() { throw new HttpErrors.InternalServerError('Bad hello'); } } givenControllerClass(TestController, spec); logErrorsExcept(500); await client.get('/hello').expect(500, { error: { message: 'Internal Server Error', statusCode: 500, }, }); }); it('respects error handler options', async () => { rootContext.bind(RestBindings.ERROR_WRITER_OPTIONS).to({debug: true}); const spec = anOpenApiSpec() .withOperation( 'get', '/hello', anOperationSpec().withOperationName('hello'), ) .build(); class TestController { @get('/hello') hello() { throw new HttpErrors.InternalServerError('Bad hello'); } } givenControllerClass(TestController, spec); logErrorsExcept(500); const response = await client.get('/hello').expect(500); expect(response.body.error).to.containDeep({ message: 'Bad hello', statusCode: 500, }); }); }); let rootContext: Context; let handler: HttpHandler; function givenHandler() { rootContext = new Context(); rootContext .bind(SequenceActions.FIND_ROUTE) .toDynamicValue(FindRouteProvider); rootContext .bind(SequenceActions.PARSE_PARAMS) .toDynamicValue(ParseParamsProvider); rootContext .bind(SequenceActions.INVOKE_METHOD) .toDynamicValue(InvokeMethodProvider); rootContext .bind(SequenceActions.LOG_ERROR) .to(createUnexpectedHttpErrorLogger()); rootContext.bind(SequenceActions.SEND).to(writeResultToResponse); rootContext.bind(SequenceActions.REJECT).toDynamicValue(RejectProvider); rootContext.bind(RestBindings.SEQUENCE).toClass(DefaultSequence); [ createBodyParserBinding( JsonBodyParser, RestBindings.REQUEST_BODY_PARSER_JSON, ), createBodyParserBinding( TextBodyParser, RestBindings.REQUEST_BODY_PARSER_TEXT, ), createBodyParserBinding( UrlEncodedBodyParser, RestBindings.REQUEST_BODY_PARSER_URLENCODED, ), createBodyParserBinding( RawBodyParser, RestBindings.REQUEST_BODY_PARSER_RAW, ), createBodyParserBinding( StreamBodyParser, RestBindings.REQUEST_BODY_PARSER_STREAM, ), ].forEach(binding => rootContext.add(binding)); rootContext .bind(RestBindings.REQUEST_BODY_PARSER) .toClass(RequestBodyParser); handler = new HttpHandler(rootContext, aRestServerConfig()); rootContext.bind(RestBindings.HANDLER).to(handler); } function logErrorsExcept(ignoreStatusCode: number) { rootContext .bind(SequenceActions.LOG_ERROR) .to(createUnexpectedHttpErrorLogger(ignoreStatusCode)); } function givenControllerClass( // eslint-disable-next-line @typescript-eslint/no-explicit-any ctor: new (...args: any[]) => object, spec: ControllerSpec, ) { handler.registerController(spec, ctor); } function givenClient() { const app = express(); app.use((req, res) => { handler.handleRequest(req, res).catch(err => { // This should never happen. If we ever get here, // then it means "handler.handlerRequest()" crashed unexpectedly. // We need to make a lot of helpful noise in such case. console.error('Request failed.', err.stack); if (res.headersSent) return; res.statusCode = 500; res.end(); }); }); client = createClientForHandler(app); } });
the_stack
// clang-format off import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; // clang-format on /** * Ctap2Status contains a subset of CTAP2 status codes. See * device::CtapDeviceResponseCode for the full list. */ export enum Ctap2Status { OK = 0x0, ERR_FP_DATABASE_FULL = 0x17, ERR_INVALID_OPTION = 0x2C, ERR_KEEPALIVE_CANCEL = 0x2D, } /** * Credential represents a CTAP2 resident credential enumerated from a * security key. * * id: (required) The hex encoding of the CBOR-serialized * PublicKeyCredentialDescriptor of the credential. * * relyingPartyId: (required) The RP ID (i.e. the site that created the * credential; eTLD+n) * * userName: (required) The PublicKeyCredentialUserEntity.name * * userDisplayName: (required) The PublicKeyCredentialUserEntity.display_name * * @see chrome/browser/ui/webui/settings/settings_security_key_handler.cc */ export type Credential = { id: string, relyingPartyId: string, userName: string, userDisplayName: string, }; /** * Encapsulates information about an authenticator's biometric sensor. */ export type SensorInfo = { maxTemplateFriendlyName: number, maxSamplesForEnroll: number|null, }; /** * SampleStatus is the result for reading an individual sample ("touch") * during a fingerprint enrollment. This is a subset of the * lastEnrollSampleStatus enum defined in the CTAP spec. */ export enum SampleStatus { OK = 0x0, } /** * SampleResponse indicates the result of an individual sample (sensor touch) * for an enrollment suboperation. * * @see chrome/browser/ui/webui/settings/settings_security_key_handler.cc */ export type SampleResponse = { status: SampleStatus, remaining: number, }; /** * EnrollmentResponse is the final response to an enrollment suboperation, * * @see chrome/browser/ui/webui/settings/settings_security_key_handler.cc */ export type EnrollmentResponse = { code: Ctap2Status, enrollment: Enrollment|null, }; /** * Enrollment represents a valid fingerprint template stored on a security * key, which can be used in a user verification request. * * @see chrome/browser/ui/webui/settings/settings_security_key_handler.cc */ export type Enrollment = { name: string, id: string, }; /** * SetPINResponse represents the response to startSetPIN and setPIN requests. * * @see chrome/browser/ui/webui/settings/settings_security_key_handler.cc */ export type SetPINResponse = { done: boolean, error?: number, currentMinPinLength?: number, newMinPinLength?: number, retries?: number, }; export interface SecurityKeysPINBrowserProxy { /** * Starts a PIN set/change operation by flashing all security keys. Resolves * with a pair of numbers. The first is one if the process has immediately * completed (i.e. failed). In this case the second is a CTAP error code. * Otherwise the process is ongoing and must be completed by calling * |setPIN|. In this case the second number is either the number of tries * remaining to correctly specify the current PIN, or else null to indicate * that no PIN is currently set. */ startSetPIN(): Promise<SetPINResponse>; /** * Attempts a PIN set/change operation. Resolves with a pair of numbers * whose meaning is the same as with |startSetPIN|. The first number will * always be 1 to indicate that the process has completed and thus the * second will be the CTAP error code. */ setPIN(oldPIN: string, newPIN: string): Promise<SetPINResponse>; /** Cancels all outstanding operations. */ close(): void; } export interface SecurityKeysCredentialBrowserProxy { /** * Starts a credential management operation. * * Callers must listen to errors that can occur during the operation via a * 'security-keys-credential-management-error' WebListener. Values received * via this listener are localized error strings. When the * WebListener fires, the operation must be considered terminated. * * @return A promise that resolves when the handler is ready for * the authenticator PIN to be provided. */ startCredentialManagement(): Promise<Array<number>>; /** * Provides a PIN for a credential management operation. The * startCredentialManagement() promise must have resolved before this method * may be called. * @return A promise that resolves with null if the PIN * was correct or the number of retries remaining otherwise. */ providePIN(pin: string): Promise<number|null>; /** * Enumerates credentials on the authenticator. A correct PIN must have * previously been supplied via providePIN() before this * method may be called. */ enumerateCredentials(): Promise<Array<Credential>>; /** * Deletes the credentials with the given IDs from the security key. * @return A localized response message to display to * the user (on either success or error) */ deleteCredentials(ids: Array<string>): Promise<string>; /** Cancels all outstanding operations. */ close(): void; } export interface SecurityKeysResetBrowserProxy { /** * Starts a reset operation by flashing all security keys and sending a * reset command to the one that the user activates. Resolves with a CTAP * error code. */ reset(): Promise<number>; /** * Waits for a reset operation to complete. Resolves with a CTAP error code. */ completeReset(): Promise<number>; /** Cancels all outstanding operations. */ close(): void; } export interface SecurityKeysBioEnrollProxy { /** * Starts a biometric enrollment operation. * * Callers must listen to errors that can occur during this operation via a * 'security-keys-bio-enrollment-error' WebUIListener. Values received via * this listener are localized error strings. The WebListener may fire at * any point during the operation (enrolling, deleting, etc) and when it * fires, the operation must be considered terminated. * * @return Resolves when the handler is ready for the * authentcation PIN to be provided. */ startBioEnroll(): Promise<Array<number>>; /** * Provides a PIN for a biometric enrollment operation. The startBioEnroll() * Promise must have resolved before this method may be called. * * @return Resolves with null if the PIN was correct, or * with the number of retries remaining otherwise. */ providePIN(pin: string): Promise<number|null>; /** * Obtains the |SensorInfo| for the authenticator. A correct PIN must have * previously been supplied via providePIN() before this method may be called. */ getSensorInfo(): Promise<SensorInfo>; /** * Enumerates enrollments on the authenticator. A correct PIN must have * previously been supplied via providePIN() before this method may be called. */ enumerateEnrollments(): Promise<Array<Enrollment>>; /** * Move the operation into enrolling mode, which instructs the authenticator * to start sampling for touches. * * Callers must listen to status updates that will occur during this * suboperation via a 'security-keys-bio-enroll-status' WebListener. Values * received via this listener are DictionaryValues with two elements (see * below). When the WebListener fires, the authenticator has either timed * out waiting for a touch, or has successfully processed a touch. Any * errors will fire the 'security-keys-bio-enrollment-error' WebListener. * * @return Resolves when the enrollment operation is finished successfully. */ startEnrolling(): Promise<EnrollmentResponse>; /** * Cancel an ongoing enrollment suboperation. This can safely be called at * any time and only has an impact when the authenticator is currently * sampling. */ cancelEnrollment(): void; /** * Deletes the enrollment with the given ID. * * @return The remaining enrollments. */ deleteEnrollment(id: string): Promise<Array<Enrollment>>; /** * Renames the enrollment with the given ID. * * @return The updated list of enrollments. */ renameEnrollment(id: string, name: string): Promise<Array<Enrollment>>; /** Cancels all outstanding operations. */ close(): void; } export class SecurityKeysPINBrowserProxyImpl implements SecurityKeysPINBrowserProxy { startSetPIN() { return sendWithPromise('securityKeyStartSetPIN'); } setPIN(oldPIN: string, newPIN: string) { return sendWithPromise('securityKeySetPIN', oldPIN, newPIN); } close() { return chrome.send('securityKeyPINClose'); } static getInstance(): SecurityKeysPINBrowserProxy { return pinBrowserProxyInstance || (pinBrowserProxyInstance = new SecurityKeysPINBrowserProxyImpl()); } static setInstance(obj: SecurityKeysPINBrowserProxy) { pinBrowserProxyInstance = obj; } } let pinBrowserProxyInstance: SecurityKeysPINBrowserProxy|null = null; export class SecurityKeysCredentialBrowserProxyImpl implements SecurityKeysCredentialBrowserProxy { startCredentialManagement() { return sendWithPromise('securityKeyCredentialManagementStart'); } providePIN(pin: string) { return sendWithPromise('securityKeyCredentialManagementPIN', pin); } enumerateCredentials() { return sendWithPromise('securityKeyCredentialManagementEnumerate'); } deleteCredentials(ids: Array<string>) { return sendWithPromise('securityKeyCredentialManagementDelete', ids); } close() { return chrome.send('securityKeyCredentialManagementClose'); } static getInstance(): SecurityKeysCredentialBrowserProxy { return credentialBrowserProxyInstance || (credentialBrowserProxyInstance = new SecurityKeysCredentialBrowserProxyImpl()); } static setInstance(obj: SecurityKeysCredentialBrowserProxy) { credentialBrowserProxyInstance = obj; } } let credentialBrowserProxyInstance: SecurityKeysCredentialBrowserProxy|null = null; export class SecurityKeysResetBrowserProxyImpl implements SecurityKeysResetBrowserProxy { reset() { return sendWithPromise('securityKeyReset'); } completeReset() { return sendWithPromise('securityKeyCompleteReset'); } close() { return chrome.send('securityKeyResetClose'); } static getInstance(): SecurityKeysResetBrowserProxy { return resetBrowserProxyInstance || (resetBrowserProxyInstance = new SecurityKeysResetBrowserProxyImpl()); } static setInstance(obj: SecurityKeysResetBrowserProxy) { resetBrowserProxyInstance = obj; } } let resetBrowserProxyInstance: SecurityKeysResetBrowserProxy|null = null; export class SecurityKeysBioEnrollProxyImpl implements SecurityKeysBioEnrollProxy { startBioEnroll() { return sendWithPromise('securityKeyBioEnrollStart'); } providePIN(pin: string) { return sendWithPromise('securityKeyBioEnrollProvidePIN', pin); } getSensorInfo() { return sendWithPromise('securityKeyBioEnrollGetSensorInfo'); } enumerateEnrollments() { return sendWithPromise('securityKeyBioEnrollEnumerate'); } startEnrolling() { return sendWithPromise('securityKeyBioEnrollStartEnrolling'); } cancelEnrollment() { return chrome.send('securityKeyBioEnrollCancel'); } deleteEnrollment(id: string) { return sendWithPromise('securityKeyBioEnrollDelete', id); } renameEnrollment(id: string, name: string) { return sendWithPromise('securityKeyBioEnrollRename', id, name); } close() { return chrome.send('securityKeyBioEnrollClose'); } static getInstance(): SecurityKeysBioEnrollProxy { return bioEnrollProxyInstance || (bioEnrollProxyInstance = new SecurityKeysBioEnrollProxyImpl()); } static setInstance(obj: SecurityKeysBioEnrollProxy) { bioEnrollProxyInstance = obj; } } let bioEnrollProxyInstance: SecurityKeysBioEnrollProxy|null = null;
the_stack
import { mountWithElement, waitImmediate, triggerEvent } from '../util' import { ref, ComponentPublicInstance } from 'vue' import { VueWrapper } from '@vue/test-utils' describe('InputNumber', () => { it('create', () => { const val = ref(1) const wrapper = mountWithElement({ template: ` <el-input-number v-model="val"> </el-input-number> `, setup() { return { val, } }, }) let input = wrapper.find('input') expect(input.element.value).toEqual('1') }) it('decrease', async () => { const val = ref(5) const wrapper = mountWithElement({ template: ` <el-input-number v-model="val"> </el-input-number> `, setup() { return { val, } }, }) let input = wrapper.find('input') let btnDecrease = wrapper.find('.el-input-number__decrease') await btnDecrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val.value).toEqual(4) expect(input.element.value).toEqual('4') }) it('increase', async () => { const val = ref(1.5) const wrapper = mountWithElement({ template: ` <el-input-number v-model="val"> </el-input-number> `, setup() { return { val, } }, }) let input = wrapper.find('input') let btnIncrease = wrapper.find('.el-input-number__increase') await btnIncrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val.value).toEqual(2.5) expect(input.element.value).toEqual('2.5') }) it('disabled', async () => { const val = ref(2) const wrapper = mountWithElement({ template: ` <el-input-number v-model="val" disabled> </el-input-number> `, setup() { return { val, } }, }) let input = wrapper.find('input') let btnDecrease = wrapper.find('.el-input-number__decrease') let btnIncrease = wrapper.find('.el-input-number__increase') await btnDecrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val.value).toEqual(2) expect(input.element.value).toEqual('2') await btnIncrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val.value).toEqual(2) expect(input.element.value).toEqual('2') }) it('step', async () => { const val = ref(5) const wrapper = mountWithElement({ template: ` <el-input-number v-model="val" :step="1.2"> </el-input-number> `, setup() { return { val, } }, }) let input = wrapper.find('input') let btnDecrease = wrapper.find('.el-input-number__decrease') let btnIncrease = wrapper.find('.el-input-number__increase') await btnDecrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val.value).toEqual(3.8) expect(input.element.value).toEqual('3.8') await btnDecrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val.value).toEqual(2.6) expect(input.element.value).toEqual('2.6') await btnIncrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val.value).toEqual(3.8) expect(input.element.value).toEqual('3.8') }) it('step strictly', async () => { const val = ref(5) const wrapper = mountWithElement({ template: ` <el-input-number v-model="val" :step="1.2" step-strictly> </el-input-number> `, setup() { return { val, } }, }) let input = wrapper.find('input') await waitImmediate() expect(val.value).toEqual(4.8) expect(input.element.value).toEqual('4.8') val.value = 8 await waitImmediate() expect(val.value).toEqual(8.4) expect(input.element.value).toEqual('8.4') }) it('min', async () => { const val1 = ref(6) const wrapper1 = mountWithElement({ template: ` <el-input-number v-model="val1" :min="6"> </el-input-number> `, setup() { return { val1, } }, }) const val2 = ref(3) const wrapper2 = mountWithElement({ template: ` <el-input-number v-model="val2" :min="6"> </el-input-number> `, setup() { return { val2, } }, }) let input2 = wrapper2.find('input') expect(val2.value === 6) expect(input2.element.value).toEqual('6') let input1 = wrapper1.find('input') let btnDecrease = wrapper1.find('.el-input-number__decrease') btnDecrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val1.value === 6) expect(input1.element.value).toEqual('6') }) it('max', async () => { const val1 = ref(6) const wrapper1 = mountWithElement({ template: ` <el-input-number v-model="val1" :max="6"> </el-input-number> `, setup() { return { val1, } }, }) const val2 = ref(8) const wrapper2 = mountWithElement({ template: ` <el-input-number v-model="val2" :max="6"> </el-input-number> `, setup() { return { val2, } }, }) let input2 = wrapper2.find('input') expect(val2.value === 6) expect(input2.element.value).toEqual('6') let input1 = wrapper1.find('input') let btnIncrease = wrapper1.find('.el-input-number__increase') btnIncrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val1.value === 6) expect(input1.element.value).toEqual('6') }) describe('precision', () => { it('precision is 2', () => { const val = ref(6.999) const wrapper = mountWithElement({ template: ` <el-input-number v-model="val" :max="8" :precision="2"> </el-input-number> `, setup() { return { val, } }, }) expect(val.value === 7) let input = wrapper.find('input') expect(input.element.value).toEqual('7.00') }) it('precision greater than the precision of step', async () => { const val = ref(6.999) const wrapper = mountWithElement({ template: ` <el-input-number v-model="val" :max="8" :precision="0" :step="0.1"> </el-input-number> `, setup() { return { val, } }, }) let input = wrapper.find('input') let btnIncrease = wrapper.find('.el-input-number__increase') expect(val.value === 7) expect(input.element.value).toEqual('7') btnIncrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(val.value === 7) expect(input.element.value).toEqual('7') }) }) it('controls', () => { const val = ref(8) const wrapper = mountWithElement({ template: ` <el-input-number :controls="false" v-model="val" :max="8"> </el-input-number> `, setup() { return { val, } }, }) expect(wrapper.find('.el-input-number__decrease').exists()).toEqual(false) expect(wrapper.find('.el-input-number__increase').exists()).toEqual(false) }) it('invalid value reset', async () => { const val = ref(8) const wrapper = mountWithElement({ template: ` <el-input-number v-model="val" :min="5" :max="10"> </el-input-number> `, setup() { return { val, } }, }) const inputNumber = wrapper.findComponent({ name: 'ElInputNumber' }) val.value = 100 await waitImmediate() expect((inputNumber.vm as any).currentValue).toEqual(10) val.value = 4 await waitImmediate() expect((inputNumber.vm as any).currentValue).toEqual(5) // @ts-ignore val.value = 'dsajkhd' await waitImmediate() expect((inputNumber.vm as any).currentValue).toEqual(5) }) describe('event:change', () => { let mockChange: jest.Mock let vm: any let wrapper: VueWrapper<ComponentPublicInstance> beforeEach(() => { const val = ref(2) mockChange = jest.fn() wrapper = mountWithElement({ template: ` <el-input-number v-model="val" ref="compo" :min='2' :max='3' :step='1' @change="mockChange"> </el-input-number> `, setup() { return { val, mockChange, } }, }) const inputNumber = wrapper.findComponent({ name: 'ElInputNumber' }) vm = inputNumber.vm }) it('emit on input', async () => { vm.handleInputChange('3') await waitImmediate() expect(mockChange).toBeCalledTimes(1) expect(mockChange).toBeCalledWith(3, 2) }) it('emit on button', async () => { const btnIncrease = wrapper.find('.el-input-number__increase') btnIncrease.trigger('mousedown') triggerEvent(document, 'mouseup') await waitImmediate() expect(mockChange).toBeCalledTimes(1) expect(mockChange).toBeCalledWith(3, 2) }) it('does not emit on programatic change', async () => { vm.userInput = 3 await waitImmediate() expect(mockChange).toBeCalledTimes(0) }) it('event:focus & blur', async () => { const inputEl = wrapper.find('input').element const mockBlur = jest.fn() const mockFocus = jest.fn() inputEl.onfocus = mockFocus inputEl.onblur = mockBlur inputEl.focus() inputEl.blur() await waitImmediate() expect(mockFocus).toBeCalledTimes(1) expect(mockBlur).toBeCalledTimes(1) }) }) // // can not test by jsdom // describe('InputNumber Methods', () => { // it('method:select', (done) => { // const val = ref('123') // const wrapper = mountWithElement({ // template: ` // <el-input-number v-model="val" > // </el-input-number> // `, // setup() { // return { // val, // } // }, // }) // const inputEl = wrapper.find('input').element // expect(inputEl.selectionStart).toEqual(val.value.length) // expect(inputEl.selectionEnd).toEqual(val.value.length) // const inputVm = wrapper.findComponent({ name: 'ElInput' }).vm as any // inputVm.select() // expect(inputEl.selectionStart).toEqual(0) // expect(inputEl.selectionEnd).toEqual(val.value.length) // }) // }) })
the_stack
/// <reference types="jquery" /> /// <reference types="pickadate" /> declare namespace Materialize { /** * The collapsible options */ interface CollapsibleOptions { /** * A setting that changes the collapsible behavior to expandable instead of the default accordion style */ accordion?: boolean | undefined; /** * Callback for Collapsible section close. * @default `function() { alert('Closed'); }` */ onClose?: Function | undefined; /** * Callback for Collapsible section open. * @default `function() { alert('Opened'); }` */ onOpen?: Function | undefined; } interface TooltipOptions { /** * The delay before the tooltip shows (in milliseconds) */ delay: number; /** * Tooltip text. Can use custom HTML if you set the html option */ tooltip?: string | undefined; /** * Set the direction of the tooltip. 'top', 'right', 'bottom', 'left'. * * @default `'bottom'` */ position?: string | undefined; /** * Allow custom html inside the tooltip. * * @default `false` */ html?: boolean | undefined; } /** * The dropdown options */ interface DropDownOptions { /** * The duration of the transition enter in milliseconds. * @default `300` */ inDuration?: number | undefined; /** * The duration of the transition out in milliseconds. * @default `225` */ outDuration?: number | undefined; /** * If true, constrainWidth to the size of the dropdown activator. * @default `true` */ constrainWidth?: boolean | undefined; /** * If true, the dropdown will open on hover. * @default `false` */ hover?: boolean | undefined; /** * This defines the spacing from the aligned edge. * @default `0` */ gutter?: number | undefined; /** * If true, the dropdown will show below the activator. * @default `false` */ belowOrigin?: boolean | undefined; /** * Defines the edge the menu is aligned to. * @default `'left'` */ alignment?: string | undefined; /** * If true, stops the event propagating from the dropdown origin click handler. * * @default `false` */ stopPropagation?: boolean | undefined; } /** * The slider options */ interface SliderOptions { /** * Set to false to hide slide indicators. * @default `true` */ indicators?: boolean | undefined; /** * Set height of slider. * @default `400` */ height?: number | undefined; /** * Set the duration of the transition animation in ms. * @default `500` */ transition?: number | undefined; /** * Set the duration between transitions in ms. * @default `6000` */ interval?: number | undefined; } /** * The carousel options */ interface CarouselOptions { /** * Transition duration in milliseconds * @default `200` */ duration?: number | undefined; /** * Perspective zoom. If 0, all items are the same size. * @default `-100` */ dist?: number | undefined; /** * Set the duration of the transition animation in ms. * @default `500` */ shift?: number | undefined; /** * Set the duration between transitions in ms. * @default `6000` */ padding?: number | undefined; /** * Set the width of the carousel. * @default `false` */ fullWidth?: boolean | undefined; /** * Set to true to show indicators. * * @default `false` */ indicators?: boolean | undefined; /** * Don't wrap around and cycle through items. * * @default `false` */ noWrap?: boolean | undefined; } /** * The modal options */ interface ModalOptions { /** * Modal can be dismissed by clicking outside of the modal. * @default `true` */ dismissible?: boolean | undefined; /** * Opacity of modal background. * @default `.5` */ opacity?: number | undefined; /** * Transition in duration. * @default `300` */ inDuration?: number | undefined; /** * Transition out duration. * @default `200` */ outDuration?: number | undefined; /** * Starting top style attribute * @default `4%` */ startingTop?: string | undefined; /** * Ending top style attribute * @default `10%` */ endingTop?: string | undefined; /** * Callback for Modal open. * @default `function() { alert('Ready'); }` */ ready?: Function | undefined; /** * Callback for Modal close. * @default `function() { alert('Closed'); }` */ complete?: Function | undefined; } /** * The push pin options */ interface PushpinOptions { /** * The distance in pixels from the top of the page where the element becomes fixed. * @default `0` */ top?: number | undefined; /** * The distance in pixels from the top of the page where the elements stops being fixed. * @default `Infinity` */ bottom?: number | undefined; /** * The offset from the top the element will be fixed at. * @default `0` */ offset?: number | undefined; } /** * The scroll spy options */ interface ScrollSpyOptions { /** * Offset from top. * @default `200` */ scrollOffset?: number | undefined; /** * Class name to be added to the active link. * @default `active` */ activeClass?: string | undefined; /** * Function that returns a selector to add activeClass to. The parameter is the section id */ getActiveElement?: Function | undefined; } /** * The slideNav options */ interface SideNavOptions { /** * The sideNav width. * @default `240` */ menuWidth?: number | undefined; /** * The horizontal origin. * @default `'left'` */ edge?: string | undefined; /** * Closes sideNav on <a> clicks, useful for Angular/Meteor. * @default `false` */ closeOnClick?: boolean | undefined; /** * Choose whether you can drag to open on touch screens. * @default `true` */ draggable?: boolean | undefined; /** * Execute a callback function when sideNav is opened. * * The callback provides a parameter which refers to the sideNav being opened. */ onOpen?: Function | undefined; /** * Execute a callback function when sideNav is closed. * * The callback provides a parameter which refers to the sideNav being closed. */ onClose?: Function | undefined; } interface ScrollFireOptions { /** * The selector for the element that is being tracked. */ selector?: string | undefined; /** * Offset to use when activating the scroll fire event * If this is 0, the callback will be fired when the selector element is at the very bottom of the user's window. */ offset?: number | undefined; /** * The string function call that you want to make when the user scrolls to the threshold. * It will only be called once. * Example: 'console.log("hello, world!")'; * or callback: () => { console.log('hello world'); } */ callback?: string | (() => void) | undefined; } interface TabOptions { /** * Execute a callback function when the tab is changed. * * The callback provides a parameter which refers to the current tab being shown. */ onShow?: Function | undefined; /** * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option. * * @default `false` */ swipeable?: boolean | undefined; /** * The maximum width of the screen, in pixels, where the swipeable functionality initializes. * * @default `Infinity` */ responsiveThreshold?: number | undefined; } interface ChipDataObject { tag: string; image?: string | undefined; id?: number | undefined; } interface ChipOptions { /** * Set the chip data */ data?: ChipDataObject[] | undefined; /** * Set first placeholder when there are no tags */ placeholder?: string | undefined; /** * Set second placeholder when adding additional tags. */ secondaryPlaceholder?: string | undefined; /** * Set autocomplete data. */ autocompleteData?: any; /** * Set autocomplete limit. */ autocompleteLimit?: number | undefined; /** * Set autocompleteOptions */ autocompleteOptions?: AutoCompleteOptions | undefined; } interface AutoCompleteOptions { /** * The JSON object data to be used for the autocomplete suggetions list */ data: object; /** * The max amount of results that can be shown at once. * @default `Infinity` */ limit?: number | undefined; /** * Callback function when value is autcompleted. */ onAutocomplete?: ((val: any) => void) | undefined; /** * The minimum length of the input for the autocomplete to start. * @default `1` */ minLength?: number | undefined; } interface Toast { /** * Dismiss all toasts */ removeAll: Function; } /** * The Materialize object */ interface Materialize { /** * Displays a toast message on screen * * @param string | JQuery message The message to display on screen * @param number displayLength The duration in milliseconds to display the message on screen * @param string className The className to use to format the message to display * @param Function completeCallback Callback function to call when the messages completes/hides. */ toast(message: string | JQuery, displayLength: number, className?: string, completeCallback?: Function): void; /** * Fires an event when the page is scrolled to a certain area * * @param ScrollFireOptions options optional parameter with scroll fire options */ scrollFire(options?: ScrollFireOptions[]): void; /** * A staggered reveal effect for any UL Tag with list items * * @param string selector the selector for the list to show in staggered fasion */ showStaggeredList(selector: string): void; /** * Fade in images. It also animates grayscale and brightness to give it a unique effect. * * @param string selector the selector for the image to fade in */ fadeInImage(selector: string): void; /** * Update all text field to reinitialize all the Materialize labels on the page if dynamically adding inputs */ updateTextFields(): void; /** * Toast functions */ Toast: Toast; } } /** * Declare Pickadate namespace again in order to add more Materialize specific properties to TimeOptions and DateOptions interfaces * * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html */ declare namespace Pickadate { interface DateOptions { weekdaysLetter?: string[] | undefined; } interface TimeOptions { /** * Set default time such as : 'now', '1:30AM', '16:30'. * @default `'now'` */ default?: string | undefined; /** * set default time to * milliseconds from now (using with default = 'now') * @default `0` */ fromnow?: number | undefined; /** * Use AM/PM or 24-hour format * @default `false` */ twelvehour?: boolean | undefined; /** * text for done-button * @default `'OK'` */ donetext?: string | undefined; /** * text for clear-button * @default `'Clear'` */ cleartext?: string | undefined; /** * Text for cancel-button * @default `'Cancel'` */ canceltext?: string | undefined; /** * automatic close timepicker * @default `false` */ autoclose?: boolean | undefined; /** * make AM PM clickable * @default `true` */ ampmclickable?: boolean | undefined; /** * Function for after opening timepicker */ aftershow?: Function | undefined; } } declare var Materialize: Materialize.Materialize; interface JQuery { /** * open Fixed Action Button */ openFAB(): void; /** * close Fixed Action Button */ closeFAB(): void; /** * Select allows user input through specified options. * * @param string method "destroy" destroy the material select */ material_select(method?: string): void; /** * Use a character counter in fields where a character restriction is in place. */ characterCounter(): JQuery; /** * Collapsibles are accordion elements that expand when clicked on. * They allow you to hide content that is not immediately relevant to the user. * * @param CollapsibleOptions | string options the collapsible options or the string "destroy" to destroy the collapsible */ collapsible(options?: Materialize.CollapsibleOptions | string): JQuery; /** * Programmatically trigger an event on a selected index * * @param string method the string "open" or "close" to open or to close the collapsible element on specified index * @param number index the element index to trigger "open" or "close" function */ collapsible(method: string, index: number): JQuery; /** * Tooltips are small, interactive, textual hints for mainly graphical elements. * When using icons for actions you can use a tooltip to give people clarification on its function. * * @param TooltipOptions | string options the tooltip options or the string "remove" to remove the tooltip function */ tooltip(options?: Materialize.TooltipOptions | string): JQuery; /** * Add a dropdown list to any button. * Make sure that the data-activates attribute matches the id in the <ul> tag. * * @param DropDownOptions options the drop down options */ dropdown(options?: Materialize.DropDownOptions): void; /** * Material box is a material design implementation of the Lightbox plugin. */ materialbox(): JQuery; /** * slider is a simple and elegant image carousel. * You can also have captions that will be transitioned on their own depending on their alignment. * You can also have indicators that show up on the bottom of the slider. * * @param SliderOptions options the slider options */ slider(options?: Materialize.SliderOptions): JQuery; /** * slider is a simple and elegant image carousel. * You can also have captions that will be transitioned on their own depending on their alignment. * You can also have indicators that show up on the bottom of the slider. * * @param string method the string "start" to start the animation or "pauze" to pauze the animation */ slider(method: string): JQuery; /** * Our slider is a simple and elegant image carousel. * You can also have captions that will be transitioned on their own depending on their alignment. * You can also have indicators that show up on the bottom of the slider. * * @param CarouselOptions options the slider options or the string "start" to start the animation or "pauze" to pauze the animation */ carousel(options?: Materialize.CarouselOptions): JQuery; /** * Our slider is a simple and elegant image carousel. * You can also have captions that will be transitioned on their own depending on their alignment. * You can also have indicators that show up on the bottom of the slider. * * @param string method the methods to pause, start, move to next and move to previous slide. */ carousel(method: string, count?: number): JQuery; /** * Modal for dialog boxes, confirmation messages, or other content that can be called up. * * To customize the behaviour of a modal * * @param ModalOptions options the lean modal options */ modal(options?: Materialize.ModalOptions): void; /** * Modal for dialog boxes, confirmation messages, or other content that can be called up. * * For opening and closing modals programatically. * * @param string action action to do (`open` or `close) */ modal(action: string, options?: Materialize.ModalOptions): void; /** * Parallax is an effect where the background content or image in this case, is moved at a different speed than the foreground content while scrolling. */ parallax(): JQuery; /** * Pushpin is a fixed positioning plugin. * * @param PushpinOptions options the push pin options */ pushpin(options?: Materialize.PushpinOptions): JQuery; /** * Scrollspy is a jQuery plugin that tracks certain elements and which element the user's screen is currently centered on. * * @param ScrollSpyOptions options the scroll spy options */ scrollSpy(options?: Materialize.ScrollSpyOptions): JQuery; /** * A slide out menu. You can add a dropdown to your sidebar by using our collapsible component. * * @param SideNavOptions | string methodOrOptions the slide navigation options or a string with "show" to reveal or "hide" to hide the menu */ sideNav(methodOrOptions?: Materialize.SideNavOptions | string): void; /** * Programmatically trigger the tab change event * * @param string method : the method to call (always "select_tab") * @param string tab : id of the tab to open */ tabs(method?: string, tab?: string): JQuery; /** * Tab Initialization with options * * @param TabOptions options jQuery plugin options */ tabs(options?: Materialize.TabOptions): JQuery; /** * Chip Initialization * * @param ChipOptions options Material chip options */ material_chip(options?: Materialize.ChipOptions): JQuery; /** * To access chip data * * @param string method name of the method to invoke */ material_chip(method: string): Materialize.ChipDataObject[] | Materialize.ChipDataObject; /** * Add an autocomplete dropdown below your input to suggest possible values. * @param autocompleteOptions options : @see autocompleteOptions for possible options */ autocomplete(options: Materialize.AutoCompleteOptions): JQuery; /** * Feature discovery - open and close a tap target * @param string action : either `'open'` or `'close'` */ tapTarget(action?: string): JQuery; }
the_stack
import {Component, ViewChild} from '@angular/core'; import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {FormsModule} from '@angular/forms'; import {By} from '@angular/platform-browser'; import * as moment from 'moment'; import {DlDateTimeNumberModule, DlDateTimePickerComponent, DlDateTimePickerModule} from '../../../public-api'; import { dispatchKeyboardEvent, DOWN_ARROW, END, ENTER, HOME, LEFT_ARROW, PAGE_DOWN, PAGE_UP, RIGHT_ARROW, SPACE, UP_ARROW } from '../dispatch-events'; import {DEC, JAN} from '../month-constants'; @Component({ template: '<dl-date-time-picker startView="month"></dl-date-time-picker>' }) class MonthStartViewComponent { @ViewChild(DlDateTimePickerComponent, {static: false}) picker: DlDateTimePickerComponent<number>; } @Component({ template: '<dl-date-time-picker startView="month" [(ngModel)]="selectedDate"></dl-date-time-picker>' }) class MonthStartViewWithNgModelComponent { @ViewChild(DlDateTimePickerComponent, {static: false}) picker: DlDateTimePickerComponent<number>; selectedDate = new Date(2017, DEC, 22).getTime(); } describe('DlDateTimePickerComponent startView=month', () => { beforeEach(async(() => { return TestBed.configureTestingModule({ imports: [ FormsModule, DlDateTimeNumberModule, DlDateTimePickerModule, ], declarations: [ MonthStartViewComponent, MonthStartViewWithNgModelComponent ] }) .compileComponents(); })); describe('default behavior ', () => { let component: MonthStartViewComponent; let fixture: ComponentFixture<MonthStartViewComponent>; beforeEach(async(() => { fixture = TestBed.createComponent(MonthStartViewComponent); fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); component = fixture.componentInstance; }); })); it('should start with month-view', () => { const monthView = fixture.debugElement.query(By.css('.dl-abdtp-month-view')); expect(monthView).toBeTruthy(); }); it('should contain 0 .dl-abdtp-col-label elements', () => { const dayLabelElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-col-label')); expect(dayLabelElements.length).toBe(0); }); it('should contain 12 .dl-abdtp-month elements', () => { const monthElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-month')); expect(monthElements.length).toBe(12); }); it('should contain 1 .dl-abdtp-now element for the current month', () => { const currentElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-now')); expect(currentElements.length).toBe(1); expect(currentElements[0].nativeElement.textContent.trim()).toBe(moment().format('MMM')); expect(currentElements[0].attributes['dl-abdtp-value']).toBe(moment().startOf('month').valueOf().toString()); }); it('should NOT contain an .dl-abdtp-now element in the previous year', () => { // click on the left button to move to the previous hour fixture.debugElement.query(By.css('.dl-abdtp-left-button')).nativeElement.click(); fixture.detectChanges(); const currentElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-now')); expect(currentElements.length).toBe(0); }); it('should NOT contain an .dl-abdtp-now element in the next year', () => { // click on the left button to move to the previous hour fixture.debugElement.query(By.css('.dl-abdtp-right-button')).nativeElement.click(); fixture.detectChanges(); const currentElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-now')); expect(currentElements.length).toBe(0); }); it('should contain 1 [tabindex=1] element', () => { const tabIndexElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-month[tabindex="0"]')); expect(tabIndexElements.length).toBe(1); }); it('should contain 1 .dl-abdtp-active element for the current month', () => { const currentElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-active')); expect(currentElements.length).toBe(1); expect(currentElements[0].nativeElement.textContent.trim()).toBe(moment().format('MMM')); expect(currentElements[0].attributes['dl-abdtp-value']).toBe(moment().startOf('month').valueOf().toString()); }); it('should contain 1 .dl-abdtp-selected element for the current month', () => { component.picker.value = moment().startOf('month').valueOf(); fixture.detectChanges(); // Bug: The value change is not detected until there is some user interaction // **ONlY** when there is no ngModel binding on the component. // I think it is related to https://github.com/angular/angular/issues/10816 const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')).nativeElement; activeElement.focus(); dispatchKeyboardEvent(activeElement, 'keydown', HOME); fixture.detectChanges(); const selectedElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-selected')); expect(selectedElements.length).toBe(1); expect(selectedElements[0].nativeElement.textContent.trim()).toBe(moment().format('MMM')); expect(selectedElements[0].attributes['dl-abdtp-value']).toBe(moment().startOf('month').valueOf().toString()); }); }); describe('ngModel=2017-12-22', () => { let component: MonthStartViewWithNgModelComponent; let fixture: ComponentFixture<MonthStartViewWithNgModelComponent>; beforeEach(async(() => { fixture = TestBed.createComponent(MonthStartViewWithNgModelComponent); fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); component = fixture.componentInstance; }); })); it('should contain .dl-abdtp-view-label element with "2017"', () => { const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label')); expect(viewLabel.nativeElement.textContent.trim()).toBe('2017'); }); it('should contain 12 .dl-abdtp-month elements with start of month utc time as class and role of gridcell', () => { const expectedValues = new Array(12) .fill(JAN) .map((january, index) => new Date(2017, january + index, 1).getTime()); const monthElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-month')); expect(monthElements.length).toBe(12); monthElements.forEach((monthElement, index) => { const expectedValue = expectedValues[index]; const ariaLabel = moment(expectedValue).format('MMM YYYY'); expect(monthElement.attributes['dl-abdtp-value']).toBe(expectedValue.toString(10), index); expect(monthElement.attributes['role']).toBe('gridcell', index); expect(monthElement.attributes['aria-label']).toBe(ariaLabel, index); }); }); it('.dl-abdtp-left-button should contain a title', () => { const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-left-button')); expect(leftButton.attributes['title']).toBe('Go to 2016'); }); it('.dl-abdtp-left-button should contain aria-label', () => { const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-left-button')); expect(leftButton.attributes['aria-label']).toBe('Go to 2016'); }); it('should have a dl-abdtp-value attribute with the previous year value on .dl-abdtp-left-button ', () => { const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-left-button')); expect(leftButton.attributes['dl-abdtp-value']).toBe(new Date(2016, JAN, 1).getTime().toString()); }); it('should switch to previous year value after clicking .dl-abdtp-left-button', () => { const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-left-button')); leftButton.nativeElement.click(); fixture.detectChanges(); const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label')); expect(viewLabel.nativeElement.textContent.trim()).toBe('2016'); const monthElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-month')); expect(monthElements[0].nativeElement.textContent.trim()).toBe('Jan'); expect(monthElements[0].attributes['dl-abdtp-value']).toBe(new Date(2016, JAN, 1).getTime().toString()); }); it('.dl-abdtp-right-button should contain a title', () => { const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-right-button')); expect(leftButton.attributes['title']).toBe('Go to 2018'); }); it('.dl-abdtp-right-button should contain aria-label', () => { const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-right-button')); expect(leftButton.attributes['aria-label']).toBe('Go to 2018'); }); it('should have a dl-abdtp-value attribute with the next year value on .dl-abdtp-right-button ', () => { const rightButton = fixture.debugElement.query(By.css('.dl-abdtp-right-button')); expect(rightButton.attributes['dl-abdtp-value']).toBe(new Date(2018, JAN, 1).getTime().toString()); }); it('should switch to next year value after clicking .dl-abdtp-right-button', () => { const rightButton = fixture.debugElement.query(By.css('.dl-abdtp-right-button')); rightButton.nativeElement.click(); fixture.detectChanges(); const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label')); expect(viewLabel.nativeElement.textContent.trim()).toBe('2018'); const monthElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-month')); expect(monthElements[0].nativeElement.textContent.trim()).toBe('Jan'); expect(monthElements[0].attributes['dl-abdtp-value']).toBe(new Date(2018, JAN, 1).getTime().toString()); }); it('.dl-abdtp-up-button should contain a title', () => { const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-up-button')); expect(leftButton.attributes['title']).toBe('Go to 2017'); }); it('.dl-abdtp-up-button should contain aria-label', () => { const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-up-button')); expect(leftButton.attributes['aria-label']).toBe('Go to 2017'); }); it('should switch to year view after clicking .dl-abdtp-up-button', () => { const upButton = fixture.debugElement.query(By.css('.dl-abdtp-up-button')); upButton.nativeElement.click(); fixture.detectChanges(); const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label')); expect(viewLabel.nativeElement.textContent).toBe('2010-2019'); const yearView = fixture.debugElement.query(By.css('.dl-abdtp-year-view')); expect(yearView).toBeTruthy(); }); it('should not emit a change event when clicking .dl-abdtp-month', () => { const changeSpy = jasmine.createSpy('change listener'); component.picker.change.subscribe(changeSpy); const monthElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-month')); monthElements[9].nativeElement.click(); // OCT fixture.detectChanges(); expect(changeSpy).not.toHaveBeenCalled(); }); it('should change to .dl-abdtp-day-view when selecting .dl-abdtp-month', () => { const monthElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-month')); monthElements[0].nativeElement.click(); // 2009 fixture.detectChanges(); const monthView = fixture.debugElement.query(By.css('.dl-abdtp-month-view')); expect(monthView).toBeFalsy(); const dayView = fixture.debugElement.query(By.css('.dl-abdtp-day-view')); expect(dayView).toBeTruthy(); }); it('should have one .dl-abdtp-active element', () => { const activeElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-active')); expect(activeElements.length).toBe(1); }); it('should change .dl-abdtp-active element on right arrow', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); activeElement.nativeElement.focus(); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', RIGHT_ARROW); fixture.detectChanges(); const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(newActiveElement.nativeElement.textContent).toBe('Jan'); }); it('should change to next year when last .dl-abdtp-month is .dl-abdtp-active element and pressing on right arrow', () => { (component.picker as any)._model.activeDate = new Date(2017, DEC, 1).getTime(); fixture.detectChanges(); dispatchKeyboardEvent(fixture.debugElement.query(By.css('.dl-abdtp-active')).nativeElement, 'keydown', RIGHT_ARROW); // 2018 fixture.detectChanges(); const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Jan'); const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label')); expect(viewLabel.nativeElement.textContent.trim()).toBe('2018'); }); it('should change .dl-abdtp-active element on left arrow', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); activeElement.nativeElement.focus(); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', LEFT_ARROW); fixture.detectChanges(); const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(newActiveElement.nativeElement.textContent).toBe('Nov'); }); it('should change to previous year when first .dl-abdtp-month is .dl-abdtp-active element and pressing on left arrow', () => { (component.picker as any)._model.activeDate = new Date(2017, JAN, 1).getTime(); fixture.detectChanges(); dispatchKeyboardEvent(fixture.debugElement.query(By.css('.dl-abdtp-active')).nativeElement, 'keydown', LEFT_ARROW); // 2019 fixture.detectChanges(); const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label')); expect(viewLabel.nativeElement.textContent.trim()).toBe('2016'); }); it('should change .dl-abdtp-active element on up arrow', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); activeElement.nativeElement.focus(); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', UP_ARROW); fixture.detectChanges(); const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(newActiveElement.nativeElement.textContent).toBe('Aug'); }); it('should change to previous year when first .dl-abdtp-month is .dl-abdtp-active element and pressing on up arrow', () => { (component.picker as any)._model.activeDate = new Date(2017, JAN, 1).getTime(); fixture.detectChanges(); dispatchKeyboardEvent(fixture.debugElement.query(By.css('.dl-abdtp-active')).nativeElement, 'keydown', UP_ARROW); // 2019 fixture.detectChanges(); const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Sep'); const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label')); expect(viewLabel.nativeElement.textContent.trim()).toBe('2016'); }); it('should change .dl-abdtp-active element on down arrow', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); activeElement.nativeElement.focus(); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', DOWN_ARROW); fixture.detectChanges(); const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(newActiveElement.nativeElement.textContent).toBe('Apr'); }); it('should change .dl-abdtp-active element on page-up (fn+up-arrow)', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); activeElement.nativeElement.focus(); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', PAGE_UP); fixture.detectChanges(); const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(newActiveElement.nativeElement.textContent).toBe('Dec'); const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label')); expect(viewLabel.nativeElement.textContent.trim()).toBe('2016'); }); it('should change .dl-abdtp-active element on page-down (fn+down-arrow)', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); activeElement.nativeElement.focus(); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', PAGE_DOWN); fixture.detectChanges(); const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(newActiveElement.nativeElement.textContent).toBe('Dec'); const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label')); expect(viewLabel.nativeElement.textContent.trim()).toBe('2018'); }); it('should change .dl-abdtp-active element to first .dl-abdtp-month on HOME', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); activeElement.nativeElement.focus(); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', HOME); fixture.detectChanges(); const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(newActiveElement.nativeElement.textContent).toBe('Jan'); }); it('should change .dl-abdtp-active element to last .dl-abdtp-month on END', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); activeElement.nativeElement.focus(); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', END); fixture.detectChanges(); const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(newActiveElement.nativeElement.textContent).toBe('Dec'); }); it('should do nothing when hitting non-supported key', () => { (component.picker as any)._model.activeDate = new Date(2017, DEC, 1).getTime(); fixture.detectChanges(); let activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', 'A'); fixture.detectChanges(); activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); expect(activeElement.nativeElement.textContent).toBe('Dec'); }); it('should change to .dl-abdtp-day-view when hitting ENTER', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', ENTER); fixture.detectChanges(); const monthView = fixture.debugElement.query(By.css('.dl-abdtp-month-view')); expect(monthView).toBeFalsy(); const dayView = fixture.debugElement.query(By.css('.dl-abdtp-day-view')); expect(dayView).toBeTruthy(); }); it('should change to .dl-abdtp-day-view when hitting SPACE', () => { const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')); dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', SPACE); fixture.detectChanges(); const monthView = fixture.debugElement.query(By.css('.dl-abdtp-month-view')); expect(monthView).toBeFalsy(); const dayView = fixture.debugElement.query(By.css('.dl-abdtp-day-view')); expect(dayView).toBeTruthy(); }); }); });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormCase { interface Header extends DevKit.Controls.IHeader { /** Date and time when the record was created. */ CreatedOn: DevKit.Controls.DateTime; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Select the case's status. */ StatusCode: DevKit.Controls.OptionSet; } interface tab__Enhanced_SLA_Details_Tab_Sections { Applicable_SLAENHANCED: DevKit.Controls.Section; SLAKPIInstances: DevKit.Controls.Section; } interface tab_ADDITIONALDETAILS_TAB_Sections { escalations: DevKit.Controls.Section; parentcaseandtype: DevKit.Controls.Section; responses: DevKit.Controls.Section; } interface tab_AssociatedKnowledgeBaseRecords_Sections { Articles: DevKit.Controls.Section; KnowledgeArticles: DevKit.Controls.Section; } interface tab_CASERELATIONSHIP_TAB_Sections { ChildCases: DevKit.Controls.Section; MergedCases: DevKit.Controls.Section; Research: DevKit.Controls.Section; Solutions: DevKit.Controls.Section; } interface tab_DeviceInsightsTab_Sections { DeviceInsightsSection: DevKit.Controls.Section; } interface tab_FieldService_Sections { tab_8_section_1: DevKit.Controls.Section; tab_8_section_2: DevKit.Controls.Section; } interface tab_general_Sections { Applicable_SLASTANDARD: DevKit.Controls.Section; Customer: DevKit.Controls.Section; Details: DevKit.Controls.Section; TabsControl: DevKit.Controls.Section; } interface tab_KBARTICLE_TAB_Sections { contract_and_product_information: DevKit.Controls.Section; kb_article: DevKit.Controls.Section; } interface tab_SOCIALDETAILS_TAB_Sections { scores: DevKit.Controls.Section; social: DevKit.Controls.Section; social3: DevKit.Controls.Section; } interface tab__Enhanced_SLA_Details_Tab extends DevKit.Controls.ITab { Section: tab__Enhanced_SLA_Details_Tab_Sections; } interface tab_ADDITIONALDETAILS_TAB extends DevKit.Controls.ITab { Section: tab_ADDITIONALDETAILS_TAB_Sections; } interface tab_AssociatedKnowledgeBaseRecords extends DevKit.Controls.ITab { Section: tab_AssociatedKnowledgeBaseRecords_Sections; } interface tab_CASERELATIONSHIP_TAB extends DevKit.Controls.ITab { Section: tab_CASERELATIONSHIP_TAB_Sections; } interface tab_DeviceInsightsTab extends DevKit.Controls.ITab { Section: tab_DeviceInsightsTab_Sections; } interface tab_FieldService extends DevKit.Controls.ITab { Section: tab_FieldService_Sections; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface tab_KBARTICLE_TAB extends DevKit.Controls.ITab { Section: tab_KBARTICLE_TAB_Sections; } interface tab_SOCIALDETAILS_TAB extends DevKit.Controls.ITab { Section: tab_SOCIALDETAILS_TAB_Sections; } interface Tabs { _Enhanced_SLA_Details_Tab: tab__Enhanced_SLA_Details_Tab; ADDITIONALDETAILS_TAB: tab_ADDITIONALDETAILS_TAB; AssociatedKnowledgeBaseRecords: tab_AssociatedKnowledgeBaseRecords; CASERELATIONSHIP_TAB: tab_CASERELATIONSHIP_TAB; DeviceInsightsTab: tab_DeviceInsightsTab; FieldService: tab_FieldService; general: tab_general; KBARTICLE_TAB: tab_KBARTICLE_TAB; SOCIALDETAILS_TAB: tab_SOCIALDETAILS_TAB; } interface Body { Tab: Tabs; /** Type the number of service units that were actually required to resolve the case. */ ActualServiceUnits: DevKit.Controls.Integer; /** Details whether the profile is blocked or not. */ BlockedProfile: DevKit.Controls.Boolean; /** Select how contact about the case was originated, such as email, phone, or web, for use in reporting and analysis. */ CaseOriginCode: DevKit.Controls.OptionSet; /** Select the type of case to identify the incident for use in case routing and analysis. */ CaseTypeCode: DevKit.Controls.OptionSet; /** Choose the contract line that the case should be logged under to make sure the customer is charged correctly. */ ContractDetailId: DevKit.Controls.Lookup; /** Choose the service contract that the case should be logged under to make sure the customer is eligible for support services. */ ContractId: DevKit.Controls.Lookup; /** Select the service level for the case to make sure the case is handled correctly. */ ContractServiceLevelCode: DevKit.Controls.OptionSet; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select the customer's level of satisfaction with the handling and resolution of the case. */ CustomerSatisfactionCode: DevKit.Controls.OptionSet; /** Type additional information to describe the case to assist the service team in reaching a resolution. */ Description: DevKit.Controls.String; /** Choose the entitlement that is applicable for the case. */ EntitlementId: DevKit.Controls.Lookup; /** Indicates the date and time when the case was escalated. */ EscalatedOn: DevKit.Controls.DateTime; /** Indicates if the first response has been sent. */ FirstResponseSent: DevKit.Controls.Boolean; /** Enter the date by which a customer service representative has to follow up with the customer on this case. */ FollowupBy: DevKit.Controls.Date; /** Will contain the Influencer score coming from NetBreeze. */ InfluenceScore: DevKit.Controls.Double; /** Indicates if the case has been escalated. */ IsEscalated: DevKit.Controls.Boolean; /** Choose the article that contains additional information or a resolution for the case, for reference during research or follow up with the customer. */ KbArticleId: DevKit.Controls.Lookup; /** Shows whether the post originated as a public or private message. */ MessageTypeCode: DevKit.Controls.OptionSet; /** Case's functional location */ msdyn_FunctionalLocation: DevKit.Controls.Lookup; /** Unique identifier for Incident Type associated with Case. */ msdyn_IncidentType: DevKit.Controls.Lookup; /** The iot alert that initiated this case */ msdyn_iotalert: DevKit.Controls.Lookup; /** The iot alert that initiated this case */ msdyn_iotalert_1: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Choose the parent case for a case. */ ParentCaseId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; /** Choose the product associated with the case to identify warranty, service, or other product issues and be able to report the number of incidents for each product. */ ProductId: DevKit.Controls.Lookup; /** Type the serial number of the product that is associated with this case, so that the number of cases per product can be reported. */ ProductSerialNumber: DevKit.Controls.String; /** Enter the date by when the case must be resolved. */ ResolveBy: DevKit.Controls.DateTime; /** For internal use only. */ ResponseBy: DevKit.Controls.DateTime; /** Value derived after assessing words commonly associated with a negative, neutral, or positive sentiment that occurs in a social post. Sentiment information can also be reported as numeric values. */ SentimentValue: DevKit.Controls.Double; /** Unique identifier of the social profile with which the case is associated. */ SocialProfileId: DevKit.Controls.Lookup; /** Choose the subject for the case, such as catalog request or product complaint, so customer service managers can identify frequent requests or problem areas. Administrators can configure subjects under Business Management in the Settings area. */ SubjectId: DevKit.Controls.Lookup; /** Shows the case number for customer reference and searching capabilities. This cannot be modified. */ TicketNumber: DevKit.Controls.String; /** Type a subject or descriptive name, such as the request, issue, or company name, to identify the case in Microsoft Dynamics 365 views. */ Title: DevKit.Controls.String; } interface Navigation { nav_msdyn_incident_msdyn_workorder_ServiceRequest: DevKit.Controls.NavigationItem, navActivities: DevKit.Controls.NavigationItem, navActivityHistory: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface quickForm_customerpane_qfc_Body { EMailAddress1: DevKit.Controls.QuickView; FullName: DevKit.Controls.QuickView; MobilePhone: DevKit.Controls.QuickView; ParentCustomerId: DevKit.Controls.QuickView; Telephone1: DevKit.Controls.QuickView; } interface quickForm_firstresponseslaquickform_Body { } interface quickForm_resolvebyslaquickform_Body { } interface quickForm_customerpane_qfc extends DevKit.Controls.IQuickView { Body: quickForm_customerpane_qfc_Body; } interface quickForm_firstresponseslaquickform extends DevKit.Controls.IQuickView { Body: quickForm_firstresponseslaquickform_Body; } interface quickForm_resolvebyslaquickform extends DevKit.Controls.IQuickView { Body: quickForm_resolvebyslaquickform_Body; } interface QuickForm { customerpane_qfc: quickForm_customerpane_qfc; firstresponseslaquickform: quickForm_firstresponseslaquickform; resolvebyslaquickform: quickForm_resolvebyslaquickform; } interface ProcessPhone_to_Case_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface ProcessCase_to_Work_Order_Business_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Phone_to_Case_Process: ProcessPhone_to_Case_Process; Case_to_Work_Order_Business_Process: ProcessCase_to_Work_Order_Business_Process; } interface Grid { RelatedSolutionGrid: DevKit.Controls.Grid; MergedCasesGrid: DevKit.Controls.Grid; ChildCasesGrid: DevKit.Controls.Grid; Associated_Articles: DevKit.Controls.Grid; Associated_KnowledgeArticles: DevKit.Controls.Grid; SLA_KPI_Instances_List: DevKit.Controls.Grid; } } class FormCase extends DevKit.IForm { /** * DynamicsCrm.DevKit form Case * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Case */ Body: DevKit.FormCase.Body; /** The Header section of form Case */ Header: DevKit.FormCase.Header; /** The Navigation of form Case */ Navigation: DevKit.FormCase.Navigation; /** The QuickForm of form Case */ QuickForm: DevKit.FormCase.QuickForm; /** The Process of form Case */ Process: DevKit.FormCase.Process; /** The Grid of form Case */ Grid: DevKit.FormCase.Grid; } namespace FormCase_for_Interactive_experience { interface Header extends DevKit.Controls.IHeader { /** Date and time when the record was created. */ CreatedOn: DevKit.Controls.DateTime; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Select the case's status. */ StatusCode: DevKit.Controls.OptionSet; } interface tab__Enhanced_SLA_Details_Tab_Sections { SLAKPIInstances: DevKit.Controls.Section; } interface tab_CASERELATIONSHIP_TAB_Sections { ChildCases: DevKit.Controls.Section; KnowledgeArticles: DevKit.Controls.Section; MergedCases: DevKit.Controls.Section; Solutions: DevKit.Controls.Section; } interface tab_Details_Sections { Additional_Details: DevKit.Controls.Section; Applicable_SLASTANDARD: DevKit.Controls.Section; Case_Details: DevKit.Controls.Section; Social_Response: DevKit.Controls.Section; } interface tab_DeviceInsightsTab_Sections { DeviceInsightsSection: DevKit.Controls.Section; } interface tab_DeviceTab_Sections { DeviceSection: DevKit.Controls.Section; } interface tab_Summary_Sections { Case_Details_Summary: DevKit.Controls.Section; General_Info: DevKit.Controls.Section; ref_pan_Related: DevKit.Controls.Section; SLAKPI_Timer_Section: DevKit.Controls.Section; Timeline: DevKit.Controls.Section; } interface tab__Enhanced_SLA_Details_Tab extends DevKit.Controls.ITab { Section: tab__Enhanced_SLA_Details_Tab_Sections; } interface tab_CASERELATIONSHIP_TAB extends DevKit.Controls.ITab { Section: tab_CASERELATIONSHIP_TAB_Sections; } interface tab_Details extends DevKit.Controls.ITab { Section: tab_Details_Sections; } interface tab_DeviceInsightsTab extends DevKit.Controls.ITab { Section: tab_DeviceInsightsTab_Sections; } interface tab_DeviceTab extends DevKit.Controls.ITab { Section: tab_DeviceTab_Sections; } interface tab_Summary extends DevKit.Controls.ITab { Section: tab_Summary_Sections; } interface Tabs { _Enhanced_SLA_Details_Tab: tab__Enhanced_SLA_Details_Tab; CASERELATIONSHIP_TAB: tab_CASERELATIONSHIP_TAB; Details: tab_Details; DeviceInsightsTab: tab_DeviceInsightsTab; DeviceTab: tab_DeviceTab; Summary: tab_Summary; } interface Body { Tab: Tabs; /** Details whether the profile is blocked or not. */ BlockedProfile: DevKit.Controls.Boolean; /** Select how contact about the case was originated, such as email, phone, or web, for use in reporting and analysis. */ CaseOriginCode: DevKit.Controls.OptionSet; /** Select how contact about the case was originated, such as email, phone, or web, for use in reporting and analysis. */ CaseOriginCode_1: DevKit.Controls.OptionSet; /** Select the type of case to identify the incident for use in case routing and analysis. */ CaseTypeCode: DevKit.Controls.OptionSet; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId_1: DevKit.Controls.Lookup; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId_2: DevKit.Controls.Lookup; /** Type additional information to describe the case to assist the service team in reaching a resolution. */ Description: DevKit.Controls.String; /** Type additional information to describe the case to assist the service team in reaching a resolution. */ Description_1: DevKit.Controls.String; /** Choose the entitlement that is applicable for the case. */ EntitlementId: DevKit.Controls.Lookup; /** Choose the entitlement that is applicable for the case. */ EntitlementId_1: DevKit.Controls.Lookup; /** Indicates the date and time when the case was escalated. */ EscalatedOn: DevKit.Controls.DateTime; /** Indicates if the first response has been sent. */ FirstResponseSent: DevKit.Controls.Boolean; /** Enter the date by which a customer service representative has to follow up with the customer on this case. */ FollowupBy: DevKit.Controls.Date; /** Will contain the Influencer score coming from NetBreeze. */ InfluenceScore: DevKit.Controls.Double; /** Indicates if the case has been escalated. */ IsEscalated: DevKit.Controls.Boolean; /** Shows whether the post originated as a public or private message. */ MessageTypeCode: DevKit.Controls.OptionSet; /** The iot alert that initiated this case */ msdyn_iotalert: DevKit.Controls.Lookup; /** The iot alert that initiated this case */ msdyn_iotalert_1: DevKit.Controls.Lookup; /** The iot alert that initiated this case */ msdyn_iotalert_2: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Choose the parent case for a case. */ ParentCaseId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; /** Choose the product associated with the case to identify warranty, service, or other product issues and be able to report the number of incidents for each product. */ ProductId: DevKit.Controls.Lookup; /** Choose the product associated with the case to identify warranty, service, or other product issues and be able to report the number of incidents for each product. */ ProductId_1: DevKit.Controls.Lookup; /** Enter the date by when the case must be resolved. */ ResolveBy: DevKit.Controls.DateTime; /** For internal use only. */ ResponseBy: DevKit.Controls.DateTime; /** Value derived after assessing words commonly associated with a negative, neutral, or positive sentiment that occurs in a social post. Sentiment information can also be reported as numeric values. */ SentimentValue: DevKit.Controls.Double; /** Unique identifier of the social profile with which the case is associated. */ SocialProfileId: DevKit.Controls.Lookup; /** Choose the subject for the case, such as catalog request or product complaint, so customer service managers can identify frequent requests or problem areas. Administrators can configure subjects under Business Management in the Settings area. */ SubjectId: DevKit.Controls.Lookup; /** Choose the subject for the case, such as catalog request or product complaint, so customer service managers can identify frequent requests or problem areas. Administrators can configure subjects under Business Management in the Settings area. */ SubjectId_1: DevKit.Controls.Lookup; /** Shows the case number for customer reference and searching capabilities. This cannot be modified. */ TicketNumber: DevKit.Controls.String; /** Shows the case number for customer reference and searching capabilities. This cannot be modified. */ TicketNumber_1: DevKit.Controls.String; /** Type a subject or descriptive name, such as the request, issue, or company name, to identify the case in Microsoft Dynamics 365 views. */ Title: DevKit.Controls.String; similarCaseRecordcontrol_id: DevKit.Controls.ActionCards; /** Type a subject or descriptive name, such as the request, issue, or company name, to identify the case in Microsoft Dynamics 365 views. */ Title_1: DevKit.Controls.String; } interface quickForm_customerpane_qfc_Body { EMailAddress1: DevKit.Controls.QuickView; FullName: DevKit.Controls.QuickView; MobilePhone: DevKit.Controls.QuickView; ParentCustomerId: DevKit.Controls.QuickView; Telephone1: DevKit.Controls.QuickView; } interface quickForm_FirstResponseByKPI_Body { } interface quickForm_ResolveByKPI_Body { } interface quickForm_customerpane_qfc extends DevKit.Controls.IQuickView { Body: quickForm_customerpane_qfc_Body; } interface quickForm_FirstResponseByKPI extends DevKit.Controls.IQuickView { Body: quickForm_FirstResponseByKPI_Body; } interface quickForm_ResolveByKPI extends DevKit.Controls.IQuickView { Body: quickForm_ResolveByKPI_Body; } interface QuickForm { customerpane_qfc: quickForm_customerpane_qfc; FirstResponseByKPI: quickForm_FirstResponseByKPI; ResolveByKPI: quickForm_ResolveByKPI; } interface ProcessPhone_to_Case_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface ProcessCase_to_Work_Order_Business_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Phone_to_Case_Process: ProcessPhone_to_Case_Process; Case_to_Work_Order_Business_Process: ProcessCase_to_Work_Order_Business_Process; } interface Grid { MergedCasesGrid: DevKit.Controls.Grid; ChildCasesGrid: DevKit.Controls.Grid; Associated_KnowledgeArticles: DevKit.Controls.Grid; SLA_KPI_Instances_List: DevKit.Controls.Grid; Devices: DevKit.Controls.Grid; } } class FormCase_for_Interactive_experience extends DevKit.IForm { /** * DynamicsCrm.DevKit form Case_for_Interactive_experience * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Case_for_Interactive_experience */ Body: DevKit.FormCase_for_Interactive_experience.Body; /** The Header section of form Case_for_Interactive_experience */ Header: DevKit.FormCase_for_Interactive_experience.Header; /** The QuickForm of form Case_for_Interactive_experience */ QuickForm: DevKit.FormCase_for_Interactive_experience.QuickForm; /** The Process of form Case_for_Interactive_experience */ Process: DevKit.FormCase_for_Interactive_experience.Process; /** The Grid of form Case_for_Interactive_experience */ Grid: DevKit.FormCase_for_Interactive_experience.Grid; } namespace FormCase_for_Multisession_experience { interface Header extends DevKit.Controls.IHeader { /** Select how contact about the case was originated, such as email, phone, or web, for use in reporting and analysis. */ CaseOriginCode: DevKit.Controls.OptionSet; /** Date and time when the record was created. */ CreatedOn: DevKit.Controls.DateTime; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Shows the case number for customer reference and searching capabilities. This cannot be modified. */ TicketNumber: DevKit.Controls.String; } interface tab_CASERELATIONSHIP_TAB_Sections { Applicable_SLASTANDARD: DevKit.Controls.Section; Case_Details: DevKit.Controls.Section; ChildCases: DevKit.Controls.Section; KnowledgeArticles: DevKit.Controls.Section; MergedCases: DevKit.Controls.Section; RelatedCases: DevKit.Controls.Section; } interface tab_Summary_Sections { Case_Details_Summary: DevKit.Controls.Section; TabsControl: DevKit.Controls.Section; } interface tab_CASERELATIONSHIP_TAB extends DevKit.Controls.ITab { Section: tab_CASERELATIONSHIP_TAB_Sections; } interface tab_Summary extends DevKit.Controls.ITab { Section: tab_Summary_Sections; } interface Tabs { CASERELATIONSHIP_TAB: tab_CASERELATIONSHIP_TAB; Summary: tab_Summary; } interface Body { Tab: Tabs; /** Select the type of case to identify the incident for use in case routing and analysis. */ CaseTypeCode: DevKit.Controls.OptionSet; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Type additional information to describe the case to assist the service team in reaching a resolution. */ Description: DevKit.Controls.String; /** Choose the entitlement that is applicable for the case. */ EntitlementId: DevKit.Controls.Lookup; /** Indicates the date and time when the case was escalated. */ EscalatedOn: DevKit.Controls.DateTime; /** Indicates if the first response has been sent. */ FirstResponseSent: DevKit.Controls.Boolean; /** Enter the date by which a customer service representative has to follow up with the customer on this case. */ FollowupBy: DevKit.Controls.Date; /** Indicates if the case has been escalated. */ IsEscalated: DevKit.Controls.Boolean; notescontrol: DevKit.Controls.Note; /** Choose the parent case for a case. */ ParentCaseId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Choose the product associated with the case to identify warranty, service, or other product issues and be able to report the number of incidents for each product. */ ProductId: DevKit.Controls.Lookup; /** Enter the date by when the case must be resolved. */ ResolveBy: DevKit.Controls.DateTime; /** For internal use only. */ ResponseBy: DevKit.Controls.DateTime; /** Select the case's status. */ StatusCode: DevKit.Controls.OptionSet; /** Choose the subject for the case, such as catalog request or product complaint, so customer service managers can identify frequent requests or problem areas. Administrators can configure subjects under Business Management in the Settings area. */ SubjectId: DevKit.Controls.Lookup; /** Type a subject or descriptive name, such as the request, issue, or company name, to identify the case in Microsoft Dynamics 365 views. */ Title: DevKit.Controls.String; } interface Navigation { navActivities: DevKit.Controls.NavigationItem, navActivityHistory: DevKit.Controls.NavigationItem } interface ProcessPhone_to_Case_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface ProcessCase_to_Work_Order_Business_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Phone_to_Case_Process: ProcessPhone_to_Case_Process; Case_to_Work_Order_Business_Process: ProcessCase_to_Work_Order_Business_Process; } interface Grid { Associated_KnowledgeArticles: DevKit.Controls.Grid; relatedCases: DevKit.Controls.Grid; ChildCasesGrid: DevKit.Controls.Grid; MergedCasesGrid: DevKit.Controls.Grid; } } class FormCase_for_Multisession_experience extends DevKit.IForm { /** * DynamicsCrm.DevKit form Case_for_Multisession_experience * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Case_for_Multisession_experience */ Body: DevKit.FormCase_for_Multisession_experience.Body; /** The Header section of form Case_for_Multisession_experience */ Header: DevKit.FormCase_for_Multisession_experience.Header; /** The Navigation of form Case_for_Multisession_experience */ Navigation: DevKit.FormCase_for_Multisession_experience.Navigation; /** The Process of form Case_for_Multisession_experience */ Process: DevKit.FormCase_for_Multisession_experience.Process; /** The Grid of form Case_for_Multisession_experience */ Grid: DevKit.FormCase_for_Multisession_experience.Grid; } namespace FormIncident_Information { interface tab_general_Sections { assignment_information: DevKit.Controls.Section; contract_and_product_information: DevKit.Controls.Section; overview: DevKit.Controls.Section; } interface tab_notesandkb_Sections { kb_article: DevKit.Controls.Section; notes: DevKit.Controls.Section; } interface tab_tab_recordwall_Sections { tab_recordwall_section_1: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface tab_notesandkb extends DevKit.Controls.ITab { Section: tab_notesandkb_Sections; } interface tab_tab_recordwall extends DevKit.Controls.ITab { Section: tab_tab_recordwall_Sections; } interface Tabs { general: tab_general; notesandkb: tab_notesandkb; tab_recordwall: tab_tab_recordwall; } interface Body { Tab: Tabs; /** Select how contact about the case was originated, such as email, phone, or web, for use in reporting and analysis. */ CaseOriginCode: DevKit.Controls.OptionSet; /** Select the type of case to identify the incident for use in case routing and analysis. */ CaseTypeCode: DevKit.Controls.OptionSet; /** Choose the contract line that the case should be logged under to make sure the customer is charged correctly. */ ContractDetailId: DevKit.Controls.Lookup; /** Choose the service contract that the case should be logged under to make sure the customer is eligible for support services. */ ContractId: DevKit.Controls.Lookup; /** Select the service level for the case to make sure the case is handled correctly. */ ContractServiceLevelCode: DevKit.Controls.OptionSet; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select the customer's level of satisfaction with the handling and resolution of the case. */ CustomerSatisfactionCode: DevKit.Controls.OptionSet; /** Enter the date by which a customer service representative has to follow up with the customer on this case. */ FollowupBy: DevKit.Controls.Date; /** Choose the article that contains additional information or a resolution for the case, for reference during research or follow up with the customer. */ KbArticleId: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Choose the product associated with the case to identify warranty, service, or other product issues and be able to report the number of incidents for each product. */ ProductId: DevKit.Controls.Lookup; /** Type the serial number of the product that is associated with this case, so that the number of cases per product can be reported. */ ProductSerialNumber: DevKit.Controls.String; /** Select the case's status. */ StatusCode: DevKit.Controls.OptionSet; /** Choose the subject for the case, such as catalog request or product complaint, so customer service managers can identify frequent requests or problem areas. Administrators can configure subjects under Business Management in the Settings area. */ SubjectId: DevKit.Controls.Lookup; /** Type a subject or descriptive name, such as the request, issue, or company name, to identify the case in Microsoft Dynamics 365 views. */ Title: DevKit.Controls.String; WebResource_RecordWall: DevKit.Controls.WebResource; } interface Navigation { navActivities: DevKit.Controls.NavigationItem, navActivityHistory: DevKit.Controls.NavigationItem } interface ProcessPhone_to_Case_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface ProcessCase_to_Work_Order_Business_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Phone_to_Case_Process: ProcessPhone_to_Case_Process; Case_to_Work_Order_Business_Process: ProcessCase_to_Work_Order_Business_Process; } } class FormIncident_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Incident_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Incident_Information */ Body: DevKit.FormIncident_Information.Body; /** The Navigation of form Incident_Information */ Navigation: DevKit.FormIncident_Information.Navigation; /** The Process of form Incident_Information */ Process: DevKit.FormIncident_Information.Process; } namespace FormTimelineWallControl_Case_Main { interface Header extends DevKit.Controls.IHeader { /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface tab_SUMMARY_TAB_Sections { SOCIAL_PANE_TAB: DevKit.Controls.Section; } interface tab_SUMMARY_TAB extends DevKit.Controls.ITab { Section: tab_SUMMARY_TAB_Sections; } interface Tabs { SUMMARY_TAB: tab_SUMMARY_TAB; } interface Body { Tab: Tabs; notescontrol: DevKit.Controls.Note; } interface Navigation { navActivities: DevKit.Controls.NavigationItem, navActivityHistory: DevKit.Controls.NavigationItem } interface ProcessPhone_to_Case_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface ProcessCase_to_Work_Order_Business_Process { /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Phone_to_Case_Process: ProcessPhone_to_Case_Process; Case_to_Work_Order_Business_Process: ProcessCase_to_Work_Order_Business_Process; } } class FormTimelineWallControl_Case_Main extends DevKit.IForm { /** * DynamicsCrm.DevKit form TimelineWallControl_Case_Main * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form TimelineWallControl_Case_Main */ Body: DevKit.FormTimelineWallControl_Case_Main.Body; /** The Header section of form TimelineWallControl_Case_Main */ Header: DevKit.FormTimelineWallControl_Case_Main.Header; /** The Navigation of form TimelineWallControl_Case_Main */ Navigation: DevKit.FormTimelineWallControl_Case_Main.Navigation; /** The Process of form TimelineWallControl_Case_Main */ Process: DevKit.FormTimelineWallControl_Case_Main.Process; } namespace FormCase_Quick_Create_for_Multisession { interface tab_tab_1_Sections { tab_1_column_1_section_1: DevKit.Controls.Section; tab_1_column_2_section_1: DevKit.Controls.Section; tab_1_column_3_section_1: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Select the type of case to identify the incident for use in case routing and analysis. */ CaseTypeCode: DevKit.Controls.OptionSet; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Type additional information to describe the case to assist the service team in reaching a resolution. */ Description: DevKit.Controls.String; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Choose the parent case for a case. */ ParentCaseId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Select the case's status. */ StatusCode: DevKit.Controls.OptionSet; /** Choose the subject for the case, such as catalog request or product complaint, so customer service managers can identify frequent requests or problem areas. Administrators can configure subjects under Business Management in the Settings area. */ SubjectId: DevKit.Controls.Lookup; /** Type a subject or descriptive name, such as the request, issue, or company name, to identify the case in Microsoft Dynamics 365 views. */ Title: DevKit.Controls.String; } } class FormCase_Quick_Create_for_Multisession extends DevKit.IForm { /** * DynamicsCrm.DevKit form Case_Quick_Create_for_Multisession * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Case_Quick_Create_for_Multisession */ Body: DevKit.FormCase_Quick_Create_for_Multisession.Body; } namespace FormApp_for_Outlook_Case_Quick_Create { interface tab_tab_1_Sections { tab_1_column_1_section_1: DevKit.Controls.Section; tab_1_column_2_section_1: DevKit.Controls.Section; tab_1_column_3_section_1: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Select how contact about the case was originated, such as email, phone, or web, for use in reporting and analysis. */ CaseOriginCode: DevKit.Controls.OptionSet; /** Select the type of case to identify the incident for use in case routing and analysis. */ CaseTypeCode: DevKit.Controls.OptionSet; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Type additional information to describe the case to assist the service team in reaching a resolution. */ Description: DevKit.Controls.String; /** Choose the entitlement that is applicable for the case. */ EntitlementId: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Choose the parent case for a case. */ ParentCaseId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; /** Choose the product associated with the case to identify warranty, service, or other product issues and be able to report the number of incidents for each product. */ ProductId: DevKit.Controls.Lookup; /** Enter the date by when the case must be resolved. */ ResolveBy: DevKit.Controls.DateTime; /** For internal use only. */ ResponseBy: DevKit.Controls.DateTime; /** Choose the subject for the case, such as catalog request or product complaint, so customer service managers can identify frequent requests or problem areas. Administrators can configure subjects under Business Management in the Settings area. */ SubjectId: DevKit.Controls.Lookup; /** Type a subject or descriptive name, such as the request, issue, or company name, to identify the case in Microsoft Dynamics 365 views. */ Title: DevKit.Controls.String; } } class FormApp_for_Outlook_Case_Quick_Create extends DevKit.IForm { /** * DynamicsCrm.DevKit form App_for_Outlook_Case_Quick_Create * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form App_for_Outlook_Case_Quick_Create */ Body: DevKit.FormApp_for_Outlook_Case_Quick_Create.Body; } namespace FormCase_Quick_Create { interface tab_tab_1_Sections { tab_1_column_1_section_1: DevKit.Controls.Section; tab_1_column_2_section_1: DevKit.Controls.Section; tab_1_column_3_section_1: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Select how contact about the case was originated, such as email, phone, or web, for use in reporting and analysis. */ CaseOriginCode: DevKit.Controls.OptionSet; /** Select the type of case to identify the incident for use in case routing and analysis. */ CaseTypeCode: DevKit.Controls.OptionSet; /** Select the customer account or contact to provide a quick link to additional customer details, such as account information, activities, and opportunities. */ CustomerId: DevKit.Controls.Lookup; /** Type additional information to describe the case to assist the service team in reaching a resolution. */ Description: DevKit.Controls.String; /** Choose the entitlement that is applicable for the case. */ EntitlementId: DevKit.Controls.Lookup; /** Unique identifier for Incident Type associated with Case. */ msdyn_IncidentType: DevKit.Controls.Lookup; /** The iot alert that initiated this case */ msdyn_iotalert: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Choose the parent case for a case. */ ParentCaseId: DevKit.Controls.Lookup; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.Controls.Lookup; /** Choose the product associated with the case to identify warranty, service, or other product issues and be able to report the number of incidents for each product. */ ProductId: DevKit.Controls.Lookup; /** Enter the date by when the case must be resolved. */ ResolveBy: DevKit.Controls.DateTime; /** For internal use only. */ ResponseBy: DevKit.Controls.DateTime; /** Choose the subject for the case, such as catalog request or product complaint, so customer service managers can identify frequent requests or problem areas. Administrators can configure subjects under Business Management in the Settings area. */ SubjectId: DevKit.Controls.Lookup; /** Type a subject or descriptive name, such as the request, issue, or company name, to identify the case in Microsoft Dynamics 365 views. */ Title: DevKit.Controls.String; } } class FormCase_Quick_Create extends DevKit.IForm { /** * DynamicsCrm.DevKit form Case_Quick_Create * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Case_Quick_Create */ Body: DevKit.FormCase_Quick_Create.Body; } class IncidentApi { /** * DynamicsCrm.DevKit IncidentApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the account with which the case is associated. */ AccountId: DevKit.WebApi.LookupValueReadonly; /** This attribute is used for Sample Service Business Processes. */ ActivitiesComplete: DevKit.WebApi.BooleanValue; /** Type the number of service units that were actually required to resolve the case. */ ActualServiceUnits: DevKit.WebApi.IntegerValue; /** Type the number of service units that were billed to the customer for the case. */ BilledServiceUnits: DevKit.WebApi.IntegerValue; /** Details whether the profile is blocked or not. */ BlockedProfile: DevKit.WebApi.BooleanValue; /** Select how contact about the case was originated, such as email, phone, or web, for use in reporting and analysis. */ CaseOriginCode: DevKit.WebApi.OptionSetValue; /** Select the type of case to identify the incident for use in case routing and analysis. */ CaseTypeCode: DevKit.WebApi.OptionSetValue; /** This attribute is used for Sample Service Business Processes. */ CheckEmail: DevKit.WebApi.BooleanValue; /** Unique identifier of the contact associated with the case. */ ContactId: DevKit.WebApi.LookupValueReadonly; /** Choose the contract line that the case should be logged under to make sure the customer is charged correctly. */ ContractDetailId: DevKit.WebApi.LookupValue; /** Choose the service contract that the case should be logged under to make sure the customer is eligible for support services. */ ContractId: DevKit.WebApi.LookupValue; /** Select the service level for the case to make sure the case is handled correctly. */ ContractServiceLevelCode: DevKit.WebApi.OptionSetValue; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the external party who created the record. */ CreatedByExternalParty: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Tells whether customer service representative has contacted the customer or not. */ CustomerContacted: DevKit.WebApi.BooleanValue; customerid_account: DevKit.WebApi.LookupValue; customerid_contact: DevKit.WebApi.LookupValue; /** Select the customer's level of satisfaction with the handling and resolution of the case. */ CustomerSatisfactionCode: DevKit.WebApi.OptionSetValue; /** Shows whether terms of the associated entitlement should be decremented or not. */ DecrementEntitlementTerm: DevKit.WebApi.BooleanValue; /** Type additional information to describe the case to assist the service team in reaching a resolution. */ Description: DevKit.WebApi.StringValue; /** The primary email address for the entity. */ EmailAddress: DevKit.WebApi.StringValue; /** Choose the entitlement that is applicable for the case. */ EntitlementId: DevKit.WebApi.LookupValue; /** The default image for the entity. */ EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; EntityImageId: DevKit.WebApi.GuidValueReadonly; /** Indicates the date and time when the case was escalated. */ EscalatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Select an existing case for the customer that has been populated. For internal use only. */ ExistingCase: DevKit.WebApi.LookupValue; /** For internal use only. */ FirstResponseByKPIId: DevKit.WebApi.LookupValue; /** Indicates if the first response has been sent. */ FirstResponseSent: DevKit.WebApi.BooleanValue; /** Shows the status of the initial response time for the case according to the terms of the SLA. */ FirstResponseSLAStatus: DevKit.WebApi.OptionSetValue; /** Enter the date by which a customer service representative has to follow up with the customer on this case. */ FollowupBy_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** This attribute is used for Sample Service Business Processes. */ FollowUpTaskCreated: DevKit.WebApi.BooleanValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the case. */ IncidentId: DevKit.WebApi.GuidValue; /** Select the current stage of the service process for the case to assist service team members when they review or transfer a case. */ IncidentStageCode: DevKit.WebApi.OptionSetValue; /** Will contain the Influencer score coming from NetBreeze. */ InfluenceScore: DevKit.WebApi.DoubleValue; /** Shows customer satisfaction by tracking effort required by the customer. Low scores typically mean higher customer satisfaction as the customer had to travel through less channels to find a resolution */ int_CustomerEffort: DevKit.WebApi.OptionSetValue; /** Mark Yes if an opportunity exists to sell additional products or services to the customer. */ int_UpSellReferral: DevKit.WebApi.BooleanValue; /** For system use only. */ IsDecrementing: DevKit.WebApi.BooleanValue; /** Indicates if the case has been escalated. */ IsEscalated: DevKit.WebApi.BooleanValue; /** Choose the article that contains additional information or a resolution for the case, for reference during research or follow up with the customer. */ KbArticleId: DevKit.WebApi.LookupValue; /** Contains the date time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Choose the primary case the current case was merged into. */ MasterId: DevKit.WebApi.LookupValue; /** Tells whether the incident has been merged with another incident. */ Merged: DevKit.WebApi.BooleanValueReadonly; /** Shows whether the post originated as a public or private message. */ MessageTypeCode: DevKit.WebApi.OptionSetValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the external party who modified the record. */ ModifiedByExternalParty: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Case's functional location */ msdyn_FunctionalLocation: DevKit.WebApi.LookupValue; /** Unique identifier for Incident Type associated with Case. */ msdyn_IncidentType: DevKit.WebApi.LookupValue; /** The iot alert that initiated this case */ msdyn_iotalert: DevKit.WebApi.LookupValue; /** Number of child incidents associated with the incident. */ NumberOfChildIncidents: DevKit.WebApi.IntegerValueReadonly; /** Shows the duration in minutes for which the case was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Choose the parent case for a case. */ ParentCaseId: DevKit.WebApi.LookupValue; /** Select a primary contact for this case. */ PrimaryContactId: DevKit.WebApi.LookupValue; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Contains the id of the process associated with the entity. */ ProcessId: DevKit.WebApi.GuidValue; /** Choose the product associated with the case to identify warranty, service, or other product issues and be able to report the number of incidents for each product. */ ProductId: DevKit.WebApi.LookupValue; /** Type the serial number of the product that is associated with this case, so that the number of cases per product can be reported. */ ProductSerialNumber: DevKit.WebApi.StringValue; /** Enter the date by when the case must be resolved. */ ResolveBy_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** For internal use only. */ ResolveByKPIId: DevKit.WebApi.LookupValue; /** Shows the status of the resolution time for the case according to the terms of the SLA. */ ResolveBySLAStatus: DevKit.WebApi.OptionSetValue; /** For internal use only. */ ResponseBy_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Tells whether the incident has been routed to queue or not. */ RouteCase: DevKit.WebApi.BooleanValue; /** Value derived after assessing words commonly associated with a negative, neutral, or positive sentiment that occurs in a social post. Sentiment information can also be reported as numeric values. */ SentimentValue: DevKit.WebApi.DoubleValue; /** Select the stage, in the case resolution process, that the case is in. */ ServiceStage: DevKit.WebApi.OptionSetValue; /** Select the severity of this case to indicate the incident's impact on the customer's business. */ SeverityCode: DevKit.WebApi.OptionSetValue; /** Choose the service level agreement (SLA) that you want to apply to the case record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this case. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Unique identifier of the social profile with which the case is associated. */ SocialProfileId: DevKit.WebApi.LookupValue; /** Contains the id of the stage where the entity is located. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the case is active, resolved, or canceled. Resolved and canceled cases are read-only and can't be edited unless they are reactivated. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the case's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Choose the subject for the case, such as catalog request or product complaint, so customer service managers can identify frequent requests or problem areas. Administrators can configure subjects under Business Management in the Settings area. */ SubjectId: DevKit.WebApi.LookupValue; /** Shows the case number for customer reference and searching capabilities. This cannot be modified. */ TicketNumber: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Type a subject or descriptive name, such as the request, issue, or company name, to identify the case in Microsoft Dynamics 365 views. */ Title: DevKit.WebApi.StringValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Incident { enum CaseOriginCode { /** 2 */ Email, /** 2483 */ Facebook, /** 700610000 */ IoT, /** 1 */ Phone, /** 3986 */ Twitter, /** 3 */ Web } enum CaseTypeCode { /** 2 */ Problem, /** 1 */ Question, /** 3 */ Request } enum ContractServiceLevelCode { /** 3 */ Bronze, /** 1 */ Gold, /** 2 */ Silver } enum CustomerSatisfactionCode { /** 2 */ Dissatisfied, /** 3 */ Neutral, /** 4 */ Satisfied, /** 1 */ Very_Dissatisfied, /** 5 */ Very_Satisfied } enum FirstResponseSLAStatus { /** 1 */ In_Progress, /** 2 */ Nearing_Noncompliance, /** 4 */ Noncompliant, /** 3 */ Succeeded } enum IncidentStageCode { /** 1 */ Default_Value } enum int_CustomerEffort { /** 121590002 */ High, /** 121590000 */ Low, /** 121590001 */ Medium } enum MessageTypeCode { /** 1 */ Private_Message, /** 0 */ Public_Message } enum PriorityCode { /** 1 */ High, /** 3 */ Low, /** 2 */ Normal } enum ResolveBySLAStatus { /** 1 */ In_Progress, /** 2 */ Nearing_Noncompliance, /** 4 */ Noncompliant, /** 3 */ Succeeded } enum ServiceStage { /** 0 */ Identify, /** 1 */ Research, /** 2 */ Resolve } enum SeverityCode { /** 1 */ Default_Value } enum StateCode { /** 0 */ Active, /** 2 */ Cancelled, /** 1 */ Resolved } enum StatusCode { /** 6 */ Cancelled, /** 1 */ In_Progress, /** 1000 */ Information_Provided, /** 2000 */ Merged, /** 2 */ On_Hold, /** 5 */ Problem_Solved, /** 4 */ Researching, /** 3 */ Waiting_for_Details } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Case','Case for Interactive experience','Case for Multisession experience','Case Quick Create for Multisession','Information','TimelineWallControl - Case- Main','Quick Create','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { ThreeCameraService } from "./threeViewer/threeCameraService" import { IRootScopeService, IWindowService } from "angular" import { CodeMapBuilding } from "./rendering/codeMapBuilding" import $ from "jquery" import { ViewCubeEventPropagationSubscriber, ViewCubeMouseEventsService } from "../viewCube/viewCube.mouseEvents.service" import { BlacklistItem } from "../../codeCharta.model" import { ThreeSceneService } from "./threeViewer/threeSceneService" import { ThreeUpdateCycleService } from "./threeViewer/threeUpdateCycleService" import { ThreeRendererService } from "./threeViewer/threeRendererService" import { isPathHiddenOrExcluded } from "../../util/codeMapHelper" import { BlacklistService, BlacklistSubscriber } from "../../state/store/fileSettings/blacklist/blacklist.service" import { FilesService, FilesSelectionSubscriber } from "../../state/store/files/files.service" import { StoreService } from "../../state/store.service" import { hierarchy } from "d3-hierarchy" import { Object3D, Raycaster } from "three" import { CodeMapLabelService } from "./codeMap.label.service" import { LazyLoader } from "../../util/lazyLoader" import { CodeMapPreRenderService } from "./codeMap.preRender.service" import { ThreeViewerService } from "./threeViewer/threeViewerService" import { setHoveredBuildingPath } from "../../state/store/appStatus/hoveredBuildingPath/hoveredBuildingPath.actions" import { hoveredBuildingPathSelector } from "../../state/store/appStatus/hoveredBuildingPath/hoveredBuildingPath.selector" interface Coordinates { x: number y: number } export interface BuildingHoveredSubscriber { onBuildingHovered(hoveredBuilding: CodeMapBuilding) } export interface BuildingUnhoveredSubscriber { onBuildingUnhovered() } export interface BuildingRightClickedEventSubscriber { onBuildingRightClicked(building: CodeMapBuilding, x: number, y: number) } export enum ClickType { LeftClick = 0, RightClick = 2 } export enum CursorType { Default = "default", Grabbing = "grabbing", Pointer = "pointer", Moving = "move" } export class CodeMapMouseEventService implements ViewCubeEventPropagationSubscriber, FilesSelectionSubscriber, BlacklistSubscriber { private static readonly BUILDING_HOVERED_EVENT = "building-hovered" private static readonly BUILDING_UNHOVERED_EVENT = "building-unhovered" private static readonly BUILDING_RIGHT_CLICKED_EVENT = "building-right-clicked" private readonly THRESHOLD_FOR_MOUSE_MOVEMENT_TRACKING = 3 private highlightedInTreeView: CodeMapBuilding private intersectedBuilding: CodeMapBuilding private mouse: Coordinates = { x: 0, y: 0 } private oldMouse: Coordinates = { x: 0, y: 0 } private mouseOnLastClick: Coordinates = { x: 0, y: 0 } private isGrabbing = false private isMoving = false private raycaster = new Raycaster() private temporaryLabelForBuilding = null private hoveredBuildingPath: string | null = null constructor( private $rootScope: IRootScopeService, private $window: IWindowService, private threeCameraService: ThreeCameraService, private threeRendererService: ThreeRendererService, private threeSceneService: ThreeSceneService, private threeUpdateCycleService: ThreeUpdateCycleService, private storeService: StoreService, private codeMapLabelService: CodeMapLabelService, private codeMapPreRenderService: CodeMapPreRenderService, private viewCubeMouseEventsService: ViewCubeMouseEventsService, private threeViewerService: ThreeViewerService ) { "ngInject" this.threeUpdateCycleService.register(() => this.threeRendererService.render()) FilesService.subscribe(this.$rootScope, this) BlacklistService.subscribe(this.$rootScope, this) this.storeService["store"].subscribe(() => { const state = this.storeService["store"].getState() const hoveredBuildingPath = hoveredBuildingPathSelector(state) if (this.hoveredBuildingPath === hoveredBuildingPath) return this.hoveredBuildingPath = hoveredBuildingPath if (this.hoveredBuildingPath) { this.hoverNode(this.hoveredBuildingPath) } else { this.unhoverNode() } }) } static changeCursorIndicator(cursorIcon: CursorType) { document.body.style.cursor = cursorIcon } static subscribeToBuildingHovered($rootScope: IRootScopeService, subscriber: BuildingHoveredSubscriber) { $rootScope.$on(this.BUILDING_HOVERED_EVENT, (_event, data) => { subscriber.onBuildingHovered(data.hoveredBuilding) }) } static subscribeToBuildingUnhovered($rootScope: IRootScopeService, subscriber: BuildingUnhoveredSubscriber) { $rootScope.$on(this.BUILDING_UNHOVERED_EVENT, () => { subscriber.onBuildingUnhovered() }) } static subscribeToBuildingRightClickedEvents($rootScope: IRootScopeService, subscriber: BuildingRightClickedEventSubscriber) { $rootScope.$on(this.BUILDING_RIGHT_CLICKED_EVENT, (_event, data) => { subscriber.onBuildingRightClicked(data.building, data.x, data.y) }) } start() { // TODO: Check if these event listeners should ever be removed again. this.threeRendererService.renderer.domElement.addEventListener("mousemove", event => this.onDocumentMouseMove(event)) this.threeRendererService.renderer.domElement.addEventListener("mouseup", event => this.onDocumentMouseUp(event)) this.threeRendererService.renderer.domElement.addEventListener("mousedown", event => this.onDocumentMouseDown(event)) this.threeRendererService.renderer.domElement.addEventListener("dblclick", () => this.onDocumentDoubleClick()) this.threeRendererService.renderer.domElement.addEventListener("mouseleave", event => this.onDocumentMouseLeave(event)) this.threeRendererService.renderer.domElement.addEventListener("mouseenter", () => this.onDocumentMouseEnter()) ViewCubeMouseEventsService.subscribeToEventPropagation(this.$rootScope, this) } hoverNode(path: string) { const { buildings } = this.threeSceneService.getMapMesh().getMeshDescription() for (const building of buildings) { if (building.node.path === path) { this.hoverBuilding(building) this.highlightedInTreeView = building } } this.threeUpdateCycleService.update() } unhoverNode() { this.unhoverBuilding() this.highlightedInTreeView = null this.threeUpdateCycleService.update() } onViewCubeEventPropagation(eventType: string, event: MouseEvent) { switch (eventType) { case "mousemove": this.onDocumentMouseMove(event) break case "mouseup": this.onDocumentMouseUp(event) break case "mousedown": this.onDocumentMouseDown(event) break case "dblclick": this.onDocumentDoubleClick() break } } onFilesSelectionChanged() { this.threeSceneService.clearSelection() this.threeSceneService.clearConstantHighlight() this.clearTemporaryLabel() this.threeUpdateCycleService.update() } onBlacklistChanged(blacklist: BlacklistItem[]) { const selectedBuilding = this.threeSceneService.getSelectedBuilding() this.clearTemporaryLabel() if (selectedBuilding) { const isSelectedBuildingBlacklisted = isPathHiddenOrExcluded(selectedBuilding.node.path, blacklist) if (isSelectedBuildingBlacklisted) { this.threeSceneService.clearSelection() } } this.unhoverBuilding() } private clearTemporaryLabel() { if (this.temporaryLabelForBuilding !== null) { this.codeMapLabelService.clearTemporaryLabel(this.temporaryLabelForBuilding) this.temporaryLabelForBuilding = null } } updateHovering() { if (this.hasMouseMoved(this.oldMouse)) { const labels = this.threeSceneService.labels?.children if (this.isGrabbing || this.isMoving) { this.threeSceneService.resetLabel() this.clearTemporaryLabel() this.threeUpdateCycleService.update() return } this.oldMouse.x = this.mouse.x this.oldMouse.y = this.mouse.y const mouseCoordinates = this.transformHTMLToSceneCoordinates() const camera = this.threeCameraService.camera const mapMesh = this.threeSceneService.getMapMesh() let nodeNameHoveredLabel = "" this.threeCameraService.camera.updateMatrixWorld(false) if (mapMesh) { if (camera.isPerspectiveCamera) { this.raycaster.setFromCamera(mouseCoordinates, camera) } const hoveredLabel = this.calculateHoveredLabel(labels) if (hoveredLabel) { this.threeSceneService.animateLabel(hoveredLabel.object, this.raycaster, labels) nodeNameHoveredLabel = hoveredLabel.object.userData.node.path } this.intersectedBuilding = nodeNameHoveredLabel !== "" ? mapMesh.getBuildingByPath(nodeNameHoveredLabel) : mapMesh.checkMouseRayMeshIntersection(mouseCoordinates, camera) const from = this.threeSceneService.getHighlightedBuilding() const to = this.intersectedBuilding ?? this.highlightedInTreeView if (from !== to) { if (this.temporaryLabelForBuilding !== null) { this.codeMapLabelService.clearTemporaryLabel(this.temporaryLabelForBuilding) this.temporaryLabelForBuilding = null } this.threeSceneService.resetLabel() this.unhoverBuilding() if (to) { if (to.node.isLeaf) { const labelForBuilding = this.threeSceneService.getLabelForHoveredNode(to, labels) ?? this.drawTemporaryLabelFor(to, labels) this.threeSceneService.animateLabel(labelForBuilding, this.raycaster, labels) } this.hoverBuilding(to) } } } } this.threeUpdateCycleService.update() } private drawTemporaryLabelFor(codeMapBuilding: CodeMapBuilding, labels: Object3D[]) { const appSettings = this.storeService.getState().appSettings const showLabelNodeName = appSettings.showMetricLabelNodeName const showLabelNodeMetric = appSettings.showMetricLabelNameValue let displayLabelMetricName = true if (showLabelNodeMetric && !showLabelNodeName) { displayLabelMetricName = false } this.codeMapLabelService.addLabel( codeMapBuilding.node, { showNodeName: displayLabelMetricName, showNodeMetric: showLabelNodeMetric }, 0 ) labels = this.threeSceneService.labels?.children const labelForBuilding = this.threeSceneService.getLabelForHoveredNode(codeMapBuilding, labels) this.temporaryLabelForBuilding = codeMapBuilding.node return labelForBuilding } private EnableOrbitalsRotation(isRotation: boolean) { this.threeViewerService.enableRotation(isRotation) this.viewCubeMouseEventsService.enableRotation(isRotation) } onDocumentMouseEnter() { this.EnableOrbitalsRotation(true) } onDocumentMouseLeave(event: MouseEvent) { if (!(event.relatedTarget instanceof HTMLCanvasElement)) this.EnableOrbitalsRotation(false) } onDocumentMouseMove(event: MouseEvent) { this.mouse.x = event.clientX this.mouse.y = event.clientY this.updateHovering() this.viewCubeMouseEventsService.propagateMovement() } onDocumentDoubleClick() { const highlightedBuilding = this.threeSceneService.getHighlightedBuilding() const selectedBuilding = this.threeSceneService.getSelectedBuilding() // check if mouse moved to prevent opening the building link after rotating the map, when the cursor ends on a building if (highlightedBuilding && !this.hasMouseMoved(this.mouseOnLastClick)) { const fileSourceLink = highlightedBuilding.node.link if (fileSourceLink) { this.$window.open(fileSourceLink, "_blank") } } if (selectedBuilding?.node.isLeaf) { const sourceLink = selectedBuilding.node.link if (sourceLink) { this.$window.open(sourceLink, "_blank") return } const fileName = this.codeMapPreRenderService.getRenderFileMeta().fileName if (fileName) { LazyLoader.openFile(fileName, selectedBuilding.node.path) } } } onDocumentMouseDown(event: MouseEvent) { if (event.button === ClickType.RightClick) { this.isMoving = true CodeMapMouseEventService.changeCursorIndicator(CursorType.Moving) } if (event.button === ClickType.LeftClick) { this.isGrabbing = true CodeMapMouseEventService.changeCursorIndicator(CursorType.Grabbing) } this.mouseOnLastClick = { x: event.clientX, y: event.clientY } this.unhoverBuilding() $(document.activeElement).blur() } onDocumentMouseUp(event: MouseEvent) { this.viewCubeMouseEventsService.resetIsDragging() if (event.button === ClickType.LeftClick) { this.onLeftClick() } else { this.onRightClick() } if (this.intersectedBuilding !== undefined) { CodeMapMouseEventService.changeCursorIndicator(CursorType.Pointer) } else { CodeMapMouseEventService.changeCursorIndicator(CursorType.Default) } } private calculateHoveredLabel(labels: Object3D[]) { let labelClosestToViewPoint = null if (labels) { for (let counter = 0; counter < labels.length; counter += 2) { const intersect = this.raycaster.intersectObject(this.threeSceneService.labels.children[counter]) if (intersect.length > 0) { if (labelClosestToViewPoint === null) { labelClosestToViewPoint = intersect[0] } else { labelClosestToViewPoint = labelClosestToViewPoint.distance < intersect[0].distance ? labelClosestToViewPoint : intersect[0] } } } return labelClosestToViewPoint } } private onRightClick() { this.isMoving = false const building = this.intersectedBuilding // check if mouse moved to prevent the node context menu to show up after moving the map, when the cursor ends on a building if (building && !this.hasMouseMovedMoreThanThreePixels(this.mouseOnLastClick)) { this.$rootScope.$broadcast(CodeMapMouseEventService.BUILDING_RIGHT_CLICKED_EVENT, { building, x: this.mouse.x, y: this.mouse.y }) this.hoverBuilding(building) } this.threeUpdateCycleService.update() } private onLeftClick() { this.isGrabbing = false if (!this.hasMouseMovedMoreThanThreePixels(this.mouseOnLastClick)) { this.threeSceneService.clearSelection() this.threeSceneService.clearConstantHighlight() if (this.intersectedBuilding) { this.threeSceneService.selectBuilding(this.intersectedBuilding) } } this.threeUpdateCycleService.update() } private hasMouseMovedMoreThanThreePixels({ x, y }: Coordinates) { return ( Math.abs(this.mouse.x - x) > this.THRESHOLD_FOR_MOUSE_MOVEMENT_TRACKING || Math.abs(this.mouse.y - y) > this.THRESHOLD_FOR_MOUSE_MOVEMENT_TRACKING ) } private hasMouseMoved({ x, y }: Coordinates) { return this.mouse.x !== x || this.mouse.y !== y } private hoverBuilding(hoveredBuilding: CodeMapBuilding) { if (hoveredBuilding) { this.hoverBuildingAndChildren(hoveredBuilding) } } private transformHTMLToSceneCoordinates(): Coordinates { const { renderer, renderer: { domElement } } = this.threeRendererService const pixelRatio = renderer.getPixelRatio() const rect = domElement.getBoundingClientRect() const x = (this.mouse.x / domElement.width) * pixelRatio * 2 - 1 const y = -(((this.mouse.y - rect.top) / domElement.height) * pixelRatio) * 2 + 1 return { x, y } } private hoverBuildingAndChildren(hoveredBuilding: CodeMapBuilding) { if (!this.isGrabbing && !this.isMoving) { CodeMapMouseEventService.changeCursorIndicator(CursorType.Pointer) const { lookUp } = this.storeService.getState() const codeMapNode = lookUp.idToNode.get(hoveredBuilding.node.id) for (const { data } of hierarchy(codeMapNode)) { const building = lookUp.idToBuilding.get(data.id) if (building) { this.threeSceneService.addBuildingToHighlightingList(building) } } this.threeSceneService.highlightBuildings() this.$rootScope.$broadcast(CodeMapMouseEventService.BUILDING_HOVERED_EVENT, { hoveredBuilding }) if (this.hoveredBuildingPath !== hoveredBuilding.node.path) { this.hoveredBuildingPath = hoveredBuilding.node.path this.storeService.dispatch(setHoveredBuildingPath(hoveredBuilding.node.path)) } } } private unhoverBuilding() { if (!this.isMoving && !this.isGrabbing) { CodeMapMouseEventService.changeCursorIndicator(CursorType.Default) } if (this.threeSceneService.getConstantHighlight().size > 0) { this.threeSceneService.clearHoverHighlight() } else { this.threeSceneService.clearHighlight() } this.$rootScope.$broadcast(CodeMapMouseEventService.BUILDING_UNHOVERED_EVENT) this.hoveredBuildingPath = null this.storeService.dispatch(setHoveredBuildingPath(null)) } }
the_stack
export interface Derivative { // function computing the value of Y' = F(x,Y) (x: number, // input x value y: number[]) // input y value) : number[] // output y' values (Array of length n) } export interface OutputFunction { // value callback (nr: number, // step number xold: number, // left edge of solution interval x: number, // right edge of solution interval (y = F(x)) y: number[], // F(x) dense?: (c: number, x: number) => number) // dense interpolator. Valid in the range [x, xold). : boolean|void // return false to halt integration } export enum Outcome { Converged, MaxStepsExceeded, EarlyReturn } export class Solver { n: number // dimension of the system uRound: number // WORK(1), machine epsilon. (WORK, IWORK are references to odex.f) maxSteps: number // IWORK(1), positive integer initialStepSize: number // H maxStepSize: number // WORK(2), maximal step size, default xEnd - x maxExtrapolationColumns: number // IWORK(2), KM, positive integer stepSizeSequence: number // IWORK(3), in [1..5] stabilityCheckCount: number // IWORK(4), in stabilityCheckTableLines: number // IWORK(5), positive integer denseOutput: boolean // IOUT >= 2, true means dense output interpolator provided to solOut denseOutputErrorEstimator: boolean // IWORK(6), reversed sense from the FORTRAN code denseComponents: number[] // IWORK(8) & IWORK(21,...), components for which dense output is required interpolationFormulaDegree: number // IWORK(7), µ = 2 * k - interpolationFormulaDegree + 1 [1..6], default 4 stepSizeReductionFactor: number // WORK(3), default 0.5 stepSizeFac1: number // WORK(4) stepSizeFac2: number // WORK(5) stepSizeFac3: number // WORK(6) stepSizeFac4: number // WORK(7) stepSafetyFactor1: number // WORK(8) stepSafetyFactor2: number // WORK(9) relativeTolerance: number|number[] // RTOL. Can be a scalar or vector of length N. absoluteTolerance: number|number[] // ATOL. Can be a scalar or vector of length N. debug: boolean constructor(n: number) { this.n = n this.uRound = 2.3e-16 this.maxSteps = 10000 this.initialStepSize = 1e-4 this.maxStepSize = 0 this.maxExtrapolationColumns = 9 this.stepSizeSequence = 0 this.stabilityCheckCount = 1 this.stabilityCheckTableLines = 2 this.denseOutput = false this.denseOutputErrorEstimator = true this.denseComponents = undefined this.interpolationFormulaDegree = 4 this.stepSizeReductionFactor = 0.5 this.stepSizeFac1 = 0.02 this.stepSizeFac2 = 4.0 this.stepSizeFac3 = 0.8 this.stepSizeFac4 = 0.9 this.stepSafetyFactor1 = 0.65 this.stepSafetyFactor2 = 0.94 this.relativeTolerance = 1e-5 this.absoluteTolerance = 1e-5 this.debug = false } grid(dt: number, out: (xOut: number, yOut: number[]) => any): OutputFunction { if (!this.denseOutput) throw new Error('Must set .denseOutput to true when using grid') let components: number[] = this.denseComponents if (!components) { components = [] for (let i = 0; i < this.n; ++i) components.push(i) } let t: number return (n: number, xOld: number, x: number, y: number[], interpolate: (i: number, x: number) => number) => { if (n === 1) { let v = out(x, y) t = x + dt return v } while (t <= x) { let yf: number[] = [] for (let i of components) { yf.push(interpolate(i, t)) } let v = out(t, yf) if (v === false) return false t += dt } } } // return a 1-based array of length n. Initial values undefined. private static dim = (n: number) => Array(n + 1) private static log10 = (x: number) => Math.log(x) / Math.LN10 // Make a 1-based 2D array, with r rows and c columns. The initial values are undefined. private static dim2(r: number, c: number): number[][] { let a = new Array(r + 1) for (let i = 1; i <= r; ++i) a[i] = Solver.dim(c) return a } // Generate step size sequence and return as a 1-based array of length n. static stepSizeSequence(nSeq: number, n: number): number[] { const a = new Array(n + 1) a[0] = 0 switch (nSeq) { case 1: for (let i = 1; i <= n; ++i) a[i] = 2 * i break case 2: a[1] = 2 for (let i = 2; i <= n; ++i) a[i] = 4 * i - 4 break case 3: a[1] = 2 a[2] = 4 a[3] = 6 for (let i = 4; i <= n; ++i) a[i] = 2 * a[i - 2] break case 4: for (let i = 1; i <= n; ++i) a[i] = 4 * i - 2 break case 5: for (let i = 1; i <= n; ++i) a[i] = 4 * i break default: throw new Error('invalid stepSizeSequence selected') } return a } // Integrate the differential system represented by f, from x to xEnd, with initial data y. // solOut, if provided, is called at each integration step. solve(f: Derivative, x: number, y0: number[], xEnd: number, solOut?: OutputFunction) { // Make a copy of y0, 1-based. We leave the user's parameters alone so that they may be reused if desired. let y = [0].concat(y0) let dz = Solver.dim(this.n) let yh1 = Solver.dim(this.n) let yh2 = Solver.dim(this.n) if (this.maxSteps <= 0) throw new Error('maxSteps must be positive') const km = this.maxExtrapolationColumns if (km <= 2) throw new Error('maxExtrapolationColumns must be > 2') const nSeq = this.stepSizeSequence || (this.denseOutput ? 4 : 1) if (nSeq <= 3 && this.denseOutput) throw new Error('stepSizeSequence incompatible with denseOutput') if (this.denseOutput && !solOut) throw new Error('denseOutput requires a solution observer function') if (this.interpolationFormulaDegree <= 0 || this.interpolationFormulaDegree >= 7) throw new Error('bad interpolationFormulaDegree') let icom = [0] // icom will be 1-based, so start with a pad entry. let nrdens = 0 if (this.denseOutput) { if (this.denseComponents) { for (let c of this.denseComponents) { // convert dense components requested into one-based indexing. if (c < 0 || c > this.n) throw new Error('bad dense component: ' + c) icom.push(c + 1) ++nrdens } } else { // if user asked for dense output but did not specify any denseComponents, // request all of them. for (let i = 1; i <= this.n; ++i) { icom.push(i) } nrdens = this.n } } if (this.uRound <= 1e-35 || this.uRound > 1) throw new Error('suspicious value of uRound') const hMax = Math.abs(this.maxStepSize || xEnd - x) const lfSafe = 2 * km * km + km function expandToArray(x: number|number[], n: number): number[] { // If x is an array, return a 1-based copy of it. If x is a number, return a new 1-based array // consisting of n copies of the number. const tolArray = [0] if (Array.isArray(x)) { return tolArray.concat(x) } else { for (let i = 0; i < n; ++i) tolArray.push(x) return tolArray } } const aTol = expandToArray(this.absoluteTolerance, this.n) const rTol = expandToArray(this.relativeTolerance, this.n) let [nEval, nStep, nAccept, nReject] = [0, 0, 0, 0] // call to core integrator const nrd = Math.max(1, nrdens) const ncom = Math.max(1, (2 * km + 5) * nrdens) const dens = Solver.dim(ncom) const fSafe = Solver.dim2(lfSafe, nrd) // Wrap f in a function F which hides the one-based indexing from the customers. const F = (x: number, y: number[], yp: number[]) => { let ret = f(x, y.slice(1)) for (let i = 0; i < ret.length; ++i) yp[i + 1] = ret[i] } let odxcor = (): Outcome => { // The following three variables are COMMON/CONTEX/ let xOldd: number let hhh: number let kmit: number let acceptStep = (n: number): boolean => { // label 60 // Returns true if we should continue the integration. The only time false // is returned is when the user's solution observation function has returned false, // indicating that she does not wish to continue the computation. xOld = x x += h if (this.denseOutput) { // kmit = mu of the paper kmit = 2 * kc - this.interpolationFormulaDegree + 1 for (let i = 1; i <= nrd; ++i) dens[i] = y[icom[i]] xOldd = xOld hhh = h // note: xOldd and hhh are part of /CONODX/ for (let i = 1; i <= nrd; ++i) dens[nrd + i] = h * dz[icom[i]] let kln = 2 * nrd for (let i = 1; i <= nrd; ++i) dens[kln + i] = t[1][icom[i]] // compute solution at mid-point for (let j = 2; j <= kc; ++j) { let dblenj = nj[j] for (let l = j; l >= 2; --l) { let factor = (dblenj / nj[l - 1]) ** 2 - 1 for (let i = 1; i <= nrd; ++i) { ySafe[l - 1][i] = ySafe[l][i] + (ySafe[l][i] - ySafe[l - 1][i]) / factor } } } let krn = 4 * nrd for (let i = 1; i <= nrd; ++i) dens[krn + i] = ySafe[1][i] // compute first derivative at right end for (let i = 1; i <= n; ++i) yh1[i] = t[1][i] F(x, yh1, yh2) krn = 3 * nrd for (let i = 1; i <= nrd; ++i) dens[krn + i] = yh2[icom[i]] * h // THE LOOP for (let kmi = 1; kmi <= kmit; ++kmi) { // compute kmi-th derivative at mid-point let kbeg = (kmi + 1) / 2 | 0 for (let kk = kbeg; kk <= kc; ++kk) { let facnj = (nj[kk] / 2) ** (kmi - 1) iPt = iPoint[kk + 1] - 2 * kk + kmi for (let i = 1; i <= nrd; ++i) { ySafe[kk][i] = fSafe[iPt][i] * facnj } } for (let j = kbeg + 1; j <= kc; ++j) { let dblenj = nj[j] for (let l = j; l >= kbeg + 1; --l) { let factor = (dblenj / nj[l - 1]) ** 2 - 1 for (let i = 1; i <= nrd; ++i) { ySafe[l - 1][i] = ySafe[l][i] + (ySafe[l][i] - ySafe[l - 1][i]) / factor } } } krn = (kmi + 4) * nrd for (let i = 1; i <= nrd; ++i) dens[krn + i] = ySafe[kbeg][i] * h if (kmi === kmit) continue // compute differences for (let kk = (kmi + 2) / 2 | 0; kk <= kc; ++kk) { let lbeg = iPoint[kk + 1] let lend = iPoint[kk] + kmi + 1 if (kmi === 1 && nSeq === 4) lend += 2 let l: number for (l = lbeg; l >= lend; l -= 2) { for (let i = 1; i <= nrd; ++i) { fSafe[l][i] -= fSafe[l - 2][i] } } if (kmi === 1 && nSeq === 4) { l = lend - 2 for (let i = 1; i <= nrd; ++i) fSafe[l][i] -= dz[icom[i]] } } // compute differences for (let kk = (kmi + 2) / 2 | 0; kk <= kc; ++kk) { let lbeg = iPoint[kk + 1] - 1 let lend = iPoint[kk] + kmi + 2 for (let l = lbeg; l >= lend; l -= 2) { for (let i = 1; i <= nrd; ++i) { fSafe[l][i] -= fSafe[l - 2][i] } } } } interp(nrd, dens, kmit) // estimation of interpolation error if (this.denseOutputErrorEstimator && kmit >= 1) { let errint = 0 for (let i = 1; i <= nrd; ++i) errint += (dens[(kmit + 4) * nrd + i] / scal[icom[i]]) ** 2 errint = Math.sqrt(errint / nrd) * errfac[kmit] hoptde = h / Math.max(errint ** (1 / (kmit + 4)), 0.01) if (errint > 10) { h = hoptde x = xOld ++nReject reject = true return true } } for (let i = 1; i <= n; ++i) dz[i] = yh2[i] } for (let i = 1; i <= n; ++i) y[i] = t[1][i] ++nAccept if (solOut) { // If denseOutput, we also want to supply the dense closure. if (solOut(nAccept + 1, xOld, x, y.slice(1), this.denseOutput && contex(xOldd, hhh, kmit, dens, icom)) === false) return false } // compute optimal order let kopt: number if (kc === 2) { kopt = Math.min(3, km - 1) if (reject) kopt = 2 } else { if (kc <= k) { kopt = kc if (w[kc - 1] < w[kc] * this.stepSizeFac3) kopt = kc - 1 if (w[kc] < w[kc - 1] * this.stepSizeFac4) kopt = Math.min(kc + 1, km - 1) } else { kopt = kc - 1 if (kc > 3 && w[kc - 2] < w[kc - 1] * this.stepSizeFac3) kopt = kc - 2 if (w[kc] < w[kopt] * this.stepSizeFac4) kopt = Math.min(kc, km - 1) } } // after a rejected step if (reject) { k = Math.min(kopt, kc) h = posneg * Math.min(Math.abs(h), Math.abs(hh[k])) reject = false return true // goto 10 } if (kopt <= kc) { h = hh[kopt] } else { if (kc < k && w[kc] < w[kc - 1] * this.stepSizeFac4) { h = hh[kc] * a[kopt + 1] / a[kc] } else { h = hh[kc] * a[kopt] / a[kc] } } // compute stepsize for next step k = kopt h = posneg * Math.abs(h) return true } let midex = (j: number): void => { const dy = Solver.dim(this.n) // Computes the jth line of the extrapolation table and // provides an estimation of the optional stepsize const hj = h / nj[j] // Euler starting step for (let i = 1; i <= this.n; ++i) { yh1[i] = y[i] yh2[i] = y[i] + hj * dz[i] } // Explicit midpoint rule const m = nj[j] - 1 const njMid = (nj[j] / 2) | 0 for (let mm = 1; mm <= m; ++mm) { if (this.denseOutput && mm === njMid) { for (let i = 1; i <= nrd; ++i) { ySafe[j][i] = yh2[icom[i]] } } F(x + hj * mm, yh2, dy) if (this.denseOutput && Math.abs(mm - njMid) <= 2 * j - 1) { ++iPt for (let i = 1; i <= nrd; ++i) { fSafe[iPt][i] = dy[icom[i]] } } for (let i = 1; i <= this.n; ++i) { let ys = yh1[i] yh1[i] = yh2[i] yh2[i] = ys + 2 * hj * dy[i] } if (mm <= this.stabilityCheckCount && j <= this.stabilityCheckTableLines) { // stability check let del1 = 0 for (let i = 1; i <= this.n; ++i) { del1 += (dz[i] / scal[i]) ** 2 } let del2 = 0 for (let i = 1; i <= this.n; ++i) { del2 += ((dy[i] - dz[i]) / scal[i]) ** 2 } const quot = del2 / Math.max(this.uRound, del1) if (quot > 4) { ++nEval atov = true h *= this.stepSizeReductionFactor reject = true return } } } // final smoothing step F(x + h, yh2, dy) if (this.denseOutput && njMid <= 2 * j - 1) { ++iPt for (let i = 1; i <= nrd; ++i) { fSafe[iPt][i] = dy[icom[i]] } } for (let i = 1; i <= this.n; ++i) { t[j][i] = (yh1[i] + yh2[i] + hj * dy[i]) / 2 } nEval += nj[j] // polynomial extrapolation if (j === 1) return // was j.eq.1 const dblenj = nj[j] let fac: number for (let l = j; l > 1; --l) { fac = (dblenj / nj[l - 1]) ** 2 - 1 for (let i = 1; i <= this.n; ++i) { t[l - 1][i] = t[l][i] + (t[l][i] - t[l - 1][i]) / fac } } err = 0 // scaling for (let i = 1; i <= this.n; ++i) { let t1i = Math.max(Math.abs(y[i]), Math.abs(t[1][i])) scal[i] = aTol[i] + rTol[i] * t1i err += ((t[1][i] - t[2][i]) / scal[i]) ** 2 } err = Math.sqrt(err / this.n) if (err * this.uRound >= 1 || (j > 2 && err >= errOld)) { atov = true h *= this.stepSizeReductionFactor reject = true return } errOld = Math.max(4 * err, 1) // compute optimal stepsizes let exp0 = 1 / (2 * j - 1) let facMin = this.stepSizeFac1 ** exp0 fac = Math.min(this.stepSizeFac2 / facMin, Math.max(facMin, (err / this.stepSafetyFactor1) ** exp0 / this.stepSafetyFactor2)) fac = 1 / fac hh[j] = Math.min(Math.abs(h) * fac, hMax) w[j] = a[j] / hh[j] } const interp = (n: number, y: number[], imit: number) => { // computes the coefficients of the interpolation formula let a = new Array(31) // zero-based: 0:30 // begin with Hermite interpolation for (let i = 1; i <= n; ++i) { let y0 = y[i] let y1 = y[2 * n + i] let yp0 = y[n + i] let yp1 = y[3 * n + i] let yDiff = y1 - y0 let aspl = -yp1 + yDiff let bspl = yp0 - yDiff y[n + i] = yDiff y[2 * n + i] = aspl y[3 * n + i] = bspl if (imit < 0) continue // compute the derivatives of Hermite at midpoint let ph0 = (y0 + y1) * 0.5 + 0.125 * (aspl + bspl) let ph1 = yDiff + (aspl - bspl) * 0.25 let ph2 = -(yp0 - yp1) let ph3 = 6 * (bspl - aspl) // compute the further coefficients if (imit >= 1) { a[1] = 16 * (y[5 * n + i] - ph1) if (imit >= 3) { a[3] = 16 * (y[7 * n + i] - ph3 + 3 * a[1]) if (imit >= 5) { for (let im = 5; im <= imit; im += 2) { let fac1 = im * (im - 1) / 2 let fac2 = fac1 * (im - 2) * (im - 3) * 2 a[im] = 16 * (y[(im + 4) * n + i] + fac1 * a[im - 2] - fac2 * a[im - 4]) } } } } a[0] = (y[4 * n + i] - ph0) * 16 if (imit >= 2) { a[2] = (y[n * 6 + i] - ph2 + a[0]) * 16 if (imit >= 4) { for (let im = 4; im <= imit; im += 2) { let fac1 = im * (im - 1) / 2 let fac2 = im * (im - 1) * (im - 2) * (im - 3) a[im] = (y[n * (im + 4) + i] + a[im - 2] * fac1 - a[im - 4] * fac2) * 16 } } } for (let im = 0; im <= imit; ++im) y[n * (im + 4) + i] = a[im] } } const contex = (xOld: number, h: number, imit: number, y: number[], icom: number[]) => { return (c: number, x: number) => { let i = 0 for (let j = 1; j <= nrd; ++j) { // careful: customers describe components 0-based. We record indices 1-based. if (icom[j] === c + 1) i = j } if (i === 0) throw new Error('no dense output available for component ' + c) const theta = (x - xOld) / h const theta1 = 1 - theta const phthet = y[i] + theta * (y[nrd + i] + theta1 * (y[2 * nrd + i] * theta + y[3 * nrd + i] * theta1)) if (imit < 0) return phthet const thetah = theta - 0.5 let ret = y[nrd * (imit + 4) + i] for (let im = imit; im >= 1; --im) { ret = y[nrd * (im + 3) + i] + ret * thetah / im } return phthet + (theta * theta1) ** 2 * ret } } // preparation const ySafe = Solver.dim2(km, nrd) const hh = Solver.dim(km) const t = Solver.dim2(km, this.n) // Define the step size sequence const nj = Solver.stepSizeSequence(nSeq, km) // Define the a[i] for order selection const a = Solver.dim(km) a[1] = 1 + nj[1] for (let i = 2; i <= km; ++i) { a[i] = a[i - 1] + nj[i] } // Initial Scaling const scal = Solver.dim(this.n) for (let i = 1; i <= this.n; ++i) { scal[i] = aTol[i] + rTol[i] + Math.abs(y[i]) } // Initial preparations const posneg = xEnd - x >= 0 ? 1 : -1 let k = Math.max(2, Math.min(km - 1, Math.floor(-Solver.log10(rTol[1] + 1e-40) * 0.6 + 1.5))) let h = Math.max(Math.abs(this.initialStepSize), 1e-4) h = posneg * Math.min(h, hMax, Math.abs(xEnd - x) / 2) const iPoint = Solver.dim(km + 1) const errfac = Solver.dim(2 * km) let xOld = x let iPt = 0 if (solOut) { if (this.denseOutput) { iPoint[1] = 0 for (let i = 1; i <= km; ++i) { let njAdd = 4 * i - 2 if (nj[i] > njAdd) ++njAdd iPoint[i + 1] = iPoint[i] + njAdd } for (let mu = 1; mu <= 2 * km; ++mu) { let errx = Math.sqrt(mu / (mu + 4)) * 0.5 let prod = (1 / (mu + 4)) ** 2 for (let j = 1; j <= mu; ++j) prod *= errx / j errfac[mu] = prod } iPt = 0 } // check return value and abandon integration if called for if (false === solOut(nAccept + 1, xOld, x, y.slice(1))) { return Outcome.EarlyReturn } } let err = 0 let errOld = 1e10 let hoptde = posneg * hMax const w = Solver.dim(km) w[1] = 0 let reject = false let last = false let atov: boolean let kc = 0 enum STATE { Start, BasicIntegrationStep, ConvergenceStep, HopeForConvergence, Accept, Reject } let state: STATE = STATE.Start loop: while (true) { this.debug && console.log('STATE', STATE[state], nStep, xOld, x, h, k, kc, hoptde) switch (state) { case STATE.Start: atov = false // Is xEnd reached in the next step? if (0.1 * Math.abs(xEnd - x) <= Math.abs(x) * this.uRound) break loop h = posneg * Math.min(Math.abs(h), Math.abs(xEnd - x), hMax, Math.abs(hoptde)) if ((x + 1.01 * h - xEnd) * posneg > 0) { h = xEnd - x last = true } if (nStep === 0 || !this.denseOutput) { F(x, y, dz) ++nEval } // The first and last step if (nStep === 0 || last) { iPt = 0 ++nStep for (let j = 1; j <= k; ++j) { kc = j midex(j) if (atov) continue loop if (j > 1 && err <= 1) { state = STATE.Accept continue loop } } state = STATE.HopeForConvergence continue } state = STATE.BasicIntegrationStep continue case STATE.BasicIntegrationStep: // basic integration step iPt = 0 ++nStep if (nStep >= this.maxSteps) { return Outcome.MaxStepsExceeded } kc = k - 1 for (let j = 1; j <= kc; ++j) { midex(j) if (atov) { state = STATE.Start continue loop } } // convergence monitor if (k === 2 || reject) { state = STATE.ConvergenceStep } else { if (err <= 1) { state = STATE.Accept } else if (err > ((nj[k + 1] * nj[k]) / 4) ** 2) { state = STATE.Reject } else state = STATE.ConvergenceStep } continue case STATE.ConvergenceStep: // label 50 midex(k) if (atov) { state = STATE.Start continue } kc = k if (err <= 1) { state = STATE.Accept continue } state = STATE.HopeForConvergence continue case STATE.HopeForConvergence: // hope for convergence in line k + 1 if (err > (nj[k + 1] / 2) ** 2) { state = STATE.Reject continue } kc = k + 1 midex(kc) if (atov) state = STATE.Start else if (err > 1) state = STATE.Reject else state = STATE.Accept continue case STATE.Accept: if (!acceptStep(this.n)) return Outcome.EarlyReturn state = STATE.Start continue case STATE.Reject: k = Math.min(k, kc, km - 1) if (k > 2 && w[k - 1] < w[k] * this.stepSizeFac3) k -= 1 ++nReject h = posneg * hh[k] reject = true state = STATE.BasicIntegrationStep } } return Outcome.Converged } const outcome = odxcor() return { y: y.slice(1), outcome: outcome, nStep: nStep, xEnd: xEnd, nAccept: nAccept, nReject: nReject, nEval: nEval } } }
the_stack
import mysql, { Connection, ConnectionConfig, FieldInfo, QueryOptions } from 'mysql'; import genericPool from 'generic-pool'; import { promisify } from 'util'; import { BaseDriver, GenericDataBaseType, DriverInterface, StreamOptions, DownloadQueryResultsOptions, TableStructure, DownloadTableData, IndexesSQL, DownloadTableMemoryData, } from '@cubejs-backend/query-orchestrator'; const GenericTypeToMySql: Record<GenericDataBaseType, string> = { string: 'varchar(255) CHARACTER SET utf8mb4', text: 'varchar(255) CHARACTER SET utf8mb4', decimal: 'decimal(38,10)', }; /** * MySQL Native types -> SQL type * @link https://github.com/mysqljs/mysql/blob/master/lib/protocol/constants/types.js#L9 */ const MySqlNativeToMySqlType = { [mysql.Types.DECIMAL]: 'decimal', [mysql.Types.NEWDECIMAL]: 'decimal', [mysql.Types.TINY]: 'tinyint', [mysql.Types.SHORT]: 'smallint', [mysql.Types.LONG]: 'int', [mysql.Types.INT24]: 'mediumint', [mysql.Types.LONGLONG]: 'bigint', [mysql.Types.NEWDATE]: 'datetime', [mysql.Types.TIMESTAMP2]: 'timestamp', [mysql.Types.DATETIME2]: 'datetime', [mysql.Types.TIME2]: 'time', [mysql.Types.TINY_BLOB]: 'tinytext', [mysql.Types.MEDIUM_BLOB]: 'mediumtext', [mysql.Types.LONG_BLOB]: 'longtext', [mysql.Types.BLOB]: 'text', [mysql.Types.VAR_STRING]: 'varchar', [mysql.Types.STRING]: 'varchar', }; const MySqlToGenericType: Record<string, GenericDataBaseType> = { mediumtext: 'text', longtext: 'text', mediumint: 'int', smallint: 'int', bigint: 'int', tinyint: 'int', 'mediumint unsigned': 'int', 'smallint unsigned': 'int', 'bigint unsigned': 'int', 'tinyint unsigned': 'int', }; export interface MySqlDriverConfiguration extends ConnectionConfig { readOnly?: boolean, loadPreAggregationWithoutMetaLock?: boolean, storeTimezone?: string, pool?: any } interface MySQLConnection extends Connection { execute: (options: string | QueryOptions, values?: any) => Promise<any> } export class MySqlDriver extends BaseDriver implements DriverInterface { protected readonly config: MySqlDriverConfiguration; protected readonly pool: genericPool.Pool<MySQLConnection>; public constructor(config: MySqlDriverConfiguration = {}) { super(); const { pool, ...restConfig } = config; this.config = { host: process.env.CUBEJS_DB_HOST, database: process.env.CUBEJS_DB_NAME, port: <any>process.env.CUBEJS_DB_PORT, user: process.env.CUBEJS_DB_USER, password: process.env.CUBEJS_DB_PASS, socketPath: process.env.CUBEJS_DB_SOCKET_PATH, timezone: 'Z', ssl: this.getSslOptions(), dateStrings: true, readOnly: true, ...restConfig, }; this.pool = genericPool.createPool({ create: async () => { const conn: any = mysql.createConnection(this.config); const connect = promisify(conn.connect.bind(conn)); if (conn.on) { conn.on('error', () => { conn.destroy(); }); } conn.execute = promisify(conn.query.bind(conn)); await connect(); return conn; }, validate: async (connection) => { try { await connection.execute('SELECT 1'); } catch (e) { this.databasePoolError(e); return false; } return true; }, destroy: (connection) => promisify(connection.end.bind(connection))(), }, { min: 0, max: process.env.CUBEJS_DB_MAX_POOL && parseInt(process.env.CUBEJS_DB_MAX_POOL, 10) || 8, evictionRunIntervalMillis: 10000, softIdleTimeoutMillis: 30000, idleTimeoutMillis: 30000, testOnBorrow: true, acquireTimeoutMillis: 20000, ...pool }); } public readOnly() { return !!this.config.readOnly; } protected withConnection(fn: (conn: MySQLConnection) => Promise<any>) { const self = this; const connectionPromise = this.pool.acquire(); let cancelled = false; const cancelObj: any = {}; const promise: any = connectionPromise.then(async conn => { const [{ connectionId }] = await conn.execute('select connection_id() as connectionId'); cancelObj.cancel = async () => { cancelled = true; await self.withConnection(async processConnection => { await processConnection.execute(`KILL ${connectionId}`); }); }; return fn(conn) .then(res => this.pool.release(conn).then(() => { if (cancelled) { throw new Error('Query cancelled'); } return res; })) .catch((err) => this.pool.release(conn).then(() => { if (cancelled) { throw new Error('Query cancelled'); } throw err; })); }); promise.cancel = () => cancelObj.cancel(); return promise; } public async testConnection() { // eslint-disable-next-line no-underscore-dangle const conn: MySQLConnection = await (<any> this.pool)._factory.create(); try { return await conn.execute('SELECT 1'); } finally { // eslint-disable-next-line no-underscore-dangle await (<any> this.pool)._factory.destroy(conn); } } public async query(query: string, values: unknown[]) { return this.withConnection(async (conn) => { await this.setTimeZone(conn); return conn.execute(query, values); }); } protected setTimeZone(conn: MySQLConnection) { return conn.execute(`SET time_zone = '${this.config.storeTimezone || '+00:00'}'`, []); } public async release() { await this.pool.drain(); await this.pool.clear(); } public informationSchemaQuery() { return `${super.informationSchemaQuery()} AND columns.table_schema = '${this.config.database}'`; } public quoteIdentifier(identifier: string) { return `\`${identifier}\``; } public fromGenericType(columnType: GenericDataBaseType) { return GenericTypeToMySql[columnType] || super.fromGenericType(columnType); } public loadPreAggregationIntoTable(preAggregationTableName: string, loadSql: any, params: any, tx: any) { if (this.config.loadPreAggregationWithoutMetaLock) { return this.cancelCombinator(async (saveCancelFn: any) => { await saveCancelFn(this.query(`${loadSql} LIMIT 0`, params)); await saveCancelFn(this.query(loadSql.replace(/^CREATE TABLE (\S+) AS/i, 'INSERT INTO $1'), params)); }); } return super.loadPreAggregationIntoTable(preAggregationTableName, loadSql, params, tx); } public async stream(query: string, values: unknown[], { highWaterMark }: StreamOptions) { // eslint-disable-next-line no-underscore-dangle const conn: MySQLConnection = await (<any> this.pool)._factory.create(); try { await this.setTimeZone(conn); const [rowStream, fields] = await ( new Promise<[any, mysql.FieldInfo[]]>((resolve, reject) => { const stream = conn.query(query, values).stream({ highWaterMark }); stream.on('fields', (f) => { resolve([stream, f]); }); stream.on('error', (e) => { reject(e); }); }) ); return { rowStream, types: this.mapFieldsToGenericTypes(fields), release: async () => { // eslint-disable-next-line no-underscore-dangle await (<any> this.pool)._factory.destroy(conn); } }; } catch (e) { // eslint-disable-next-line no-underscore-dangle await (<any> this.pool)._factory.destroy(conn); throw e; } } protected mapFieldsToGenericTypes(fields: mysql.FieldInfo[]) { return fields.map((field) => { // @ts-ignore let dbType = mysql.Types[field.type]; if (field.type in MySqlNativeToMySqlType) { // @ts-ignore dbType = MySqlNativeToMySqlType[field.type]; } return { name: field.name, type: this.toGenericType(dbType) }; }); } public async downloadQueryResults(query: string, values: unknown[], options: DownloadQueryResultsOptions) { if ((options || {}).streamImport) { return this.stream(query, values, options); } return this.withConnection(async (conn) => { await this.setTimeZone(conn); return new Promise((resolve, reject) => { conn.query(query, values, (err, rows, fields) => { if (err) { reject(err); } else { resolve({ rows, types: this.mapFieldsToGenericTypes(<FieldInfo[]>fields), }); } }); }); }); } public toColumnValue(value: any, genericType: GenericDataBaseType) { if (genericType === 'timestamp' && typeof value === 'string') { return value && value.replace('Z', ''); } if (genericType === 'boolean' && typeof value === 'string') { if (value.toLowerCase() === 'true') { return true; } if (value.toLowerCase() === 'false') { return false; } } return super.toColumnValue(value, genericType); } protected isDownloadTableDataRow(tableData: DownloadTableData): tableData is DownloadTableMemoryData { return (<DownloadTableMemoryData> tableData).rows !== undefined; } public async uploadTableWithIndexes( table: string, columns: TableStructure, tableData: DownloadTableData, indexesSql: IndexesSQL ) { if (!this.isDownloadTableDataRow(tableData)) { throw new Error(`${this.constructor} driver supports only rows upload`); } await this.createTable(table, columns); try { const batchSize = 1000; // TODO make dynamic? for (let j = 0; j < Math.ceil(tableData.rows.length / batchSize); j++) { const currentBatchSize = Math.min(tableData.rows.length - j * batchSize, batchSize); const indexArray = Array.from({ length: currentBatchSize }, (v, i) => i); const valueParamPlaceholders = indexArray.map(i => `(${columns.map((c, paramIndex) => this.param(paramIndex + i * columns.length)).join(', ')})`).join(', '); const params = indexArray.map(i => columns .map(c => this.toColumnValue(tableData.rows[i + j * batchSize][c.name], c.type))) .reduce((a, b) => a.concat(b), []); await this.query( `INSERT INTO ${table} (${columns.map(c => this.quoteIdentifier(c.name)).join(', ')}) VALUES ${valueParamPlaceholders}`, params ); } for (let i = 0; i < indexesSql.length; i++) { const [query, p] = indexesSql[i].sql; await this.query(query, p); } } catch (e) { await this.dropTable(table); throw e; } } public toGenericType(columnType: string) { return MySqlToGenericType[columnType.toLowerCase()] || MySqlToGenericType[columnType.toLowerCase().split('(')[0]] || super.toGenericType(columnType); } }
the_stack
import { Injectable } from '@angular/core'; import * as _ from 'lodash'; import * as moment from 'moment'; import { QUARTER } from './../constants/quarter'; import { LoggerService } from './logger.service'; import { RefactorFieldsService } from './refactor-fields.service'; @Injectable() export class UtilsService { constructor(private logger: LoggerService, private refactorFieldsService: RefactorFieldsService) {} setTimeoutPromise(milliseconds) { const promise = new Promise((resolve: any, reject: any) => { setTimeout(() => { resolve(resolve, reject); }, milliseconds); }); return promise; } isObjectEmpty = obj => { return Object.keys(obj).length === 0 && obj.constructor === Object; } debounce(func, wait, immediate) { let timeout; return function() { const context = this, args = arguments; const later = function() { timeout = null; if (!immediate) { func.apply(context, args); } }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; } isObject(val) { if (val === null) { return false; } return typeof val === 'function' || typeof val === 'object'; } clickClearDropdown() { setTimeout(function() { const clear = document.getElementsByClassName( 'btn btn-xs btn-link pull-right' ); for (let len = 0; len < clear.length; len++) { const element: HTMLElement = clear[len] as HTMLElement; element.click(); } }, 10); } objectToArray(object, keyLabel = 'key', valueLabel = 'value') { return _.map(object, (element, key, array) => { const arrayElement: any = {}; arrayElement[keyLabel] = key; arrayElement[valueLabel] = element; return arrayElement; }); } arrayToCommaSeparatedString(arr) { let str = ''; for (let i = 0; i < arr.length; i++) { i === arr.length - 1 ? str = str + arr[i] : str = str + arr[i] + ','; } return str; } massageTableData(data) { /* * added by Trinanjan 14/02/2017 * the funciton replaces keys of the table header data to a readable format */ const refactoredService = this.refactorFieldsService; const newData = []; data.map(function(responseData) { const KeysTobeChanged = Object.keys(responseData); let newObj = {}; KeysTobeChanged.forEach(element => { const elementnew = refactoredService.getDisplayNameForAKey( element.toLocaleLowerCase() ) || element; newObj = Object.assign(newObj, { [elementnew]: responseData[element] }); }); newData.push(newObj); }); return newData; } addOrReplaceElement(array, toAddElement, comparator) { const i = _.findIndex(array, (element, index, _array) => { return comparator(element, index, _array); }); if (i >= 0) { array.splice(i, 1, toAddElement); } else { array.push(toAddElement); } } getParamsFromUrlSnippet(urlSnippet) { const split = urlSnippet.split('?'); const url = split[0]; const inputParams = split[1].split('&'); const params = {}; _.each(inputParams, arg => { const key = arg.substring(0, arg.indexOf('=')); const value = arg.substring(arg.indexOf('=') + 1, arg.length); params[key] = value; }); return { url: url, params: params }; } arrayToObject(array, keyLabel = 'key', valueLabel = 'value') { const object = {}; _.each(array, (element, index, list) => { object[element[keyLabel]] = element[valueLabel]; }); return object; } /** * Funciton added by trinanjan on 30.01.2018 * This function process the queryparams from router snapshot and * passes the required formate obj for filter parameter */ processFilterObj(data) { let object = {}; if (data.filter !== '' && data.filter !== undefined ) { const eachFilterObj = data.filter.split('*'); _.each(eachFilterObj, (element, index) => { const eachFilterParam = element.split('='); const key = eachFilterParam[0]; const value = eachFilterParam[1]; object[key] = value; }); } else { object = {}; } return object; } /** * Funciton added by trinanjan on 31.01.2018 * This function process filter parameter to be passes to required format * Example Input --> {'tagged':'true','targetType':'ec2'} * Example Output --> {'filter': 'tagged=true*targetType=ec2'} */ makeFilterObj(data) { try { let object = {}; const localArray = []; if (Object.keys(data).length === 0 && data.constructor === Object) { return object; } else { const localObjKeys = Object.keys(data); _.each(localObjKeys, (element, index) => { if (typeof data[element] !== 'undefined') { const localValue = data[element].toString(); const localKeys = element.toString(); const localObj = localKeys + '=' + localValue; localArray.push(localObj); } }); object = { filter: localArray.join('*') }; return object; } } catch (error) { this.logger.log('error', 'js error - ' + error); } } calculateDate(_JSDate) { if (!_JSDate) { return 'No Data'; } const date = new Date(_JSDate); const year = date.getFullYear().toString(); const month = date.getMonth() + 1; let monthString; if (month < 10) { monthString = '0' + month.toString(); } else { monthString = month.toString(); } const day = date.getDate(); let dayString; if (day < 10) { dayString = '0' + day.toString(); } else { dayString = day.toString(); } return monthString + '-' + dayString + '-' + year ; } calculateDateAndTime(_JSDate) { const monthsList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']; const date = new Date(_JSDate); const year = date.getFullYear(); const month = date.getMonth(); const day = date.getDate(); const monthValue = monthsList[month]; let hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); const ampm = (hours >= 12) ? 'PM' : 'AM'; if (ampm === 'PM') { hours = hours - 12; } return monthValue + ' ' + day + ',' + ' ' + year + ' ' + hours + ':' + minutes + ':' + seconds + ' ' + ampm; } getNumberOfWeeks = function(year, quarter) { const currentQuarter = QUARTER.quarterObj[quarter]; const fromDate = moment(year + '-' + currentQuarter.fromMonth + '-' + currentQuarter.fromDay); let weeks = 14; if (+quarter === 1 ) { // if year is leap year and first quarter starts with Sunday. if (moment([year]).isLeapYear() && fromDate.weekday() === 0) { weeks = 13; // if first quarter starts with Sunday or Monday. } else if (fromDate.weekday() === 0 || fromDate.weekday() === 1) { weeks = 13; } // if second quarter starts with Sunday. } else if (+quarter === 2 && fromDate.weekday() === 0) { weeks = 13; } return weeks; }; checkIfAPIReturnedDataIsEmpty(data) { // There can be multiple scenarios: /* - data can be an empty object - data can be an empty array - data can be undefined */ let isEmpty = false; if (data) { if (Array.isArray(data) && data.length === 0) { isEmpty = true; } else if (Object.keys(data).length === 0 && data.constructor === Object) { isEmpty = true; } } else { isEmpty = true; } return isEmpty; } strToBool(str) { // will match one and only one of the string 'true','1', or 'on' rerardless // of capitalization and regardless off surrounding white-space. // const regex = /^\s*(true|1|on)\s*$/i; return regex.test(str); } extractNumbersFromString(str) { const numb = str.match(/\d/g); const number = numb.join(''); return number; } capitalizeFirstLetter(string): any { return string.charAt(0).toUpperCase() + string.slice(1); } findValueInArray(array, valueToBeFound) { return array.findIndex(eachValue => { return (eachValue && eachValue.toLowerCase()) === (valueToBeFound && valueToBeFound.toLowerCase()); }); } getContextUrlExceptDomain(url) { const parser = this.parseUrl(url); const pathname = parser.pathname || ''; const query = parser.search || ''; const fragments = parser.hash || ''; return pathname + query + fragments; } parseUrl(url) { let parser; if (url && url !== '') { parser = document.createElement('a'); parser.href = url; /* parser.protocol; // => "http:" parser.hostname; // => "example.com" parser.port; // => "3000" parser.pathname; // => "/pathname/" parser.search; // => "?search=test" parser.hash; // => "#hash" parser.host; // => "example.com:3000" */ } return parser; } getDateAndTime(dateWithoutTime, assumeUTCEndOfDay = true) { const date = new Date(dateWithoutTime); const hours = assumeUTCEndOfDay ? 23 : 0; const minutes = assumeUTCEndOfDay ? 59 : 0; const seconds = 0; const date_utc = this.convertDateToUTCEndOfDay(date, hours, minutes, seconds); const date_currentTimeZone = new Date(date_utc); return date_currentTimeZone; } convertDateToUTCEndOfDay(date, hours = 23, minutes = 59, seconds = 0) { return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), hours, minutes, seconds); } getUTCDate(date) { // get UTC Date in YYYY-MM-DD format const utcDate = moment.utc(date).format('YYYY-MM-DD'); return utcDate; } }
the_stack
import { BrandedButton } from '@covid/components'; import { ShareButton } from '@covid/components/buttons'; import { Text } from '@covid/components/typography'; import { WebView } from '@covid/components/WebView'; import Analytics, { events } from '@covid/core/Analytics'; import { TCoordinates, TPersonalisedLocalData } from '@covid/core/AsyncStorageService'; import { patientService } from '@covid/core/patient/PatientService'; import { TRootState } from '@covid/core/state/root'; import { selectStartupInfo } from '@covid/core/state/selectors'; import { TStartupInfo } from '@covid/core/user/dto/UserAPIContracts'; import { appCoordinator } from '@covid/features/AppCoordinator'; import i18n from '@covid/locale/i18n'; import NavigatorService from '@covid/NavigatorService'; import { sizes } from '@covid/themes'; import { loadEstimatedCasesCartoMap } from '@covid/utils/files'; import { useNavigation } from '@react-navigation/native'; import { colors } from '@theme'; import * as React from 'react'; import { Image, StyleSheet, TouchableOpacity, View } from 'react-native'; import { useSelector } from 'react-redux'; const MAP_HEIGHT = 246; interface IEmptyViewProps { primaryLabel?: string; secondaryLabel?: string; ctaLabel?: string; onPress: VoidFunction; } enum EMapEventOrigin { Arrow = 'arrow', Map = 'map', } enum EMapType { Carto = 'carto', ImageAsset = 'image_asset', } function EmptyView({ onPress, ...props }: IEmptyViewProps) { const [html, setHtml] = React.useState<string>(''); const startupInfo = useSelector<TRootState, TStartupInfo | undefined>(selectStartupInfo); const primaryLabel = props.primaryLabel ?? i18n.t('covid-cases-map.covid-in-x', { location: 'your area' }); const secondaryLabel = props.secondaryLabel ?? i18n.t('covid-cases-map.update-postcode'); const ctaLabel = props.ctaLabel ?? i18n.t('covid-cases-map.update-postcode-cta'); const [showUpdatePostcode, setShowUpdatePostcode] = React.useState<boolean | undefined>( startupInfo?.show_edit_location, ); const showCartoMap = true; const root = showCartoMap ? { paddingTop: 0 } : {}; const showMap = () => { Analytics.track(events.ESTIMATED_CASES_MAP_CLICKED, { origin: EMapEventOrigin.Map }); NavigatorService.navigate('EstimatedCases'); }; React.useEffect(() => setShowUpdatePostcode(startupInfo?.show_edit_location), [startupInfo]); React.useEffect(() => { let isMounted = true; const runAsync = async () => { try { Analytics.track(events.ESTIMATED_CASES_MAP_EMPTY_STATE_SHOWN); const data = await loadEstimatedCasesCartoMap(); if (isMounted) { setHtml(data); } } catch (_) {} }; runAsync(); return () => { isMounted = false; }; }, []); return ( <View style={[styles.root, root]}> <View style={{ marginVertical: sizes.l, paddingHorizontal: sizes.m }}> <Text rhythm={8} textClass="h4"> {primaryLabel} </Text> <Text inverted colorPalette="uiDark" colorShade="dark" textClass="pSmallLight"> {i18n.t('covid-cases-map.current-estimates')} </Text> </View> {showCartoMap ? ( <View style={styles.mapContainer}> <TouchableOpacity activeOpacity={0.6} onPress={showMap}> <WebView originWhitelist={['*']} pointerEvents="none" source={{ html }} style={styles.webview} /> </TouchableOpacity> </View> ) : null} {showUpdatePostcode ? ( <> <View style={{ paddingHorizontal: sizes.m, paddingVertical: sizes.m }}> <Text inverted colorPalette="uiDark" colorShade="dark" textClass="pSmallLight"> {secondaryLabel} </Text> </View> <View style={{ paddingHorizontal: sizes.m }}> <BrandedButton onPress={onPress} style={styles.detailsButton}> <Text colorPalette="burgundy" textClass="pLight"> {ctaLabel} </Text> </BrandedButton> </View> </> ) : null} </View> ); } interface IProps { isSharing?: boolean; } type TMapConfig = { coordinates: TCoordinates; zoom: number; }; const DEFAULT_MAP_CENTER: TCoordinates = { lat: 53.963843, lng: -3.823242 }; const ZOOM_LEVEL_CLOSER = 10.5; const ZOOM_LEVEL_FURTHER = 6; export function EstimatedCasesMapCard({ isSharing }: IProps) { const { navigate } = useNavigation(); const localData = useSelector<TRootState, TPersonalisedLocalData | undefined>( (state) => state.content.personalizedLocalData, ); const viewRef = React.useRef(null); const webViewRef = React.useRef<WebView>(null); const [displayLocation, setDisplayLocation] = React.useState<string>('your area'); const [mapUrl, setMapUrl] = React.useState<string | null>(null); const [showEmpty, setShowEmpty] = React.useState<boolean>(true); const [useCartoMap, setUseCartoMap] = React.useState<boolean>(true); const [html, setHtml] = React.useState<string>(''); const [mapConfig, setTMapConfig] = React.useState<TMapConfig>({ coordinates: DEFAULT_MAP_CENTER, zoom: ZOOM_LEVEL_FURTHER, }); React.useEffect(() => { // Use carto map if map url is not avaliable const hasMapUrl = !!localData?.mapUrl; setUseCartoMap(!hasMapUrl); Analytics.track(events.ESTIMATED_CASES_MAP_SHOWN, { type: hasMapUrl ? EMapType.ImageAsset : EMapType.Carto }); // Show empty state if data is missing if (!localData) { setShowEmpty(true); return; } // Show to up date local data setDisplayLocation(localData!.name); setMapUrl(localData!.mapUrl); setShowEmpty(false); // Update carto's map center if map url isn't avaliable if (!hasMapUrl) { syncMapCenter(); } }, [localData]); React.useEffect(() => { if (!webViewRef.current) return; webViewRef.current!.call('updateMapView', mapConfig); }, [mapConfig, setTMapConfig, webViewRef.current]); React.useEffect(() => { let isMounted = true; Analytics.track(events.ESTIMATED_CASES_MAP_EMPTY_STATE_SHOWN); (async () => { try { if (isMounted) { setHtml(await loadEstimatedCasesCartoMap()); } } catch (_) {} })(); return function cleanUp() { isMounted = false; }; }, []); const syncMapCenter = () => { // Set defaults center let config = { coordinates: { lat: DEFAULT_MAP_CENTER.lat, lng: DEFAULT_MAP_CENTER.lng }, zoom: ZOOM_LEVEL_FURTHER, }; // Use data from API if (localData?.mapConfig) { config = { coordinates: { lat: localData.mapConfig.lat, lng: localData.mapConfig.lng }, zoom: ZOOM_LEVEL_CLOSER, }; } setTMapConfig(config); }; const onEvent = (type: string) => { if (type === 'mapLoaded') { syncMapCenter(); } }; const map = (): React.ReactNode => { if (useCartoMap) { return ( <WebView onEvent={onEvent} originWhitelist={['*']} pointerEvents="none" ref={webViewRef} source={{ html }} style={styles.webview} /> ); } return <Image source={{ uri: mapUrl ?? '' }} style={styles.webview} />; }; const share = async () => { Analytics.track(events.ESTIMATED_CASES_MAP_SHARE_CLICKED); navigate('Share', { sharable: 'MAP' }); }; const onMapTapped = () => { Analytics.track(events.ESTIMATED_CASES_MAP_CLICKED, { origin: EMapEventOrigin.Map }); NavigatorService.navigate('EstimatedCases'); }; if (showEmpty) { return ( <EmptyView onPress={async () => { const profile = await patientService.myPatientProfile(); if (profile) appCoordinator.startEditLocation(profile!); }} /> ); } return ( <View style={styles.root}> <View collapsable={false} ref={viewRef} style={styles.snapshotContainer}> <View style={{ marginVertical: isSharing ? 4 : 24, paddingHorizontal: sizes.m }}> <Text rhythm={8} textClass="h4"> {i18n.t('covid-cases-map.covid-in-x', { location: displayLocation })} </Text> <Text inverted colorPalette="uiDark" colorShade="dark" textClass="pSmallLight"> {i18n.t('covid-cases-map.current-estimates')} </Text> </View> <View style={styles.mapContainer}> {isSharing ? ( <>{map()}</> ) : ( <TouchableOpacity activeOpacity={0.6} onPress={onMapTapped}> {map()} </TouchableOpacity> )} </View> </View> {!isSharing ? <ShareButton label={i18n.t('covid-cases-map.share')} onPress={share} /> : null} </View> ); } const styles = StyleSheet.create({ detailsButton: { backgroundColor: 'transparent', borderColor: colors.purple, borderWidth: 1, marginBottom: sizes.l, paddingHorizontal: sizes.xxl, }, detailsButtonLabel: { color: colors.purple, fontSize: 14, }, divider: { alignSelf: 'center', backgroundColor: colors.backgroundFour, height: 1, width: '92%', }, emptyStateArrow: { alignItems: 'center', flexDirection: 'row', position: 'absolute', right: 0, }, mapContainer: { width: '100%', }, mapImage: { height: MAP_HEIGHT, resizeMode: 'cover', }, postcodeButton: { marginBottom: sizes.l, }, primaryLabel: { color: colors.textDark, textAlign: 'center', }, root: { backgroundColor: colors.white, borderRadius: sizes.m, marginVertical: sizes.xs, overflow: 'hidden', }, shareIcon: { marginRight: sizes.xs, marginTop: sizes.xxs, }, shareLabel: { color: colors.purple, fontSize: 14, textAlign: 'center', }, shareTouchable: { flexDirection: 'row', justifyContent: 'center', marginVertical: sizes.m, paddingTop: sizes.xxs, }, snapshotContainer: { backgroundColor: colors.white, width: '100%', }, stats: { marginRight: sizes.xs, }, statsContainer: { alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: sizes.m, width: '100%', }, statsLabel: { fontSize: 14, lineHeight: 20, marginBottom: sizes.xxs, }, statsRow: { alignItems: 'flex-end', flexDirection: 'row', }, webview: { height: MAP_HEIGHT, }, });
the_stack
import React from 'react'; import { List } from 'immutable'; import { FormattedMessage } from 'react-intl'; import { Button } from 'react-bootstrap'; import { IMapEditorEvent, TMapEditorType } from 'ibax/geo'; import themed from 'components/Theme/themed'; import { loadModules } from 'esri-loader'; import Autosuggest, { GetSuggestionValue, SuggestionsFetchRequested, ChangeEvent, OnSuggestionSelected } from 'react-autosuggest'; import Modal, { IModalProps } from './'; import Validation from 'components/Validation'; import MapView from 'components/Map/MapView'; import Tooltip from 'components/Tooltip'; import SegmentButton from 'components/Button/SegmentButton'; export interface IMapEditorModalProps { mapType?: 'streets' | 'satellite' | 'hybrid' | 'topo' | 'gray' | 'dark-gray' | 'oceans' | 'national-geographic' | 'terrain' | 'osm'; tool?: TMapEditorType; coords: [number, number][]; center?: [number, number]; zoom?: number; } interface IMapEditorModalState { search: string; tool: TMapEditorType; points: List<[number, number]>; area: number; pending: boolean; address: string; center?: [number, number]; suggestions: ISuggestion[]; } interface ISuggestion { address: string; location: [number, number]; } export const PlacesAutocompleteList = themed.div` position: relative; .react-autosuggest__suggestions-list { position: absolute; top: 0; left: 0; right: 0; background: #fff; z-index: 10; list-style-type: none; padding: 0; margin: 0; border-right: 1px solid #66afe9; border-left: 1px solid #66afe9; border-bottom: 1px solid #66afe9; } .react-autosuggest__suggestion { padding: 10px; } .react-autosuggest__suggestion--highlighted { background: #fafafa; cursor: pointer; } .places-autocomplete-container__item__description { color: red !important; } `; interface IToolButtonProps { tooltip: JSX.Element; onClick: React.EventHandler<React.MouseEvent<HTMLButtonElement>>; className?: string; disabled?: boolean; } const ToolButton: React.SFC<IToolButtonProps> = props => ( <div className="mr" style={{ display: 'inline-block' }}> <Tooltip body={props.tooltip}> <button type="button" className="btn btn-icon" onClick={props.onClick} disabled={props.disabled}> <span className={`btn-label ${props.className || ''}`} /> </button> </Tooltip> </div> ); const mapTools = ['point', 'line', 'polygon']; class MapEditorModal extends Modal<IMapEditorModalProps, IMapEditorEvent, IMapEditorModalState> { private _isMounted = false; constructor(props: any) { super(props); this.state = { points: List(), tool: props.params.tool || 'point', area: 0, pending: false, address: '', search: '', center: props.params.center, suggestions: [] }; } componentDidMount() { this._isMounted = true; this.initialize(this.props); } componentWillUnmount() { this._isMounted = false; } componentWillReceiveProps(props: IModalProps<IMapEditorModalProps, IMapEditorEvent>) { this.initialize(props); } initialize(props: IModalProps<IMapEditorModalProps, IMapEditorEvent>) { this.setState({ points: List(props.params.coords || []) }); } calcResult(coords: [number, number][], onResult: (result: string) => void) { loadModules(['esri/tasks/Locator', 'esri/geometry/Polygon']).then((deps: [__esri.LocatorConstructor, __esri.PolygonConstructor]) => { const [Locator, Polygon] = deps; const locator = new Locator({ url: 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer' }); const centerPoint = new Polygon({ rings: [coords] }).centroid; locator.locationToAddress(centerPoint).then(result => { onResult(result.address || ''); }).catch(e => { onResult(''); }); }).catch(e => { onResult(''); }); } onSuccess = (values: { [key: string]: any }) => { this.setState({ pending: true }); const points = this.state.points.toArray(); this.calcResult(points, result => { if (this._isMounted) { this.props.onResult({ type: this.state.tool, coords: this.state.points.toArray(), area: this.state.area, address: result }); this.setState({ pending: false }); } }); } onClick = (e: __esri.MapViewClickEvent) => { const points = 'point' === this.state.tool ? List<[number, number]>([[e.mapPoint.longitude, e.mapPoint.latitude]]) : this.state.points.push([e.mapPoint.longitude, e.mapPoint.latitude]); this.setState({ points }); } onUndo = () => { const points = this.state.points.pop(); this.setState({ points }); } onClear = () => { this.setState({ points: List<[number, number]>() }); } onAreaChange = (area: number) => { this.setState({ area }); } onChange = (event: React.FormEvent<any>, params: ChangeEvent) => { this.setState({ search: params.newValue }); } onSuggestionSelected: OnSuggestionSelected<ISuggestion> = (e, data) => { this.setState({ address: data.suggestion.address, center: data.suggestion.location }); } getSuggestionValue: GetSuggestionValue<ISuggestion> = suggestion => { return suggestion.address; } onSuggestionsFetchRequested: SuggestionsFetchRequested = ({ value }) => { loadModules(['esri/tasks/Locator']).then((deps: [__esri.LocatorConstructor]) => { const [Locator] = deps; const locator = new Locator({ url: 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer' }); locator.addressToLocations({ address: { SingleLine: value, SingleLineFieldName: value }, maxLocations: 5 } as any).then(result => { if (this._isMounted) { this.setState({ suggestions: result.map(l => ({ address: l.address, location: [l.location.longitude, l.location.latitude] as [number, number] })) }); } }); }).catch(err => { /* Silently suppress errors */ }); } onSuggestionsClearRequested = () => { this.setState({ suggestions: [] }); } onToolChange = (index: number) => { this.setState({ tool: mapTools[index] as any, points: List<[number, number]>() }); } render() { return ( <div> <Modal.Header> <FormattedMessage id="map.editor" defaultMessage="Map editor" /> </Modal.Header> <Modal.Body style={{ paddingBottom: 0 }}> <PlacesAutocompleteList> <Autosuggest suggestions={this.state.suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} getSuggestionValue={this.getSuggestionValue} renderSuggestionsContainer={params => ( <PlacesAutocompleteList {...params.containerProps}> {params.children} </PlacesAutocompleteList> )} renderSuggestion={(suggestion, params) => ( <div key={suggestion.address} className={params.isHighlighted ? 'places-autocomplete-container__item places-autocomplete-container__item_active' : 'places-autocomplete-container__item'} > {suggestion.address} </div> )} inputProps={{ placeholder: '', value: this.state.search, onChange: this.onChange, className: 'form-control' }} /> </PlacesAutocompleteList> </Modal.Body> <Validation.components.ValidatedForm onSubmitSuccess={this.onSuccess}> <Modal.Body style={{ paddingTop: 0 }}> <div style={{ minWidth: 500, width: '60%' }}> <div className="mt"> <MapView height={400} tool={this.state.tool} center={this.state.center} zoom={this.props.params.zoom} mapType={this.props.params.mapType} onClick={this.onClick} coords={this.state.points.toArray()} onAreaChange={this.onAreaChange} /> </div> </div> <div className="mt text-center clearfix" style={{ position: 'relative' }}> <div style={{ position: 'relative', zIndex: 1 }}> <div className="pull-right"> <FormattedMessage id="map.area" defaultMessage="Area: {value}" values={{ value: this.state.area.toFixed(2) }} /> <span>&nbsp;</span> <span className="text-muted"> <FormattedMessage id="map.meter.short" defaultMessage="m" /><sup>2</sup> </span> </div> <div className="pull-left"> <ToolButton tooltip={<FormattedMessage id="undo" defaultMessage="Undo" />} onClick={this.onUndo} disabled={0 === this.state.points.count()} className="fa fa-undo" /> <ToolButton tooltip={<FormattedMessage id="clear" defaultMessage="Clear" />} onClick={this.onClear} disabled={0 === this.state.points.count()} className="fa fa-trash" /> </div> </div> <div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, textAlign: 'center', zIndex: 0 }}> <SegmentButton activeIndex={mapTools.indexOf(this.state.tool)} onChange={this.onToolChange} items={[ <FormattedMessage key="point" id="map.tool.point" defaultMessage="Point" />, <FormattedMessage key="line" id="map.tool.line" defaultMessage="Line" />, <FormattedMessage key="polygon" id="map.tool.polygon" defaultMessage="Polygon" /> ]} /> </div> </div> </Modal.Body> <Modal.Footer className="text-right"> <Button type="button" bsStyle="link" onClick={this.props.onCancel.bind(this)}> <FormattedMessage id="cancel" defaultMessage="Cancel" /> </Button> <Validation.components.ValidatedSubmit bsStyle="primary" disabled={this.state.pending}> <FormattedMessage id="confirm" defaultMessage="Confirm" /> </Validation.components.ValidatedSubmit> </Modal.Footer> </Validation.components.ValidatedForm> </div> ); } } export default MapEditorModal;
the_stack
import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, HostListener, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { ControllerClient } from '../../client'; import { decodeFrameData, decodeFrames } from '@deepkit/framework-debug-api'; import { Application, Container, Graphics, InteractionEvent, Rectangle, Text, TextStyle } from 'pixi.js'; import { FrameCategory, FrameEnd, FrameStart } from '@deepkit/stopwatch'; import * as Hammer from 'hammerjs'; import { formatTime, FrameItem, FrameParser } from './frame'; import { FrameContainer } from './frame-container'; import { Subject } from 'rxjs'; import { ClientProgress } from '@deepkit/rpc'; class ViewState { scrollX: number = 0; zoom: number = 20; width: number = 500; height: number = 100; scrollWidth: number = 1; } interface FrameData { id: number; worker: number; data: Uint8Array; } class ProfilerContainer extends Container { protected headerLines = new Graphics(); protected selectedLines = new Graphics(); protected headerText = new Container(); protected frameContainer = new Container(); protected offsetText: Text; protected textStyle = { fontSize: 12, fill: 0xdddddd } as TextStyle; protected hoverMenu?: Container; public selected?: FrameItem; public ignoreNextClick: boolean = false; protected inactiveAlpha = 0.6; protected parserSub = this.parser.subscribe(this.onUpdate.bind(this)); constructor( public parser: FrameParser, public viewState: ViewState, public onSelect: (frame?: FrameItem) => void, ) { super(); this.addChild(this.headerLines); this.addChild(this.headerText); this.addChild(this.frameContainer); this.addChild(this.selectedLines); this.offsetText = new Text('0', this.textStyle); this.addChild(this.offsetText); this.offsetText.x = 0; this.offsetText.y = 13; this.hitArea = new Rectangle(0, 0, this.viewState.width, this.viewState.height); this.interactive = true; this.on('click', () => { if (this.ignoreNextClick) { this.ignoreNextClick = false; return; } this.setSelected(undefined); }); this.frameContainer.y = 15; } onUpdate(create: FrameItem[], update: FrameItem[], remove: FrameItem[]) { // console.log('create', create, remove); for (const item of remove) { if (!item.container) continue; this.frameContainer.removeChild(item.container); item.container = undefined; } const add: FrameContainer[] = []; for (const item of create) { const container = item.container = new FrameContainer(item, this.parser.offsetX, this.viewState); container.rectangle.interactive = true; container.rectangle.addListener('click', (event) => { if (this.ignoreNextClick) { //the bg click resets it return; } event.stopPropagation(); this.setSelected(item); }); container.rectangle.addListener('mouseover', (event) => { this.onHover(container, event); }); container.rectangle.addListener('mousemove', (event) => { this.onHoverMove(container, event); }); container.rectangle.addListener('mouseout', (event) => { this.onHoverOut(container, event); }); if (this.selected) { container.rectangle.alpha = container.item.frame.id === this.selected.frame.id ? 1 : this.inactiveAlpha; container.text.alpha = container.item.frame.id === this.selected.frame.id ? 1 : this.inactiveAlpha; } add.push(container); // this.containers.push(container); // console.log('children[0].item.x > item.x', children[0] ? children[0].item.frame.label : '', children[0] ? children[0].item.x : '', item.x, item.frame.label); // if (children.length) { // if (children[0].item.x > item.x) { // this.frameContainer.addChildAt(container, 0); // // } else if (children[children.length-1].item.x < item.x) { // } else { // this.frameContainer.addChild(container); // } // } else { // this.frameContainer.addChild(container); // } } // console.log(children.map(v => v.item.frame.label)); if (add.length) { this.frameContainer.addChild(...add); this.containers.sort((a, b) => { return a.item.x - b.item.x; }); } // this.updateTransform(); } timestampToX(timestamp: number): number { return ((timestamp - this.parser.offsetX - this.viewState.scrollX) / this.viewState.zoom); } protected setWindow() { // const padding = (this.viewState.width * 0.05) * this.viewState.zoom; const padding = 1; const start = (this.viewState.scrollX) - padding; const end = start + ((this.viewState.width) * this.viewState.zoom) + padding; this.parserSub.setWindow({start, end}); // console.log('setWindow', start, end, this.viewState); } viewChanged() { this.setWindow(); this.update(); } addFrames(frames: (FrameStart | FrameEnd)[]) { this.setWindow(); this.parser.feed(frames); } get containers(): FrameContainer[] { return this.frameContainer.children as FrameContainer[]; } setSelected(frame?: FrameItem) { if (this.selected && this.selected === frame) { this.selected = undefined; } else { this.selected = frame; } for (const container of this.containers) { if (this.selected) { container.rectangle.alpha = container.item.frame.id === this.selected.frame.id ? 1 : this.inactiveAlpha; container.text.alpha = container.item.frame.id === this.selected.frame.id ? 1 : this.inactiveAlpha; } else { container.rectangle.alpha = 1; container.text.alpha = 1; } } this.renderSelectedLines(); this.onSelect(this.selected); } protected onHover(container: FrameContainer, event: InteractionEvent) { if (this.hoverMenu) return; this.hoverMenu = new Container(); const prefix = container.item.frame.category ? '[' + FrameCategory[container.item.frame.category] + '] ' : ''; const message = new Text(prefix + container.item.frame.label + ' (' + formatTime(container.item.took, 3) + ')', this.textStyle); this.hoverMenu.addChild(message); this.hoverMenu.x = event.data.global.x; this.hoverMenu.y = event.data.global.y + 20; this.addChild(this.hoverMenu); } protected onHoverMove(container: FrameContainer, event: InteractionEvent) { if (!this.hoverMenu) return; this.hoverMenu.x = event.data.global.x; this.hoverMenu.y = event.data.global.y + 20; } protected onHoverOut(container: FrameContainer, event: InteractionEvent) { if (!this.hoverMenu) return; this.removeChild(this.hoverMenu); this.hoverMenu = undefined; } forward() { const scrollX = this.selected ? this.selected.x - this.parser.offsetX : this.viewState.scrollX; for (const frame of this.frameContainer.children as FrameContainer[]) { if (frame.item.x - this.parser.offsetX > scrollX) { // this.viewState.scrollX = frame.frame.x - this.offsetX; this.setSelected(frame.item); this.update(); return; } } } update() { for (const layer of this.containers) { layer.update(); } this.renderHeaderLines(); this.renderSelectedLines(); this.hitArea = new Rectangle(0, 0, this.viewState.width, this.viewState.height); } protected renderSelectedLines() { this.selectedLines.clear(); if (this.selected) { this.selectedLines.beginFill(0xeeeeee, 0.5); // this.selectedLines.lineStyle(1, 0x73AB77); this.selectedLines.drawRect(this.timestampToX(this.selected.x), 0, 1, this.viewState.height); if (this.selected.took) { this.selectedLines.drawRect(this.timestampToX(this.selected.x + this.selected.took), 0, 1, this.height); } } this.selectedLines.endFill(); } protected renderHeaderLines() { let padding = 10 / this.viewState.zoom; while (padding < 5) padding += 10 / this.viewState.zoom; const jumpSize = 10 * padding; this.headerLines.clear(); this.headerLines.lineStyle(1, 0xffffff, 0.7); for (const text of this.headerText.children) { text.visible = false; } const offsetTime = this.viewState.scrollX; this.offsetText.text = (offsetTime > 0 ? '+' : '') + formatTime(offsetTime); const maxLines = (this.viewState.width + jumpSize) / padding; for (let i = 0; i < maxLines; i++) { const x = (i * padding); this.headerLines.moveTo(x, 0); this.headerLines.lineStyle(i % 10 === 0 ? 2 : 1, 0xffffff, 0.7); this.headerLines.lineTo(x, i % 10 === 0 ? 12 : i % 5 === 0 ? 7 : 5); if (i % 10 === 0 && x > 0) { let text = this.headerText.children[i] as Text; if (!this.headerText.children[i]) { text = new Text(formatTime(x * this.viewState.zoom), { fontSize: 12, fill: 0xdddddd } as TextStyle); this.headerText.addChild(text); } text.x = x; text.y = 13; text.visible = true; text.text = formatTime(x * this.viewState.zoom); } } } } @Component({ template: ` <dui-window-toolbar for="main"> <dui-button-group> <!-- <dui-button textured icon="arrow_right" (click)="forward()"></dui-button>--> <dui-button textured icon="garbage" (click)="resetProfilerFrames()"></dui-button> </dui-button-group> <div> {{profiler.parser.frames}} frames, {{profiler.parser.rootItems.length}} contexts </div> </dui-window-toolbar> <!-- <div class="top-frames">--> <!-- </div>--> <div class="canvas" #canvas></div> <profile-timeline [parser]="parser" [selected]="selectedFrameChildrenStats.contextStart" (selectItem)="timelineSelect($event)"></profile-timeline> <div class="inspector text-selection" *ngIf="selectedFrame"> <h3>{{selectedFrame.frame.label}}</h3> <div style="margin-bottom: 10px;"> <label>Type</label> {{FrameCategory[selectedFrame.frame.category]}} </div> <div style="margin-bottom: 10px;"> <label>y</label> {{selectedFrame.y}} </div> <ng-container *ngIf="selectedFrameChildrenStats.contextStart"> <div> <label>Context</label> {{FrameCategory[selectedFrameChildrenStats.contextStart.frame.category]}} (#{{selectedFrameChildrenStats.contextStart.frame.context}}) {{selectedFrameChildrenStats.contextStart.frame.label}} </div> <div> <label>Time from start of context</label> {{formatTime(selectedFrame.x - selectedFrameChildrenStats.contextStart.x, 3)}} </div> </ng-container> <div> <label>Total time</label> <ng-container *ngIf="selectedFrame.took"> {{formatTime(selectedFrame.took, 3)}} </ng-container> <ng-container *ngIf="!selectedFrame.took"> Pending </ng-container> </div> <ng-container *ngIf="selectedFrame.frame.category === FrameCategory.http"> <div> <label>Method</label> {{selectedFrameData.method}} </div> <div> <label>Client IP</label> {{selectedFrameData.clientIp}} </div> <div> <label>Response Status</label> {{selectedFrameData.responseStatus || 'pending'}} </div> </ng-container> <ng-container *ngIf="selectedFrame.frame.category === FrameCategory.database"> <div> <label>Entity</label> {{selectedFrameData.className}} </div> <div style="padding: 10px 0;"> <label class="header">SQL</label> <ng-container *ngFor="let item of selectedFrameChildren"> <ng-container *ngIf="item.data && item.frame.category === FrameCategory.databaseQuery"> <div> {{item.data.sql}}<br/> {{item.data.sqlParams|json}} </div> </ng-container> </ng-container> </div> </ng-container> <ng-container *ngIf="selectedFrame.frame.category === FrameCategory.databaseQuery"> <div style="padding: 10px 0;"> <label class="header">SQL</label> {{selectedFrameData.sql}}<br/> {{selectedFrameData.sqlParams|json}} </div> </ng-container> <ng-container *ngIf="selectedFrameChildren.length"> <h4 style="margin-top: 10px;">Child frames ({{selectedFrameChildren.length}})</h4> <div class="child"> <label>Self time</label> <div class="bar"> <div class="bg" [style.width.%]="(selectedFrame.took-selectedFrameChildrenStats.totalTime) / selectedFrame.took * 100"></div> <div class="text"> {{formatTime(selectedFrame.took - selectedFrameChildrenStats.totalTime, 3)}} ({{(selectedFrame.took - selectedFrameChildrenStats.totalTime) / selectedFrame.took * 100|number:'2.2-2'}}%) </div> </div> </div> <div class="child" *ngFor="let item of selectedFrameChildren"> <label>{{item.frame.label}}</label> <div class="bar"> <div class="bg" [style.width.%]="item.took / selectedFrame.took * 100"></div> <div class="text"> {{formatTime(item.took, 3)}} ({{item.took / selectedFrame.took * 100|number:'2.2-2'}}%) </div> </div> </div> </ng-container> <!-- <div>--> <!-- {{selectedFrameData|json}}--> <!-- </div>--> </div> `, styleUrls: ['./profile.component.scss'] }) export class ProfileComponent implements OnInit, OnDestroy, AfterViewInit { FrameCategory = FrameCategory; formatTime = formatTime; protected app = new Application({ width: 500, height: 500, antialias: true, autoDensity: true, transparent: true, resolution: window.devicePixelRatio }); protected frameData: FrameData[] = []; public selectedFrame?: FrameItem; public selectedFrameChildrenStats: { totalTime: number, contextStart?: FrameItem } = { totalTime: 0 }; public selectedFrameChildren: FrameItem[] = []; public selectedFrameData: { [name: string]: any } = {}; protected viewState = new ViewState(); public parser = new FrameParser(); public profiler: ProfilerContainer = new ProfilerContainer(this.parser, this.viewState, this.onSelect.bind(this)); public frameSub?: Subject<Uint8Array>; public frameDataSub?: Subject<Uint8Array>; @ViewChild('canvas', { read: ElementRef }) canvas?: ElementRef; constructor( protected client: ControllerClient, protected cd: ChangeDetectorRef, ) { } timelineSelect(item: FrameItem) { this.viewState.scrollX = item.x - this.parser.offsetX; this.profiler.viewChanged(); this.profiler.setSelected(item); this.profiler.update(); } onSelect(item?: FrameItem) { this.selectedFrame = item; this.selectedFrameData = {}; if (item) { for (const data of this.frameData) { if (data.id === item.frame.id && data.worker === item.frame.worker) { Object.assign(this.selectedFrameData, data.data); } } this.selectedFrameChildren = []; const map: { [id: number]: FrameItem } = {}; const end = item.x + item.took; this.selectedFrameChildrenStats.totalTime = 0; this.selectedFrameChildrenStats.contextStart = undefined; let contextStartFound: boolean = false; const targetY = item.y + 1; for (const child of this.profiler.parser.items) { if (!child) continue; if (!contextStartFound && child.frame.context === item.frame.context && child.frame.worker === item.frame.worker) { contextStartFound = true; this.selectedFrameChildrenStats.contextStart = child; } if (child.frame.context === item.frame.context && child.frame.worker === item.frame.worker && child.x > item.x && child.x < end && child.y === targetY) { this.selectedFrameChildrenStats.totalTime += child.took; this.selectedFrameChildren.push(child); for (const data of this.frameData) { if (data.id === child.frame.id && data.worker === item.frame.worker) { if (!child.data) child.data = {}; Object.assign(child.data, data.data); } } } } } // console.log('selectedFrameChildren', this.selectedFrameChildren); this.cd.detectChanges(); } ngOnDestroy() { this.app.destroy(true); if (this.frameSub) this.frameSub.unsubscribe(); if (this.frameDataSub) this.frameDataSub.unsubscribe(); } forward() { //todo: use this.topLevelFrames // console.log('this.viewState', this.viewState); for (const frame of this.profiler.parser.rootItems) { if (this.selectedFrame && frame.x <= this.selectedFrame.x) continue; if (frame.x > this.viewState.scrollX) { this.viewState.scrollX = frame.x - this.parser.offsetX; this.profiler.viewChanged(); this.profiler.setSelected(frame); this.profiler.update(); return; } } // this.profiler.forward(); } @HostListener('window:resize') onResize() { if (!this.canvas) return; this.app.renderer.resize(this.canvas.nativeElement.clientWidth, this.canvas.nativeElement.clientHeight); this.viewState.width = this.canvas.nativeElement.clientWidth; this.viewState.height = this.canvas.nativeElement.clientHeight; this.profiler.update(); } async ngAfterViewInit() { this.createCanvas(); await this.loadFrames(); this.cd.detectChanges(); } async ngOnInit() { } async resetProfilerFrames() { this.parser.reset(); this.frameData = []; await this.client.debug.resetProfilerFrames(); } protected async loadFrames() { console.time('download'); const trackFrames = ClientProgress.track(); const [framesBuffer, dataBuffer] = await this.client.debug.getProfilerFrames(); console.timeEnd('download'); console.time('parse'); const frames = decodeFrames(framesBuffer); this.frameData = decodeFrameData(dataBuffer); console.timeEnd('parse'); // console.log('this.frames', frames); // console.log('this.frameData', this.frameData); console.time('addFrames'); this.profiler.addFrames(frames); console.timeEnd('addFrames'); this.profiler.update(); const frameSub = this.frameSub = await this.client.debug.subscribeStopwatchFrames(); frameSub.subscribe((next) => { this.profiler.addFrames(decodeFrames(next)); this.profiler.update(); }); const frameDataSub = this.frameDataSub = await this.client.debug.subscribeStopwatchFramesData(); frameDataSub.subscribe((next) => { const item = this.selectedFrame; for (const data of decodeFrameData(next)) { this.frameData.push(data); if (item && data.id === item.frame.id && data.worker === item.frame.worker) { Object.assign(this.selectedFrameData, data.data); } } this.cd.detectChanges(); }); } protected createCanvas() { // The application will create a canvas element for you that you // can then insert into the DOM. if (!this.canvas) return; this.canvas.nativeElement.appendChild(this.app.view); this.app.renderer.view.style.position = 'absolute'; this.app.renderer.view.style.display = 'block'; this.app.renderer.view.style.width = '100%'; this.app.renderer.view.style.height = '100%'; this.app.renderer.resize(this.canvas.nativeElement.clientWidth, this.canvas.nativeElement.clientHeight); this.viewState.width = this.canvas.nativeElement.clientWidth; this.viewState.height = this.canvas.nativeElement.clientHeight; this.app.stage.addChild(this.profiler); const mc = new Hammer.Manager(this.app.renderer.view); mc.add(new Hammer.Pan({ direction: Hammer.DIRECTION_ALL, threshold: 0 })); let offsetXStart = 0; mc.on('panstart', () => { offsetXStart = this.viewState.scrollX; this.profiler.ignoreNextClick = true; }); mc.on('panend', () => { offsetXStart = this.viewState.scrollX; }); mc.on('pan', (ev) => { if (ev.deltaX === 0) return; this.viewState.scrollX = offsetXStart - (ev.deltaX * this.viewState.zoom); this.profiler.viewChanged(); }); this.app.renderer.view.addEventListener('wheel', (event) => { const newZoom = Math.min(1000000, Math.max(0.1, this.viewState.zoom - (Math.min(event.deltaY * -1 / 500, 0.3) * this.viewState.zoom))); const ratio = newZoom / this.viewState.zoom; const eventOffsetX = event.clientX - this.app.renderer.view.getBoundingClientRect().x; this.viewState.scrollX -= (eventOffsetX) * this.viewState.zoom * (ratio - 1); this.viewState.zoom = newZoom; event.preventDefault(); this.profiler.viewChanged(); }); } }
the_stack
import api from '@/api'; import { CAT_TYPE, COLLECT_TYPE, CREATE_MODEL_TYPE, DATA_SOURCE_ENUM, ID_COLLECTIONS, KAFKA_DATA_TYPE, QOS_TYPE, READ_MODE_TYPE, RESTFUL_METHOD, RESTFUL_PROPTOCOL, RESTFUL_RESP_MODE, SLOAR_CONFIG_TYPE, SOURCE_TIME_TYPE, SYNC_TYPE, TASK_TYPE_ENUM, } from '@/constant'; import { isKafka, isHaveTableColumn } from '@/utils/is'; import molecule from '@dtinsight/molecule'; import { cloneDeep, isEmpty } from 'lodash'; export const UnlimitedSpeed = '不限制上传速率'; // 校验字段信息 export function checkColumnsData(rule: any, value: any, callback: any, source: any) { if (isHaveTableColumn(source?.type)) { if (isEmpty(value) || value?.some((item: any) => isEmpty(item))) { let err = '请填写字段信息'; return callback(err); } if ( value?.some( (item: { type: string }) => item.type?.toLowerCase() === 'Not Support'.toLowerCase(), ) ) { let err = '字段中存在不支持的类型,请重新填写'; return callback(err); } } callback(); } export interface SettingMap { speed?: number | string; readerChannel?: number; writerChannel?: number; isSaveDirty?: boolean; sourceId?: number; tableName?: string; lifeDay?: number; } export const streamTaskActions = { initState: { // 实时任务初始化数据 currentStep: null, sourceMap: { type: undefined, port: undefined, table: [], sourceId: undefined, collectType: COLLECT_TYPE.ALL, cat: [CAT_TYPE.INSERT, CAT_TYPE.UPDATE, CAT_TYPE.DELETE], pavingData: false, rdbmsDaType: SYNC_TYPE.BINLOG, startSCN: undefined, codec: 'plain', qos: QOS_TYPE.EXACTLY_ONCE, isCleanSession: true, parse: 'text', decoder: READ_MODE_TYPE.LENGTH, codecType: 'text', collectPoint: 'taskRun', requestMode: RESTFUL_METHOD[1].value, decode: RESTFUL_RESP_MODE[0].value, protocol: RESTFUL_PROPTOCOL[0].value, startLocation: undefined, temporary: false, slotConfig: Number(Object.keys(SLOAR_CONFIG_TYPE)[0]), mode: 'group-offsets', }, targetMap: { sourceId: undefined, topic: undefined, isCleanSession: true, qos: QOS_TYPE.EXACTLY_ONCE, }, settingMap: { // 通道控制 speed: -1, readerChannel: '1', writerChannel: 1, }, }, /** * 获取当前任务数据 * @returns */ getCurrentPage() { const state = molecule.editor.getState(); return cloneDeep(state.current?.tab?.data); }, /** * 更新当前任务数据 * @param key 字段名 * @param value 对应字段值 * @param isDirty 是否有修改任务 */ setCurrentPageValue(key: any, value: any, isDirty?: any) { const page = this.getCurrentPage(); const state = molecule.editor.getState(); const tab: any = state.current?.tab || {}; page[key] = value; if (typeof isDirty == 'boolean') { page.notSynced = isDirty; } tab['data'] = page; molecule.editor.updateTab(tab); }, setCurrentPage(data: any) { const state = molecule.editor.getState(); const tab: any = state.current?.tab || {}; tab['data'] = data; molecule.editor.updateTab(tab); }, updateCurrentPage(data: any) { let page = this.getCurrentPage(); page = Object.assign({}, page, data); this.setCurrentPage(page); }, navtoStep(step: number) { this.setCurrentPageValue('currentStep', step); }, exchangeDistributeTable(distributeTable: any) { if (!distributeTable) { return []; } const KeyAndValue = Object.entries(distributeTable); return KeyAndValue.map(([name, tables]) => { return { name, tables, isSaved: true, }; }); }, initCurrentPage() { const page = cloneDeep(this.getCurrentPage()); this.setCurrentPage({ ...page, ...this.initState }); }, /** * 获取实时采集task初始化信息 * @param {Int} taskId */ initCollectionTask(taskId: any) { const page = this.getCurrentPage(); /** * 假如已经存在这个属性,则说明当前的task不是第一次打开,所以采用原来的数据 */ if (typeof page.currentStep != 'undefined') { return; } if (page.submitted) { this.setCurrentPageValue('isEdit', true); } const { sourceMap, targetMap } = page; if (!isEmpty(sourceMap) || !isEmpty(targetMap)) { sourceMap.pavingData = !!sourceMap.pavingData; sourceMap.multipleTable = sourceMap.multipleTable || false; if (sourceMap.journalName || sourceMap.startSCN) { sourceMap.collectType = COLLECT_TYPE.FILE; } else if (sourceMap.timestamp) { sourceMap.collectType = COLLECT_TYPE.TIME; } else if (sourceMap.lsn) { sourceMap.collectType = COLLECT_TYPE.LSN; } else { sourceMap.collectType = COLLECT_TYPE.ALL; } if (sourceMap.distributeTable) { sourceMap.distributeTable = this.exchangeDistributeTable(sourceMap.distributeTable); sourceMap.multipleTable = true; } /** * 针对 kafka 的 codec, timestamp 做处理 */ if (isKafka(sourceMap.type)) { sourceMap.collectType = undefined; sourceMap.codec = sourceMap.codec || KAFKA_DATA_TYPE.TYPE_COLLECT_JSON; } if ( [ DATA_SOURCE_ENUM.KAFKA, DATA_SOURCE_ENUM.KAFKA_2X, DATA_SOURCE_ENUM.TBDS_KAFKA, DATA_SOURCE_ENUM.KAFKA_HUAWEI, ].includes(targetMap.type) ) { targetMap.dataSequence = targetMap.dataSequence || false; } this.updateSourceMap(page.sourceMap, false, true); this.updateTargetMap(page.targetMap, false, true); this.updateChannelControlMap(page.setting, false, true); this.setCurrentPageValue('currentStep', 3); } else { this.initCurrentPage(); this.setCurrentPageValue('currentStep', 0); } }, updateSourceMap(params: any = {}, clear: any = false, notDirty: any = false) { const page = this.getCurrentPage(); let sourceMap = page?.sourceMap || {}; if (clear) { sourceMap = { ...this.initState.sourceMap, type: sourceMap?.type, sourceId: sourceMap?.sourceId, rdbmsDaType: sourceMap?.rdbmsDaType, multipleTable: false, pavingData: sourceMap?.type == DATA_SOURCE_ENUM.POSTGRESQL, codec: isKafka(sourceMap?.type) ? KAFKA_DATA_TYPE.TYPE_COLLECT_JSON : 'plain', }; this.setCurrentPageValue('targetMap', cloneDeep(this.initState.targetMap)); } if (params.distributeTable) { let tables = params.distributeTable.reduce((prevValue: any, item: any) => { return prevValue.concat(item.tables); }, []); params.table = tables; } this.setCurrentPageValue( 'sourceMap', cloneDeep({ ...sourceMap, ...params, }), !notDirty, ); }, updateTargetMap(params = {}, clear: any, notDirty: boolean = false) { const page = this.getCurrentPage(); let targetMap = page?.targetMap || {}; if (clear) { targetMap = this.initState.targetMap; } this.setCurrentPageValue( 'targetMap', cloneDeep({ ...targetMap, ...params, }), notDirty ? undefined : true, ); }, updateChannelControlMap( params: SettingMap = {}, clear: any = false, notDirty: boolean = false, ) { const page = this.getCurrentPage(); let settingMap = page?.settingMap || {}; if (clear) { settingMap = this.initState.settingMap; } if (params.isSaveDirty == false) { params.sourceId = undefined; params.tableName = undefined; params.lifeDay = undefined; } else if (params.isSaveDirty) { params.lifeDay = 90; } if (params.speed === UnlimitedSpeed) params.speed = -1; this.setCurrentPageValue( 'settingMap', cloneDeep({ ...settingMap, ...params, }), !notDirty, ); }, }; // 对多资源附加资源 resourceTree 的处理 // 初始时,在基础上拼接没请求到的 additionalResourceList export function joinAdditionTree(tree: any, addtionalTree: any[], resourceTree?: any[]) { const sourceTree = resourceTree ? [...addtionalTree, ...resourceTree] : addtionalTree; for (let i = 0; i < tree.length; i++) { const nodeTree = tree[i]; const children = (nodeTree.children = nodeTree.children || []); if (!(nodeTree.type === 'folder')) { break; } if (!nodeTree.children) { nodeTree.children = []; } if (children.length > 0) { joinAdditionTree(children, addtionalTree, resourceTree); } const childrenList = sourceTree.filter((item: any) => item.nodePid === nodeTree?.id); if (childrenList.length > 0) { childrenList.forEach((child: any) => { if (!children.map((item: any) => item.id).includes(child.id)) { const nodeChild = formatTreeChild(nodeTree, child); children.push(nodeChild); } }); } } return tree; } // 对 node 参数稍作处理 function formatTreeChild(parent: any, child: any) { const result = { ...child, parentId: child.nodePid, name: child.resourceName, level: parent.level + 1, type: 'file', catalogueType: null, readWriteLockVO: null, children: null, taskType: null, createUser: child.createUser || '', }; return result; } // 遍历树形节点,用新节点替换老节点 export function replaceTreeNode(treeNode: any, replace: any) { if (treeNode.id === parseInt(replace.id, 10) && treeNode.type == replace.type) { // 多级目录的情况处理 const replaceChildren = replace.children || []; const regionChildren = treeNode.children || []; replaceChildren.forEach((child: any) => { const sameChild = regionChildren.find((item: any) => item.id === child.id); if (sameChild && sameChild.children && sameChild.children.length && !child.children) { child.children = sameChild.children; } }); treeNode = Object.assign(treeNode, replace); return; } if (treeNode.children) { const children = treeNode.children; for (let i = 0; i < children.length; i += 1) { replaceTreeNode(children[i], replace); } } } interface Task { componentVersion: string; source: { offset: number; offsetUnit: string; timeType: number; timeTypeArr: number[]; procTime: string; }[]; } /** * 切换 flink 版本时,源表的时间特征会在 timeType 和 timeTypeArr 两个字段切换 * flink1.12 时 timeTypeArr 字段只在前端使用 * @param oldTask - 用于比较 componentVersion 是否变化 * @param newTask - 用于接口传参的 task,会改变 newTask 本身! */ export function transformTimeType(oldTask: Task, newTask: Task) { // 切换为 1.12 时,根据 timeType 修改 timeTypeArr if (oldTask.componentVersion !== '1.12' && newTask.componentVersion === '1.12') { for (const form of newTask?.source || []) { form.timeTypeArr = form.timeType === SOURCE_TIME_TYPE.EVENT_TIME ? [1, 2] : [SOURCE_TIME_TYPE.PROC_TIME]; // timeType 勾选 procTime 时,带上默认名称 form.procTime = 'proc_time'; } } // 1.12 切换为其他版本时,根据 timeTypeArr 修改 timeType if (oldTask.componentVersion === '1.12' && newTask.componentVersion !== '1.12') { for (const form of newTask?.source || []) { form.timeType = form.timeTypeArr?.includes(SOURCE_TIME_TYPE.EVENT_TIME) ? SOURCE_TIME_TYPE.EVENT_TIME : SOURCE_TIME_TYPE.PROC_TIME; } } } /** * 切换 flink 版本时,源表的 offset 的时间单位需要进行转化 * @param oldTask - 用于比较 componentVersion 是否变化 * @param newTask - 用于接口传参的 task,会改变 newTask 本身! */ export function transformOffsetUnit(oldTask: Task, newTask: Task) { // 切换为 1.12 时,时间单位由 ms 变为 s if (oldTask.componentVersion !== '1.12' && newTask.componentVersion === '1.12') { for (const form of newTask?.source || []) { form.offset = form.offset / 1000; form.offsetUnit = 'SECOND'; } } // 1.12 切换为其他版本时,单位转化为 ms if (oldTask.componentVersion === '1.12' && newTask.componentVersion !== '1.12') { // 各单位转换为秒 const unit: any = { SECOND: 1, MINUTE: 60, HOUR: 3600, DAY: 86400, MONTH: 86400 * 30, YEAR: 86400 * 365, }; for (const form of newTask?.source || []) { form.offset = unit[form.offsetUnit] * form.offset * 1000; // flink 版本不是 1.12 也不会读取这个字段,不改也行 form.offsetUnit = 'ms'; } } }
the_stack
import { getStoreKey, pluginName, getStorageSecretUrl, getOperationManifestUrl, } from './common'; import loglevel from 'loglevel'; import fetcher from 'make-fetch-happen'; import { HttpRequestCache } from './cache'; import type { InMemoryLRUCache } from 'apollo-server-caching'; import type { OperationManifest } from './ApolloServerPluginOperationRegistry'; import type { Logger, ApolloConfig, WithRequired } from 'apollo-server-types'; import type { Response, RequestInit, fetch } from 'apollo-server-env'; const DEFAULT_POLL_SECONDS: number = 30; const SYNC_WARN_TIME_SECONDS: number = 60; export interface AgentOptions { logger?: Logger; fetcher?: typeof fetch; pollSeconds?: number; apollo: WithRequired<ApolloConfig, 'keyHash' | 'graphRef'>; store: InMemoryLRUCache; } type SignatureStore = Set<string>; const callToAction = `Ensure this server's schema has been published with 'apollo service:push' and that operations have been registered with 'apollo client:push'.`; export default class Agent { private fetcher: typeof fetch; private timer?: NodeJS.Timer; private logger: Logger; private requestInFlight: Promise<any> | null = null; private lastSuccessfulCheck?: Date; private storageSecret?: string; // Only exposed for testing. public _timesChecked: number = 0; private lastOperationSignatures: SignatureStore = new Set(); private readonly options: AgentOptions = Object.create(null); // We've made most of our protocols capable of just taking a graph ref, // meaning that we can later iterate on the semantics of graph refs without // needing to make changes to Apollo Server. But not the operation registry! // We really need to know the pieces separately. *sigh* private readonly graphId: string; readonly graphVariant: string; constructor(options: AgentOptions) { Object.assign(this.options, options); const { graphRef } = this.options.apollo; const at = graphRef.indexOf('@'); if (at === -1) { this.graphId = graphRef; this.graphVariant = 'current'; } else { this.graphId = graphRef.substring(0, at); this.graphVariant = graphRef.substring(at + 1); } this.logger = this.options.logger || loglevel.getLogger(pluginName); this.fetcher = this.options.fetcher || getDefaultGcsFetcher(); } async requestPending() { return this.requestInFlight; } private pollSeconds() { return this.options.pollSeconds || DEFAULT_POLL_SECONDS; } async start() { this.logger.debug('Starting operation registry agent...'); // This is what we'll trigger at a regular interval. const pulse = async () => await this.checkForUpdate(); // The first pulse should happen before we start the timer. try { await pulse(); } catch (err) { console.error( 'The operation manifest could not be fetched. Retries will continue, but requests will be forbidden until the manifest is fetched.', (err as Error).message || err, ); } // Afterward, keep the pulse going. this.timer = this.timer || setInterval(function () { // Errors in the interval indicate that the manifest might have failed // to update, but we've still got the seed update so we will continue // serving based on the previous manifest until we gain sync again. // These errors will be logged, but not crash the server. pulse().catch((err) => console.error(err.message || err)); }, this.pollSeconds() * 1000); // Prevent the Node.js event loop from remaining active (and preventing, // e.g. process shutdown) by calling `unref` on the `Timeout`. For more // information, see https://nodejs.org/api/timers.html#timers_timeout_unref. this.timer.unref(); } public stop() { if (this.timer) { clearInterval(this.timer); } } private timeSinceLastSuccessfulCheck() { if (!this.lastSuccessfulCheck) { // So far back that it's never? return -Infinity; } return new Date().getTime() - this.lastSuccessfulCheck.getTime(); } private warnWhenLossOfSync() { // This is probably good information to reveal in general, though nice // to have in development. if (this.timeSinceLastSuccessfulCheck() > SYNC_WARN_TIME_SECONDS * 1000) { console.warn( `WARNING: More than ${SYNC_WARN_TIME_SECONDS} seconds has elapsed since a successful fetch of the manifest. (Last success: ${this.lastSuccessfulCheck})`, ); } } private async fetchAndUpdateStorageSecret(): Promise<string | undefined> { const storageSecretUrl = getStorageSecretUrl( this.graphId, this.options.apollo.keyHash, ); const response = await this.fetcher(storageSecretUrl, this.fetchOptions); if (response.status === 304) { this.logger.debug( 'The storage secret was the same as the previous attempt.', ); return this.storageSecret; } if (!response.ok) { const responseText = await response.text(); this.logger.debug(`Could not fetch storage secret ${responseText}`); return; } this.storageSecret = await response.json(); return this.storageSecret; } private fetchOptions: RequestInit = { // More than three times our polling interval should be long enough to wait. timeout: this.pollSeconds() * 3 /* times */ * 1000 /* ms */, }; private async fetchManifest(): Promise<Response> { this.logger.debug(`Checking for storageSecret`); const storageSecret = await this.fetchAndUpdateStorageSecret(); if (!storageSecret) { throw new Error('No storage secret found'); } const storageSecretManifestUrl = getOperationManifestUrl( this.graphId, storageSecret, this.graphVariant, ); this.logger.debug( `Checking for manifest changes at ${storageSecretManifestUrl}`, ); const response = await this.fetcher( storageSecretManifestUrl, this.fetchOptions, ); if (response.status === 404 || response.status === 403) { throw new Error( `No manifest found for tag "${this.graphVariant}" at ` + `${storageSecretManifestUrl}. ${callToAction}`, ); } return response; } private async tryUpdate(): Promise<boolean> { this._timesChecked++; let response: Response; try { response = await this.fetchManifest(); // When the response indicates that the resource hasn't changed, there's // no need to do any other work. Returning false is meant to indicate // that there wasn't an update, but there was a successful fetch. if (response.status === 304) { return false; } if (!response.ok) { const responseText = await response.text(); // The response error code only comes in XML, but we don't have an XML // parser handy, so we'll just match the string. if (responseText.includes('<Code>AccessDenied</Code>')) { throw new Error(`No manifest found. ${callToAction}`); } // For other unknown errors. throw new Error(`Unexpected status: ${responseText}`); } const contentType = response.headers.get('content-type'); if (contentType && contentType !== 'application/json') { throw new Error(`Unexpected 'Content-Type' header: ${contentType}`); } } catch (err) { const ourErrorPrefix = `Unable to fetch operation manifest for graph ID '${this.graphId}': ${err}`; (err as Error).message = `${ourErrorPrefix}: ${err}`; throw err; } await this.updateManifest(await response.json()); // True is good! return true; } public async checkForUpdate() { // Display a warning message if things have fallen abnormally behind. this.warnWhenLossOfSync(); // Don't check again if we're already in-flight. if (this.requestInFlight) { return this.requestInFlight; } // Prevent other requests from crossing paths. this.requestInFlight = this.tryUpdate(); const resetRequestInFlight = () => (this.requestInFlight = null); return this.requestInFlight .then((result) => { // Mark this for reporting and monitoring reasons. this.lastSuccessfulCheck = new Date(); resetRequestInFlight(); return result; }) .catch((err) => { // We don't want to handle any errors, but we do want to erase the // current Promise reference. resetRequestInFlight(); throw err; }); } public async updateManifest(manifest: OperationManifest) { if ( !manifest || manifest.version !== 2 || !Array.isArray(manifest.operations) ) { throw new Error('Invalid manifest format.'); } const incomingOperations: Map<string, string> = new Map(); const replacementSignatures: SignatureStore = new Set(); for (const { signature, document } of manifest.operations) { incomingOperations.set(signature, document); // Keep track of each operation in this manifest so we can store it // for comparison after the next fetch. replacementSignatures.add(signature); // If it it's _not_ in the last fetch, we know it's added. We could // just set it — which would be less costly, but it's nice to have this // for debugging. if (!this.lastOperationSignatures.has(signature)) { // Newly added operation. this.logger.debug(`Incoming manifest ADDs: ${signature}`); this.options.store.set(getStoreKey(signature), document); } } // Explicitly purge items which have been removed since our last // successful fetch of the manifest. for (const signature of this.lastOperationSignatures) { if (!incomingOperations.has(signature)) { // Remove operations which are no longer present. this.logger.debug(`Incoming manifest REMOVEs: ${signature}`); this.options.store.delete(getStoreKey(signature)); } } // Save the ones from this fetch, so we know what to remove on the next // actual update. Particularly important since a future distributed // store might not actually let us look this up again. this.lastOperationSignatures = replacementSignatures; } } const GCS_RETRY_COUNT = 5; function getDefaultGcsFetcher() { return fetcher.defaults({ cacheManager: new HttpRequestCache(), // All headers should be lower-cased here, as `make-fetch-happen` // treats differently cased headers as unique (unlike the `Headers` object). // @see: https://git.io/JvRUa headers: { 'user-agent': [ require('../package.json').name, require('../package.json').version, ].join('/'), }, retry: { retries: GCS_RETRY_COUNT, // The default factor: expected attempts at 0, 1, 3, 7, 15, and 31 seconds elapsed factor: 2, // 1 second minTimeout: 1000, randomize: true, }, }); }
the_stack
import * as angular from 'angular'; import { CalloutType } from './calloutTypeEnum'; import { CalloutArrow } from './calloutArrowEnum'; /** * @ngdoc class * @name CalloutController * @module officeuifabric.components.callout * * @restrict E * * @description * CalloutController is the controller for the <uif-callout> directive * */ export class CalloutController { public static $inject: string[] = ['$scope', '$log']; constructor(public $scope: ICalloutScope, public $log: angular.ILogService) { } } /** * @ngdoc directive * @name uifCalloutHeader * @module officeuifabric.components.callout * * @restrict E * * @description * `<uif-callout-header>` is an directive for rendering callout header * * @usage * * <uif-callout> * <uif-callout-header>All of your favorite people</uif-callout-header> * </uif-callout> */ export class CalloutHeaderDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = false; public scope: boolean = false; public template: string = '<div class="ms-Callout-header"><p class="ms-Callout-title" ng-transclude></p></div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new CalloutHeaderDirective(); return directive; } public link(scope: any, instanceElement: angular.IAugmentedJQuery, attrs: any, ctrls: any[]): void { let mainWrapper: JQuery = instanceElement.parent().parent(); if (!angular.isUndefined(mainWrapper) && mainWrapper.hasClass('ms-Callout-main')) { let detachedHeader: JQuery = instanceElement.detach(); mainWrapper.prepend(detachedHeader); } } } /** * @ngdoc directive * @name uifCalloutContent * @module officeuifabric.components.callout * * @restrict E * * @description * `<uif-callout-content>` is an directive for rendering callout content * * @usage * * <uif-callout> * <uif-callout-content>Consider adding a link to learn more at the bottom.</uif-callout-content> * </uif-callout> */ export class CalloutContentDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = false; public scope: boolean = false; public template: string = '<div class="ms-Callout-content"><p class="ms-Callout-subText" ng-transclude></p></div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new CalloutContentDirective(); return directive; } } /** * @ngdoc directive * @name uifCalloutActions * @module officeuifabric.components.callout * * @restrict E * * @description * `<uif-callout-actions>` is an directive for rendering callout actions * * @usage * * <uif-callout> * <uif-callout-actions> * <a href="#" class="ms-Callout-link ms-Link ms-Link--hero">Learn more</a> * </uif-callout-actions> * </uif-callout> */ export class CalloutActionsDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = false; public scope: boolean = false; public template: string = '<div class="ms-Callout-actions" ng-transclude></div>'; public require: string = '^?uifCallout'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new CalloutActionsDirective(); return directive; } public link(scope: ICalloutScope, instanceElement: angular.IAugmentedJQuery, attrs: any, calloutController: CalloutController): void { if (angular.isObject(calloutController)) { calloutController.$scope.$watch('hasSeparator', (hasSeparator: boolean) => { if (hasSeparator) { let actionChildren: JQuery = instanceElement.children().eq(0).children(); for (let buttonIndex: number = 0; buttonIndex < actionChildren.length; buttonIndex++) { let action: JQuery = actionChildren.eq(buttonIndex); // handle CSS on button action.addClass('ms-Callout-action'); // take care of span inside buttons let actionSpans: JQuery = action.find('span'); // add only to spans that are either button label or icon for (let spanIndex: number = 0; spanIndex < actionSpans.length; spanIndex++) { let actionSpan: JQuery = actionSpans.eq(spanIndex); if (actionSpan.hasClass('ms-Button-label') || actionSpan.hasClass('ms-Button-icon')) { actionSpan.addClass('ms-Callout-actionText'); } } } } }); } } } /** * @ngdoc interface * @name ICalloutAttributes * @module officeuifabric.components.callout * * @description * Those are the attributes that can be used on callout directive. * * * @property {string} uifSeparator - Renders a separating line between content and actions * @property {string} uifActiontext - Render a separating line between content and actions. Same as `uifSeparator` * @property {CalloutArrow} uifArrow - Direction of the arrow * @property {boolean} uifClose - Renders close button */ interface ICalloutAttributes extends angular.IAttributes { uifSeparator: string; uifActionText: string; uifArrow: string; uifClose: boolean; } /** * @ngdoc interface * @name ICalloutScope * @module officeuifabric.components.callout * * @description * This is the scope used by the directive. * * @property {CalloutType} uifType - Type of callout to render * @property {boolean} ngShow - Callout visible or not. */ interface ICalloutScope extends angular.IScope { arrowDirection: string; hasSeparator: boolean; uifType: string; ngShow: boolean; closeButton: boolean; isMouseOver: boolean; closeButtonClicked: boolean; getCalloutClasses: () => string; } /** * @ngdoc directive * @name uifCallout * @module officeuifabric.components.callout * * @restrict E * * @description * `<uif-callout>` is an directive for rendering callout component. * @see https://github.com/OfficeDev/Office-UI-Fabric/tree/master/src/components/Callout * * @usage * * <uif-callout> * <uif-callout-content>Consider adding a link to learn more at the bottom.</uif-callout-content> * </uif-callout> */ export class CalloutDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = false; public template: string = '<div class="ms-Callout" ' + 'ng-class="getCalloutClasses()"> ' + '<div class="ms-Callout-main"><div class="ms-Callout-inner" ng-transclude></div></div></div>'; public require: string[] = ['uifCallout']; public scope: any = { ngShow: '=?', uifType: '@' }; public controller: typeof CalloutController = CalloutController; // mapping CSS classes for arrow types private uifArrowClasses: { [index: number]: string } = { [CalloutArrow.bottom] : 'ms-Callout--arrowBottom', [CalloutArrow.left] : 'ms-Callout--arrowLeft', [CalloutArrow.right] : 'ms-Callout--arrowRight', [CalloutArrow.top] : 'ms-Callout--arrowTop' }; // mapping CSS classes for type private uifTypeClasses: {[index: number]: string} = { [CalloutType.oobe] : 'ms-Callout--OOBE', [CalloutType.peek] : 'ms-Callout--Peek' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new CalloutDirective(); return directive; } public link(scope: ICalloutScope, instanceElement: angular.IAugmentedJQuery, attrs: ICalloutAttributes, ctrls: any[]): void { let calloutController: CalloutController = ctrls[0]; attrs.$observe('uifType', (calloutType: string) => { if (angular.isUndefined(CalloutType[calloutType])) { calloutController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.callout - "' + calloutType + '" is not a valid value for uifType. It should be oobe or peek'); } }); attrs.$observe('uifArrow', (attrArrowDirection: string) => { if (angular.isDefined(attrArrowDirection) && angular.isUndefined(CalloutArrow[attrArrowDirection])) { calloutController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.callout - "' + attrArrowDirection + '" is not a valid value for uifArrow. It should be left, right, top, bottom.'); return; } scope.arrowDirection = attrArrowDirection; }); scope.hasSeparator = (!angular.isUndefined(attrs.uifActionText) || !angular.isUndefined(attrs.uifSeparator)); if (!angular.isUndefined(attrs.uifClose)) { scope.closeButton = true; let closeButtonElement: angular.IAugmentedJQuery = angular.element( '<button class="ms-Callout-close" type="button">' + '<i class="ms-Icon ms-Icon--x"></i>' + '</button>'); let calloutDiv: JQuery = instanceElement.find('div').eq(0); calloutDiv.append(closeButtonElement); // register close button click closeButtonElement.bind('click', (eventObject: JQueryEventObject) => { scope.ngShow = false; scope.closeButtonClicked = true; scope.$apply(); }); } instanceElement.bind('mouseenter', (eventObject: JQueryEventObject) => { scope.isMouseOver = true; scope.$apply(); }); instanceElement.bind('mouseleave', (eventObject: JQueryEventObject) => { scope.isMouseOver = false; scope.$apply(); }); scope.$watch('ngShow', (newValue: boolean, oldValue: boolean) => { // close button closes everytime let isClosingByButtonClick: boolean = !newValue && scope.closeButtonClicked; if (isClosingByButtonClick) { scope.ngShow = scope.closeButtonClicked = false; return; } if (!newValue && angular.isUndefined(attrs.uifClose)) { // callout visible on mouse over scope.ngShow = scope.isMouseOver; } else { // callout visiblity controlled by ng-show scope.ngShow = newValue; } }); scope.$watch('isMouseOver', (newVal: boolean, oldVal: boolean) => { // mouse was over element and now it's out if (!newVal && oldVal) { // when there's button, only button can close. if (!scope.closeButton) { scope.ngShow = false; } } }); scope.getCalloutClasses = () => { let calloutClasses: string[] = []; let calloutType: number = CalloutType[scope.uifType]; let calloutArrow: number = angular.isDefined(scope.arrowDirection) ? CalloutArrow[scope.arrowDirection] : undefined; if (angular.isDefined(calloutType)) { calloutClasses.push(this.uifTypeClasses[calloutType]); } if (angular.isDefined(calloutArrow)) { calloutClasses.push(this.uifArrowClasses[calloutArrow]); } if (scope.closeButton) { calloutClasses.push('ms-Callout--close'); } if (scope.hasSeparator) { calloutClasses.push('ms-Callout--actionText'); } return calloutClasses.join(' '); }; } } /** * @ngdoc module * @name officeuifabric.components.callout * * @description * Callout * */ export let module: angular.IModule = angular.module('officeuifabric.components.callout', ['officeuifabric.components']) .directive('uifCallout', CalloutDirective.factory()) .directive('uifCalloutHeader', CalloutHeaderDirective.factory()) .directive('uifCalloutContent', CalloutContentDirective.factory()) .directive('uifCalloutActions', CalloutActionsDirective.factory());
the_stack
import { Assert, AITestClass } from "@microsoft/ai-test-framework"; import { ITestContext, StepResult } from "@microsoft/ai-test-framework/dist-esm/src/TestCase"; import { _InternalMessageId, LoggingSeverity } from "../../../src/JavaScriptSDK.Enums/LoggingEnums"; import { _InternalLogMessage, DiagnosticLogger } from "../../../src/JavaScriptSDK/DiagnosticLogger"; import { isObject, objForEachKey, objKeys, optimizeObject, setValue } from "../../../src/JavaScriptSDK/HelperFuncs"; interface PerfMeasurements { duration: number; iteration: number; avgIteration: number; avgDuration: number; maxDuration: number; total: number; attempts: number; deviation: number; }; export class CorePerfCheckTests extends AITestClass { public testInitialize() { super.testInitialize(); } public testCleanup() { super.testCleanup(); } public registerTests() { this.testCase({ name: "PerfChecks: isObject", test: () => { let testObject = { test: "Value" }; let iterations = 500000; let checks = 0; let duration = this._runPerfTest("isObject", () => { if (isObject(testObject)) { checks++; } }, 10, iterations, 0.00001); Assert.equal(iterations * duration.attempts, checks, "Make sure we hit all of them"); } }); /** * This test always currently fails on chromium based browsers due to the way that chromium provides super * fast internal private classes for fixed objects and using the optimizeObject() creates a non-optimized * dynamic class -- so commenting out for future validation and local runs on Firefox */ // this.testCase({ // name: "PerfChecks: objForEachKey fixed large object", // test: () => { // let iterations = 100000; // let baseTestObject = { // "test.value0": "Test Value 0", // "test.value1": "Test Value 1", // "test.value2": "Test Value 2", // "test.value3": "Test Value 3", // "test.value4": "Test Value 4", // "test.value5": "Test Value 5", // "test.value6": "Test Value 6", // "test.value7": "Test Value 7", // "test.value8": "Test Value 8", // "test.value9": "Test Value 9", // "test.value10": "Test Value 10", // "test.value11": "Test Value 11", // "test.value12": "Test Value 12", // "test.value13": "Test Value 13", // "test.value14": "Test Value 14", // "test.value15": "Test Value 15", // "test.value16": "Test Value 16", // "test.value17": "Test Value 17", // "test.value18": "Test Value 18", // "test.value19": "Test Value 19", // "test.value20": "Test Value 20", // "test.value21": "Test Value 21", // "test.value22": "Test Value 22", // "test.value23": "Test Value 23", // "test.value24": "Test Value 24", // "test.value25": "Test Value 25", // "test.value26": "Test Value 26", // "test.value27": "Test Value 27", // "test.value28": "Test Value 28", // "test.value29": "Test Value 29", // "test.value30": "Test Value 30", // "test.value31": "Test Value 31", // "test.value32": "Test Value 32", // "test.value33": "Test Value 33", // "test.value34": "Test Value 34", // "test.value35": "Test Value 35", // "test.value36": "Test Value 36", // "test.value37": "Test Value 37", // "test.value38": "Test Value 38", // "test.value39": "Test Value 39" // } as any; // let objectFields = Object["keys"](baseTestObject).length; // // JIT Optimization if we know we are playing with a dynamic object // let optTestObject = optimizeObject(baseTestObject); // let testObject6 = Object["assign"]({}, baseTestObject); // testObject6["_dummy"] = 0; // testObject6 = Object["assign"]({}, testObject6); // delete testObject6["_dummy"]; // let adjOptTestObject = optimizeObject(testObject6); // let checks = 0; // let baseDuration = this._runPerfTest("baseTestObject", () => { // objForEachKey(baseTestObject, (name, value) => { // checks++; // }); // }, 200, iterations, 0.003, 20); // Assert.equal(iterations * objectFields * baseDuration.attempts, checks, "Make sure we hit all of them"); // checks = 0; // let optDuration1 = this._runPerfTest("optTestObject", () => { // objForEachKey(optTestObject, (name, value) => { // checks++; // }); // }, 300, iterations, 0.003, 20); // Assert.equal(iterations * objectFields * optDuration1.attempts, checks, "Make sure we hit all of them"); // this._checkRun(baseDuration, optDuration1); // checks = 0; // let optDuration2 = this._runPerfTest("adjOptTestObject", () => { // objForEachKey(adjOptTestObject, (name, value) => { // checks++; // }); // }, 300, iterations, 0.003, 20); // Assert.equal(iterations * objectFields * optDuration2.attempts, checks, "Make sure we hit all of them"); // this._checkRun(baseDuration, optDuration2); // } // }); this.testCase({ name: "PerfChecks: objForEachKey dynamic large (40 fields) object", timeout: 60000, test: () => { let iterations = 100000; let baseTestObject = { }; for (let lp = 0; lp < 40; lp++) { baseTestObject["test.value" + lp] = "Test Value " + lp; } let objectFields = Object["keys"](baseTestObject).length; // JIT Optimization if we know we are playing with a dynamic object let optTestObject = optimizeObject(baseTestObject); let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { objForEachKey(baseTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.003).then((baseDuration) => { Assert.equal(iterations * objectFields * baseDuration.attempts, checks, "Make sure we hit all of them"); checks = 0; return this._runPerfTestAsync("optTestObject", () => { objForEachKey(optTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.003, baseDuration).then((optDuration1) => { Assert.equal(iterations * objectFields * optDuration1.attempts, checks, "Make sure we hit all of them"); this._checkRun(baseDuration, optDuration1); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: objForEachKey complete small (<20 fields) dynamic object", timeout: 60000, test: () => { let iterations = 100000; let baseTestObject = { } as any; let objectFields = 19; // There is a JIT optimization for objects with <= 19 fields for (let lp = 0; lp < objectFields; lp++) { setValue(baseTestObject, "test.value." + lp, "Test Value " + lp); } // JIT Optimization if we know we are playing with a dynamic object let optTestObject = optimizeObject(baseTestObject); let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { objForEachKey(baseTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.0015).then((baseDuration) => { Assert.equal(iterations * objectFields * baseDuration.attempts, checks, "Make sure we hit all of them"); checks = 0; return this._runPerfTestAsync("optTestObject", () => { objForEachKey(optTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.001, baseDuration).then((optDuration) => { Assert.equal(iterations * objectFields * optDuration.attempts, checks, "Make sure we hit all of them"); this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: objForEachKey complete large (>= 20 fields) dynamic object", timeout: 60000, test: () => { let iterations = 100000; let baseTestObject = { } as any; let objectFields = 21; // There is a JIT optimization for objects with <= 19 fields for (let lp = 0; lp < objectFields; lp++) { setValue(baseTestObject, "test.value." + lp, "Test Value " + lp); } // JIT Optimization if we know we are playing with a dynamic object let optTestObject = optimizeObject(baseTestObject); let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { objForEachKey(baseTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.002).then((baseDuration) => { Assert.equal(iterations * objectFields * baseDuration.attempts, checks, "Make sure we hit all of them"); checks = 0; return this._runPerfTestAsync("optTestObject", () => { objForEachKey(optTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.002, baseDuration).then((optDuration) => { Assert.equal(iterations * objectFields * optDuration.attempts, checks, "Make sure we hit all of them"); this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: objForEachKey with small (<20 fields) extended dynamic object", timeout: 60000, test: () => { let iterations = 100000; let baseTestObject = { a: 1 } as any; let objectFields = 18; for (let lp = 0; lp < objectFields - 1; lp++) { setValue(baseTestObject, "test.value." + lp, "Test Value " + lp); } // JIT Optimization if we know we are playing with a dynamic object let optTestObject = optimizeObject(baseTestObject); let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { objForEachKey(baseTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.0015).then((baseDuration) => { Assert.equal(iterations * objectFields * baseDuration.attempts, checks, "Make sure we hit all of them"); checks = 0; return this._runPerfTestAsync("optTestObject", () => { objForEachKey(optTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.001, baseDuration).then((optDuration) => { Assert.equal(iterations * objectFields * optDuration.attempts, checks, "Make sure we hit all of them"); this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: objForEachKey with large (>=20 fields) extended dynamic object", timeout: 60000, test: () => { let iterations = 100000; let baseTestObject = { a: 1 } as any; let objectFields = 20; for (let lp = 0; lp < objectFields - 1; lp++) { setValue(baseTestObject, "test.value." + lp, "Test Value " + lp); } // JIT Optimization if we know we are playing with a dynamic object let optTestObject = optimizeObject(baseTestObject); let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { objForEachKey(baseTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.0015).then((baseDuration) => { Assert.equal(iterations * objectFields * baseDuration.attempts, checks, "Make sure we hit all of them"); checks = 0; return this._runPerfTestAsync("optTestObject", () => { objForEachKey(optTestObject, (name, value) => { checks++; }); }, 400, iterations, 0.0015, baseDuration).then((optDuration) => { Assert.equal(iterations * objectFields * optDuration.attempts, checks, "Make sure we hit all of them"); this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); /** * This test always currently fails on chromium based browsers due to the way that chromium provides super * fast internal private classes for fixed objects and using the optimizeObject() creates a non-optimized * dynamic class -- so commenting out for future validation and local runs on Firefox */ // this.testCase({ // name: "PerfChecks: json.stringify fixed large (40 fields) object", // test: () => { // let iterations = 100000; // let baseTestObject = { // "test.value0": "Test Value 0", // "test.value1": "Test Value 1", // "test.value2": "Test Value 2", // "test.value3": "Test Value 3", // "test.value4": "Test Value 4", // "test.value5": "Test Value 5", // "test.value6": "Test Value 6", // "test.value7": "Test Value 7", // "test.value8": "Test Value 8", // "test.value9": "Test Value 9", // "test.value10": "Test Value 10", // "test.value11": "Test Value 11", // "test.value12": "Test Value 12", // "test.value13": "Test Value 13", // "test.value14": "Test Value 14", // "test.value15": "Test Value 15", // "test.value16": "Test Value 16", // "test.value17": "Test Value 17", // "test.value18": "Test Value 18", // "test.value19": "Test Value 19", // "test.value20": "Test Value 20", // "test.value21": "Test Value 21", // "test.value22": "Test Value 22", // "test.value23": "Test Value 23", // "test.value24": "Test Value 24", // "test.value25": "Test Value 25", // "test.value26": "Test Value 26", // "test.value27": "Test Value 27", // "test.value28": "Test Value 28", // "test.value29": "Test Value 29", // "test.value30": "Test Value 30", // "test.value31": "Test Value 31", // "test.value32": "Test Value 32", // "test.value33": "Test Value 33", // "test.value34": "Test Value 34", // "test.value35": "Test Value 35", // "test.value36": "Test Value 36", // "test.value37": "Test Value 37", // "test.value38": "Test Value 38", // "test.value39": "Test Value 39" // } as any; // let optTestObject = optimizeObject(baseTestObject); // Assert.equal(JSON.stringify(baseTestObject), JSON.stringify(optTestObject), "Make sure the new assigned object is the same"); // let checks = 0; // let baseDuration = this._runPerfTest("baseTestObject", () => { // JSON.stringify(baseTestObject); // }, 550, iterations, 0.005); // checks = 0; // let optDuration = this._runPerfTest("optTestObject", () => { // JSON.stringify(optTestObject); // }, 550, iterations, 0.005); // this._checkRun(baseDuration, optDuration); // } // }); this.testCase({ name: "PerfChecks: json.stringify dynamic large (40 fields) object", timeout: 120000, test: () => { let iterations = 10000; let baseTestObject = { }; for (let lp = 0; lp < 40; lp++) { baseTestObject["test.value" + lp] = "Test Value " + lp; } let optTestObject = optimizeObject(baseTestObject); Assert.equal(JSON.stringify(baseTestObject), JSON.stringify(optTestObject), "Make sure the new assigned object is the same"); let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { JSON.stringify(baseTestObject); }, 150, iterations, 0.015).then((baseDuration) => { checks = 0; return this._runPerfTestAsync("optTestObject", () => { JSON.stringify(optTestObject); }, 150, iterations, 0.015, baseDuration).then((optDuration) => { this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: json.stringify complete small (<20 fields) dynamic object", timeout: 120000, test: () => { let iterations = 10000; let baseTestObject = { } as any; let objectFields = 19; // There is a JIT optimization for objects with <= 19 fields for (let lp = 0; lp < objectFields; lp++) { setValue(baseTestObject, "test.value." + lp, "Test Value " + lp); } let optTestObject = optimizeObject(baseTestObject); Assert.equal(JSON.stringify(baseTestObject), JSON.stringify(optTestObject), "Make sure the new assigned object is the same"); let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { JSON.stringify(baseTestObject); }, 50, iterations, 0.005).then((baseDuration) => { checks = 0; return this._runPerfTestAsync("optTestObject", () => { JSON.stringify(optTestObject); }, 50, iterations, 0.005, baseDuration).then((optDuration) => { this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: json.stringify with small (<20 fields) extended dynamic object", timeout: 120000, test: () => { let iterations = 10000; let baseTestObject = { a: 1 } as any; let objectFields = 19; for (let lp = 0; lp < objectFields - 1; lp++) { setValue(baseTestObject, "test.value." + lp, "Test Value " + lp); } // Jit Optimization!!! let optTestObject = optimizeObject(baseTestObject); Assert.equal(JSON.stringify(baseTestObject), JSON.stringify(optTestObject), "Make sure the new assigned object is the same"); return this._runPerfTestAsync("baseTestObject", () => { JSON.stringify(baseTestObject); }, 50, iterations, 0.005).then((baseDuration) => { return this._runPerfTestAsync("optTestObject", () => { JSON.stringify(optTestObject); }, 50, iterations, 0.003, baseDuration).then((optDuration) => { this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: json.stringify with large (>= 20 fields) extended dynamic object", timeout: 60000, test: () => { let iterations = 10000; let baseTestObject = { a: 1 } as any; let objectFields = 20; for (let lp = 0; lp < objectFields - 1; lp++) { setValue(baseTestObject, "test.value." + lp, "Test Value " + lp); } let optTestObject = optimizeObject(baseTestObject); Assert.equal(JSON.stringify(baseTestObject), JSON.stringify(optTestObject), "Make sure the new assigned object is the same"); return this._runPerfTestAsync("baseTestObject", () => { JSON.stringify(baseTestObject); }, 100, iterations, 0.01).then((baseDuration) => { return this._runPerfTestAsync("optTestObject", () => { JSON.stringify(optTestObject); }, 100, iterations, 0.01, baseDuration).then((optDuration) => { this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: objKeys with small (<20 fields) dynamic object", timeout: 60000, test: () => { let iterations = 100000; let objectFields = 19; let baseTestObject = { }; for (let lp = 0; lp < objectFields; lp++) { baseTestObject["value" + lp] = "Test Value " + lp; } let optTestObject = optimizeObject(baseTestObject); let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { checks += objKeys(baseTestObject).length; }, 300, iterations, 0.0015).then((baseDuration) => { Assert.equal(iterations * objectFields * baseDuration.attempts, checks, "Make sure we hit all of them"); checks = 0; return this._runPerfTestAsync("optTestObject", () => { checks += objKeys(optTestObject).length; }, 300, iterations, 0.001, baseDuration).then((optDuration) => { Assert.equal(iterations * objectFields * optDuration.attempts, checks, "Make sure we hit all of them"); this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: objKeys extended object with small (<20 fields)", timeout: 60000, test: () => { let iterations = 100000; let objectFields = 19; let baseTestObject = { a: 1 }; for (let lp = 0; lp < objectFields - 1; lp++) { baseTestObject["value" + lp] = "Test Value " + lp; } let optTestObject = optimizeObject(baseTestObject); let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { checks += objKeys(baseTestObject).length; }, 150, iterations, 0.0015).then((baseDuration) => { Assert.equal(iterations * objectFields * baseDuration.attempts, checks, "Make sure we hit all of them"); checks = 0; return this._runPerfTestAsync("optTestObject", () => { checks += objKeys(optTestObject).length; }, 150, iterations, 0.0015, baseDuration).then((optDuration) => { Assert.equal(iterations * objectFields * optDuration.attempts, checks, "Make sure we hit all of them"); this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); this.testCase({ name: "PerfChecks: objKeys dynamic object with large (>=20 fields)", timeout: 60000, test: () => { let iterations = 100000; let objectFields = 21; let baseTestObject = { }; for (let lp = 0; lp < objectFields; lp++) { baseTestObject["value" + lp] = "Test Value " + lp; } let checks = 0; return this._runPerfTestAsync("baseTestObject", () => { checks += objKeys(baseTestObject).length; }, 200, iterations, 0.0015).then((baseDuration) => { Assert.equal(iterations * objectFields * baseDuration.attempts, checks, "Make sure we hit all of them"); let optTestObject = optimizeObject(baseTestObject); checks = 0; return this._runPerfTestAsync("optTestObject", () => { checks += objKeys(optTestObject).length; }, 200, iterations, 0.0015, baseDuration).then((optDuration) => { Assert.equal(iterations * objectFields * optDuration.attempts, checks, "Make sure we hit all of them"); this._checkRun(baseDuration, optDuration); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); }).catch((reason) => { Assert.ok(false, "Promise rejected - " + reason); }); } }); } private _getStandardDeviation(values: number[]) { const n = values.length const mean = values.reduce((a, b) => a + b) / n return Math.sqrt(values.map(x => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n) } private _checkRun(baseDuration: PerfMeasurements, chkDuration: PerfMeasurements) { if (chkDuration.duration <= baseDuration.duration) { // If the new min is smaller then it's a pass Assert.ok(true, `New minimum ${chkDuration.duration} is <= the base ${baseDuration.duration}`); return; } if (chkDuration.avgDuration <= baseDuration.avgDuration) { // If the new average is smaller then it's a pass Assert.ok(true, `New average ${chkDuration.avgDuration} is <= the base average ${baseDuration.avgDuration}`); return } if (chkDuration.duration <= (baseDuration.avgDuration + (baseDuration.deviation / 2))) { // If the new min is smaller then it's a pass Assert.ok(true, `Chk minimum ${chkDuration.duration} is <= base average less half base deviation ${baseDuration.avgDuration + (baseDuration.deviation / 2)}`); return; } if ((chkDuration.duration + chkDuration.deviation) <= baseDuration.avgDuration) { // If the new min is smaller then it's a pass Assert.ok(true, `Chk min plus deviation ${chkDuration.duration + chkDuration.deviation} is <= base average ${baseDuration.avgDuration}`); return; } if ((chkDuration.duration + baseDuration.deviation) <= baseDuration.avgDuration) { // If the new min is smaller then it's a pass Assert.ok(true, `Chk min plus base deviation ${chkDuration.duration + baseDuration.deviation} is <= base average ${baseDuration.avgDuration}`); return; } if (chkDuration.duration <= baseDuration.avgDuration) { // If the new min is smaller than the base average Assert.ok(true, `New minimum ${chkDuration.duration} is <= the base average ${baseDuration.avgDuration}`); return; } if (chkDuration.duration <= baseDuration.maxDuration) { // If the new min is smaller than the base max value (needed for build servers and shared CPU runs) Assert.ok(true, `New minimum ${chkDuration.duration} is <= the base average ${baseDuration.maxDuration}`); return; } Assert.ok(false, "The new values are not smaller or within the standard deviation thresholds\n" + `Base: mn:${baseDuration.duration}, avg:${baseDuration.avgDuration}, avg:${baseDuration.maxDuration}, dev:${baseDuration.deviation} it:${baseDuration.iteration} avg:${baseDuration.avgIteration}\n` + `Chk : mn:${chkDuration.duration}, avg:${chkDuration.avgDuration}, avg:${chkDuration.maxDuration}, dev:${chkDuration.deviation} it:${chkDuration.iteration} avg:${chkDuration.avgIteration}`); } private _runPerfIterations(theDuration: PerfMeasurements, testName: string, theTest: () => void, iterations: number, attempts: number[]) { let start = performance.now(); for (let lp = 0; lp < iterations; lp++) { theTest(); } let duration = performance.now() - start; if (attempts.length === 0) { theDuration.duration = duration; theDuration.maxDuration = duration; theDuration.total = duration; } else { theDuration.total += duration; theDuration.duration = Math.min(theDuration.duration, duration); theDuration.maxDuration = Math.max(theDuration.maxDuration, duration); } attempts.push(duration); Assert.ok(true, `${testName}: Attempt: ${(attempts.length)} Took: ${duration}ms Avg: ${duration / iterations}`); } private _runPerfAttempts(testName: string, theTest: () => void, iterations: number, maxAttempts: number, totalAttempts: number): PerfMeasurements { let values: number[] = [] let theDuration: PerfMeasurements = { duration: 0, iteration: 0, avgIteration: 0, avgDuration: 0, maxDuration: 0, total: 0, attempts: totalAttempts, deviation: 0 }; let attempts = 0; do { attempts++; this._runPerfIterations(theDuration, testName, theTest, iterations, values); } while (attempts < maxAttempts); theDuration.iteration = theDuration.duration / iterations; totalAttempts += attempts; theDuration.attempts = totalAttempts; theDuration.avgDuration = theDuration.total / attempts; theDuration.avgIteration = theDuration.avgDuration / iterations; theDuration.deviation = this._getStandardDeviation(values); return theDuration; } private _runPerfTest(testName: string, theTest: () => void, maxTime: number, iterations: number, maxIteration: number, baseMeasurements?: PerfMeasurements, maxAttempts = 25): PerfMeasurements { let theDuration: PerfMeasurements = {} as PerfMeasurements; let retryCount = 0; while (retryCount < 5) { retryCount++; theDuration = this._runPerfAttempts(testName, theTest, iterations, maxAttempts, theDuration.attempts || 0); let devAllowance = (theDuration.deviation / 2); if ((theDuration.duration + devAllowance) <= maxTime && (theDuration.iteration < maxIteration || (theDuration.avgIteration - devAllowance) < maxIteration)) { // Good run if (!baseMeasurements || theDuration.deviation < baseMeasurements.deviation * 2.5) { break; } } } Assert.ok(theDuration.duration <= maxTime, `${testName}: Check min total time for <= ${maxTime}ms from ${iterations} iterations. Min: ${theDuration.duration}ms Avg: ${theDuration.avgDuration}ms Max: ${theDuration.maxDuration}ms Total: ${theDuration.total}ms Deviation: ${theDuration.deviation}ms`); Assert.ok(theDuration.iteration < maxIteration || (theDuration.avgIteration - (theDuration.deviation / 2)) < maxIteration, `${testName}: Check Average iteration. Avg: ${theDuration.avgIteration}ms Min: ${theDuration.iteration}`); return theDuration; } private _runPerfTestAsync(testName: string, theTest: () => void, maxTime: number, iterations: number, maxIteration: number, baseMeasurements?: PerfMeasurements, maxAttempts = 25): Promise<PerfMeasurements> { let _self = this; return new Promise<PerfMeasurements>((runComplete, runReject) => { function _scheduleTest(theTest: () => void) { AITestClass.orgSetTimeout(() => { try { theTest.call(_self); } catch (e) { Assert.ok(false, "Unexpected exception - " + e); runReject(e); } }, 0); } try { let theDuration: PerfMeasurements = {} as PerfMeasurements; let retryCount = 0; function doAttempts() { retryCount++; theDuration = _self._runPerfAttempts(testName, theTest, iterations, maxAttempts, theDuration.attempts || 0); let devAllowance = (theDuration.deviation / 2); if (retryCount >= 5 || ((theDuration.duration + devAllowance) <= maxTime && (theDuration.iteration < maxIteration || (theDuration.avgIteration - devAllowance) < maxIteration))) { // Last Retry or Good run if (retryCount >= 5 || !baseMeasurements || theDuration.deviation < baseMeasurements.deviation * 2.5) { Assert.ok(theDuration.duration <= maxTime, `${testName}: Check min total time for <= ${maxTime}ms from ${iterations} iterations. Min: ${theDuration.duration}ms Avg: ${theDuration.avgDuration}ms Max: ${theDuration.maxDuration}ms Total: ${theDuration.total}ms Deviation: ${theDuration.deviation}ms`); Assert.ok(theDuration.iteration < maxIteration || (theDuration.avgIteration - (theDuration.deviation / 2)) < maxIteration, `${testName}: Check Average iteration. Avg: ${theDuration.avgIteration}ms Min: ${theDuration.iteration}`); runComplete(theDuration); return; } } Assert.ok(true, `${testName}: Summary Min: ${theDuration.duration}ms Avg: ${theDuration.avgDuration}ms Max: ${theDuration.maxDuration}ms Total: ${theDuration.total}ms Deviation: ${theDuration.deviation}ms Iteration Avg: ${theDuration.avgIteration}ms Min: ${theDuration.iteration}`); // reschedule _scheduleTest(doAttempts); } _scheduleTest(doAttempts); } catch (e) { Assert.ok(false, "Unexpected exception - " + e); runReject(e); } }); } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class Grafana extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: Grafana.Types.ClientConfiguration) config: Config & Grafana.Types.ClientConfiguration; /** * Assigns a Grafana Enterprise license to a workspace. Upgrading to Grafana Enterprise incurs additional fees. For more information, see Upgrade a workspace to Grafana Enterprise. */ associateLicense(params: Grafana.Types.AssociateLicenseRequest, callback?: (err: AWSError, data: Grafana.Types.AssociateLicenseResponse) => void): Request<Grafana.Types.AssociateLicenseResponse, AWSError>; /** * Assigns a Grafana Enterprise license to a workspace. Upgrading to Grafana Enterprise incurs additional fees. For more information, see Upgrade a workspace to Grafana Enterprise. */ associateLicense(callback?: (err: AWSError, data: Grafana.Types.AssociateLicenseResponse) => void): Request<Grafana.Types.AssociateLicenseResponse, AWSError>; /** * Creates a workspace. In a workspace, you can create Grafana dashboards and visualizations to analyze your metrics, logs, and traces. You don't have to build, package, or deploy any hardware to run the Grafana server. Don't use CreateWorkspace to modify an existing workspace. Instead, use UpdateWorkspace. */ createWorkspace(params: Grafana.Types.CreateWorkspaceRequest, callback?: (err: AWSError, data: Grafana.Types.CreateWorkspaceResponse) => void): Request<Grafana.Types.CreateWorkspaceResponse, AWSError>; /** * Creates a workspace. In a workspace, you can create Grafana dashboards and visualizations to analyze your metrics, logs, and traces. You don't have to build, package, or deploy any hardware to run the Grafana server. Don't use CreateWorkspace to modify an existing workspace. Instead, use UpdateWorkspace. */ createWorkspace(callback?: (err: AWSError, data: Grafana.Types.CreateWorkspaceResponse) => void): Request<Grafana.Types.CreateWorkspaceResponse, AWSError>; /** * Deletes an Amazon Managed Grafana workspace. */ deleteWorkspace(params: Grafana.Types.DeleteWorkspaceRequest, callback?: (err: AWSError, data: Grafana.Types.DeleteWorkspaceResponse) => void): Request<Grafana.Types.DeleteWorkspaceResponse, AWSError>; /** * Deletes an Amazon Managed Grafana workspace. */ deleteWorkspace(callback?: (err: AWSError, data: Grafana.Types.DeleteWorkspaceResponse) => void): Request<Grafana.Types.DeleteWorkspaceResponse, AWSError>; /** * Displays information about one Amazon Managed Grafana workspace. */ describeWorkspace(params: Grafana.Types.DescribeWorkspaceRequest, callback?: (err: AWSError, data: Grafana.Types.DescribeWorkspaceResponse) => void): Request<Grafana.Types.DescribeWorkspaceResponse, AWSError>; /** * Displays information about one Amazon Managed Grafana workspace. */ describeWorkspace(callback?: (err: AWSError, data: Grafana.Types.DescribeWorkspaceResponse) => void): Request<Grafana.Types.DescribeWorkspaceResponse, AWSError>; /** * Displays information about the authentication methods used in one Amazon Managed Grafana workspace. */ describeWorkspaceAuthentication(params: Grafana.Types.DescribeWorkspaceAuthenticationRequest, callback?: (err: AWSError, data: Grafana.Types.DescribeWorkspaceAuthenticationResponse) => void): Request<Grafana.Types.DescribeWorkspaceAuthenticationResponse, AWSError>; /** * Displays information about the authentication methods used in one Amazon Managed Grafana workspace. */ describeWorkspaceAuthentication(callback?: (err: AWSError, data: Grafana.Types.DescribeWorkspaceAuthenticationResponse) => void): Request<Grafana.Types.DescribeWorkspaceAuthenticationResponse, AWSError>; /** * Removes the Grafana Enterprise license from a workspace. */ disassociateLicense(params: Grafana.Types.DisassociateLicenseRequest, callback?: (err: AWSError, data: Grafana.Types.DisassociateLicenseResponse) => void): Request<Grafana.Types.DisassociateLicenseResponse, AWSError>; /** * Removes the Grafana Enterprise license from a workspace. */ disassociateLicense(callback?: (err: AWSError, data: Grafana.Types.DisassociateLicenseResponse) => void): Request<Grafana.Types.DisassociateLicenseResponse, AWSError>; /** * Lists the users and groups who have the Grafana Admin and Editor roles in this workspace. If you use this operation without specifying userId or groupId, the operation returns the roles of all users and groups. If you specify a userId or a groupId, only the roles for that user or group are returned. If you do this, you can specify only one userId or one groupId. */ listPermissions(params: Grafana.Types.ListPermissionsRequest, callback?: (err: AWSError, data: Grafana.Types.ListPermissionsResponse) => void): Request<Grafana.Types.ListPermissionsResponse, AWSError>; /** * Lists the users and groups who have the Grafana Admin and Editor roles in this workspace. If you use this operation without specifying userId or groupId, the operation returns the roles of all users and groups. If you specify a userId or a groupId, only the roles for that user or group are returned. If you do this, you can specify only one userId or one groupId. */ listPermissions(callback?: (err: AWSError, data: Grafana.Types.ListPermissionsResponse) => void): Request<Grafana.Types.ListPermissionsResponse, AWSError>; /** * Returns a list of Amazon Managed Grafana workspaces in the account, with some information about each workspace. For more complete information about one workspace, use DescribeWorkspace. */ listWorkspaces(params: Grafana.Types.ListWorkspacesRequest, callback?: (err: AWSError, data: Grafana.Types.ListWorkspacesResponse) => void): Request<Grafana.Types.ListWorkspacesResponse, AWSError>; /** * Returns a list of Amazon Managed Grafana workspaces in the account, with some information about each workspace. For more complete information about one workspace, use DescribeWorkspace. */ listWorkspaces(callback?: (err: AWSError, data: Grafana.Types.ListWorkspacesResponse) => void): Request<Grafana.Types.ListWorkspacesResponse, AWSError>; /** * Updates which users in a workspace have the Grafana Admin or Editor roles. */ updatePermissions(params: Grafana.Types.UpdatePermissionsRequest, callback?: (err: AWSError, data: Grafana.Types.UpdatePermissionsResponse) => void): Request<Grafana.Types.UpdatePermissionsResponse, AWSError>; /** * Updates which users in a workspace have the Grafana Admin or Editor roles. */ updatePermissions(callback?: (err: AWSError, data: Grafana.Types.UpdatePermissionsResponse) => void): Request<Grafana.Types.UpdatePermissionsResponse, AWSError>; /** * Modifies an existing Amazon Managed Grafana workspace. If you use this operation and omit any optional parameters, the existing values of those parameters are not changed. To modify the user authentication methods that the workspace uses, such as SAML or Amazon Web Services SSO, use UpdateWorkspaceAuthentication. To modify which users in the workspace have the Admin and Editor Grafana roles, use UpdatePermissions. */ updateWorkspace(params: Grafana.Types.UpdateWorkspaceRequest, callback?: (err: AWSError, data: Grafana.Types.UpdateWorkspaceResponse) => void): Request<Grafana.Types.UpdateWorkspaceResponse, AWSError>; /** * Modifies an existing Amazon Managed Grafana workspace. If you use this operation and omit any optional parameters, the existing values of those parameters are not changed. To modify the user authentication methods that the workspace uses, such as SAML or Amazon Web Services SSO, use UpdateWorkspaceAuthentication. To modify which users in the workspace have the Admin and Editor Grafana roles, use UpdatePermissions. */ updateWorkspace(callback?: (err: AWSError, data: Grafana.Types.UpdateWorkspaceResponse) => void): Request<Grafana.Types.UpdateWorkspaceResponse, AWSError>; /** * Use this operation to define the identity provider (IdP) that this workspace authenticates users from, using SAML. You can also map SAML assertion attributes to workspace user information and define which groups in the assertion attribute are to have the Admin and Editor roles in the workspace. */ updateWorkspaceAuthentication(params: Grafana.Types.UpdateWorkspaceAuthenticationRequest, callback?: (err: AWSError, data: Grafana.Types.UpdateWorkspaceAuthenticationResponse) => void): Request<Grafana.Types.UpdateWorkspaceAuthenticationResponse, AWSError>; /** * Use this operation to define the identity provider (IdP) that this workspace authenticates users from, using SAML. You can also map SAML assertion attributes to workspace user information and define which groups in the assertion attribute are to have the Admin and Editor roles in the workspace. */ updateWorkspaceAuthentication(callback?: (err: AWSError, data: Grafana.Types.UpdateWorkspaceAuthenticationResponse) => void): Request<Grafana.Types.UpdateWorkspaceAuthenticationResponse, AWSError>; } declare namespace Grafana { export type AccountAccessType = "CURRENT_ACCOUNT"|"ORGANIZATION"|string; export type AllowedOrganization = string; export type AllowedOrganizations = AllowedOrganization[]; export type AssertionAttribute = string; export interface AssertionAttributes { /** * The name of the attribute within the SAML assertion to use as the email names for SAML users. */ email?: AssertionAttribute; /** * The name of the attribute within the SAML assertion to use as the user full "friendly" names for user groups. */ groups?: AssertionAttribute; /** * The name of the attribute within the SAML assertion to use as the login names for SAML users. */ login?: AssertionAttribute; /** * The name of the attribute within the SAML assertion to use as the user full "friendly" names for SAML users. */ name?: AssertionAttribute; /** * The name of the attribute within the SAML assertion to use as the user full "friendly" names for the users' organizations. */ org?: AssertionAttribute; /** * The name of the attribute within the SAML assertion to use as the user roles. */ role?: AssertionAttribute; } export interface AssociateLicenseRequest { /** * The type of license to associate with the workspace. */ licenseType: LicenseType; /** * The ID of the workspace to associate the license with. */ workspaceId: WorkspaceId; } export interface AssociateLicenseResponse { /** * A structure containing data about the workspace. */ workspace: WorkspaceDescription; } export interface AuthenticationDescription { /** * A structure containing information about how this workspace works with Amazon Web Services SSO. */ awsSso?: AwsSsoAuthentication; /** * Specifies whether this workspace uses Amazon Web Services SSO, SAML, or both methods to authenticate users to use the Grafana console in the Amazon Managed Grafana workspace. */ providers: AuthenticationProviders; /** * A structure containing information about how this workspace works with SAML, including what attributes within the assertion are to be mapped to user information in the workspace. */ saml?: SamlAuthentication; } export type AuthenticationProviderTypes = "AWS_SSO"|"SAML"|string; export type AuthenticationProviders = AuthenticationProviderTypes[]; export interface AuthenticationSummary { /** * Specifies whether the workspace uses SAML, Amazon Web Services SSO, or both methods for user authentication. */ providers: AuthenticationProviders; /** * Specifies whether the workplace's user authentication method is fully configured. */ samlConfigurationStatus?: SamlConfigurationStatus; } export interface AwsSsoAuthentication { /** * The ID of the Amazon Web Services SSO-managed application that is created by Amazon Managed Grafana. */ ssoClientId?: SSOClientId; } export type Boolean = boolean; export type ClientToken = string; export interface CreateWorkspaceRequest { /** * Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify ORGANIZATION, you must specify which organizational units the workspace can access in the workspaceOrganizationalUnits parameter. */ accountAccessType: AccountAccessType; /** * Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate users for using the Grafana console within a workspace. For more information, see User authentication in Amazon Managed Grafana. */ authenticationProviders: AuthenticationProviders; /** * A unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: ClientToken; /** * The name of an IAM role that already exists to use with Organizations to access Amazon Web Services data sources and notification channels in other accounts in an organization. */ organizationRoleName?: OrganizationRoleName; /** * If you specify Service Managed, Amazon Managed Grafana automatically creates the IAM roles and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels. If you specify CUSTOMER_MANAGED, you will manage those roles and permissions yourself. If you are creating this workspace in a member account of an organization that is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose CUSTOMER_MANAGED. For more information, see Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels */ permissionType: PermissionType; /** * The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace. */ stackSetName?: StackSetName; /** * Specify the Amazon Web Services data sources that you want to be queried in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these sources. You must still add them as data sources in the Grafana console in the workspace. If you don't specify a data source here, you can still add it as a data source in the workspace console later. However, you will then have to manually configure permissions for it. */ workspaceDataSources?: DataSourceTypesList; /** * A description for the workspace. This is used only to help you identify this workspace. */ workspaceDescription?: Description; /** * The name for the workspace. It does not have to be unique. */ workspaceName?: WorkspaceName; /** * Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels. */ workspaceNotificationDestinations?: NotificationDestinationsList; /** * Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization. */ workspaceOrganizationalUnits?: OrganizationalUnitList; /** * The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from. If you already have a role that you want to use, specify it here. If you omit this field and you specify some Amazon Web Services resources in workspaceDataSources or workspaceNotificationDestinations, a new IAM role with the necessary permissions is automatically created. */ workspaceRoleArn?: IamRoleArn; } export interface CreateWorkspaceResponse { /** * A structure containing data about the workspace that was created. */ workspace: WorkspaceDescription; } export type DataSourceType = "AMAZON_OPENSEARCH_SERVICE"|"CLOUDWATCH"|"PROMETHEUS"|"XRAY"|"TIMESTREAM"|"SITEWISE"|string; export type DataSourceTypesList = DataSourceType[]; export interface DeleteWorkspaceRequest { /** * The ID of the workspace to delete. */ workspaceId: WorkspaceId; } export interface DeleteWorkspaceResponse { /** * A structure containing information about the workspace that was deleted. */ workspace: WorkspaceDescription; } export interface DescribeWorkspaceAuthenticationRequest { /** * The ID of the workspace to return authentication information about. */ workspaceId: WorkspaceId; } export interface DescribeWorkspaceAuthenticationResponse { /** * A structure containing information about the authentication methods used in the workspace. */ authentication: AuthenticationDescription; } export interface DescribeWorkspaceRequest { /** * The ID of the workspace to display information about. */ workspaceId: WorkspaceId; } export interface DescribeWorkspaceResponse { /** * A structure containing information about the workspace. */ workspace: WorkspaceDescription; } export type Description = string; export interface DisassociateLicenseRequest { /** * The type of license to remove from the workspace. */ licenseType: LicenseType; /** * The ID of the workspace to remove the Grafana Enterprise license from. */ workspaceId: WorkspaceId; } export interface DisassociateLicenseResponse { /** * A structure containing information about the workspace. */ workspace: WorkspaceDescription; } export type Endpoint = string; export type GrafanaVersion = string; export type IamRoleArn = string; export interface IdpMetadata { /** * The URL of the location containing the metadata. */ url?: IdpMetadataUrl; /** * The actual full metadata file, in XML format. */ xml?: String; } export type IdpMetadataUrl = string; export type LicenseType = "ENTERPRISE"|"ENTERPRISE_FREE_TRIAL"|string; export interface ListPermissionsRequest { /** * (Optional) Limits the results to only the group that matches this ID. */ groupId?: SsoId; /** * The maximum number of results to include in the response. */ maxResults?: ListPermissionsRequestMaxResultsInteger; /** * The token to use when requesting the next set of results. You received this token from a previous ListPermissions operation. */ nextToken?: PaginationToken; /** * (Optional) Limits the results to only the user that matches this ID. */ userId?: SsoId; /** * (Optional) If you specify SSO_USER, then only the permissions of Amazon Web Services SSO users are returned. If you specify SSO_GROUP, only the permissions of Amazon Web Services SSO groups are returned. */ userType?: UserType; /** * The ID of the workspace to list permissions for. This parameter is required. */ workspaceId: WorkspaceId; } export type ListPermissionsRequestMaxResultsInteger = number; export interface ListPermissionsResponse { /** * The token to use in a subsequent ListPermissions operation to return the next set of results. */ nextToken?: PaginationToken; /** * The permissions returned by the operation. */ permissions: PermissionEntryList; } export interface ListWorkspacesRequest { /** * The maximum number of workspaces to include in the results. */ maxResults?: ListWorkspacesRequestMaxResultsInteger; /** * The token for the next set of workspaces to return. (You receive this token from a previous ListWorkspaces operation.) */ nextToken?: PaginationToken; } export type ListWorkspacesRequestMaxResultsInteger = number; export interface ListWorkspacesResponse { /** * The token to use when requesting the next set of workspaces. */ nextToken?: PaginationToken; /** * An array of structures that contain some information about the workspaces in the account. */ workspaces: WorkspaceList; } export type LoginValidityDuration = number; export type NotificationDestinationType = "SNS"|string; export type NotificationDestinationsList = NotificationDestinationType[]; export type OrganizationRoleName = string; export type OrganizationalUnit = string; export type OrganizationalUnitList = OrganizationalUnit[]; export type PaginationToken = string; export interface PermissionEntry { /** * Specifies whether the user or group has the Admin or Editor role. */ role: Role; /** * A structure with the ID of the user or group with this role. */ user: User; } export type PermissionEntryList = PermissionEntry[]; export type PermissionType = "CUSTOMER_MANAGED"|"SERVICE_MANAGED"|string; export type Role = "ADMIN"|"EDITOR"|string; export type RoleValue = string; export type RoleValueList = RoleValue[]; export interface RoleValues { /** * A list of groups from the SAML assertion attribute to grant the Grafana Admin role to. */ admin?: RoleValueList; /** * A list of groups from the SAML assertion attribute to grant the Grafana Editor role to. */ editor?: RoleValueList; } export type SSOClientId = string; export interface SamlAuthentication { /** * A structure containing details about how this workspace works with SAML. */ configuration?: SamlConfiguration; /** * Specifies whether the workspace's SAML configuration is complete. */ status: SamlConfigurationStatus; } export interface SamlConfiguration { /** * Lists which organizations defined in the SAML assertion are allowed to use the Amazon Managed Grafana workspace. If this is empty, all organizations in the assertion attribute have access. */ allowedOrganizations?: AllowedOrganizations; /** * A structure that defines which attributes in the SAML assertion are to be used to define information about the users authenticated by that IdP to use the workspace. */ assertionAttributes?: AssertionAttributes; /** * A structure containing the identity provider (IdP) metadata used to integrate the identity provider with this workspace. */ idpMetadata: IdpMetadata; /** * How long a sign-on session by a SAML user is valid, before the user has to sign on again. */ loginValidityDuration?: LoginValidityDuration; /** * A structure containing arrays that map group names in the SAML assertion to the Grafana Admin and Editor roles in the workspace. */ roleValues?: RoleValues; } export type SamlConfigurationStatus = "CONFIGURED"|"NOT_CONFIGURED"|string; export type SsoId = string; export type StackSetName = string; export type String = string; export type Timestamp = Date; export type UpdateAction = "ADD"|"REVOKE"|string; export interface UpdateError { /** * Specifies which permission update caused the error. */ causedBy: UpdateInstruction; /** * The error code. */ code: UpdateErrorCodeInteger; /** * The message for this error. */ message: String; } export type UpdateErrorCodeInteger = number; export type UpdateErrorList = UpdateError[]; export interface UpdateInstruction { /** * Specifies whether this update is to add or revoke role permissions. */ action: UpdateAction; /** * The role to add or revoke for the user or the group specified in users. */ role: Role; /** * A structure that specifies the user or group to add or revoke the role for. */ users: UserList; } export type UpdateInstructionBatch = UpdateInstruction[]; export interface UpdatePermissionsRequest { /** * An array of structures that contain the permission updates to make. */ updateInstructionBatch: UpdateInstructionBatch; /** * The ID of the workspace to update. */ workspaceId: WorkspaceId; } export interface UpdatePermissionsResponse { /** * An array of structures that contain the errors from the operation, if any. */ errors: UpdateErrorList; } export interface UpdateWorkspaceAuthenticationRequest { /** * Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate users for using the Grafana console within a workspace. For more information, see User authentication in Amazon Managed Grafana. */ authenticationProviders: AuthenticationProviders; /** * If the workspace uses SAML, use this structure to map SAML assertion attributes to workspace user information and define which groups in the assertion attribute are to have the Admin and Editor roles in the workspace. */ samlConfiguration?: SamlConfiguration; /** * The ID of the workspace to update the authentication for. */ workspaceId: WorkspaceId; } export interface UpdateWorkspaceAuthenticationResponse { /** * A structure that describes the user authentication for this workspace after the update is made. */ authentication: AuthenticationDescription; } export interface UpdateWorkspaceRequest { /** * Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify ORGANIZATION, you must specify which organizational units the workspace can access in the workspaceOrganizationalUnits parameter. */ accountAccessType?: AccountAccessType; /** * The name of an IAM role that already exists to use to access resources through Organizations. */ organizationRoleName?: OrganizationRoleName; /** * If you specify Service Managed, Amazon Managed Grafana automatically creates the IAM roles and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels. If you specify CUSTOMER_MANAGED, you will manage those roles and permissions yourself. If you are creating this workspace in a member account of an organization and that account is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose CUSTOMER_MANAGED. For more information, see Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels */ permissionType?: PermissionType; /** * The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace. */ stackSetName?: StackSetName; /** * Specify the Amazon Web Services data sources that you want to be queried in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these sources. You must still add them as data sources in the Grafana console in the workspace. If you don't specify a data source here, you can still add it as a data source later in the workspace console. However, you will then have to manually configure permissions for it. */ workspaceDataSources?: DataSourceTypesList; /** * A description for the workspace. This is used only to help you identify this workspace. */ workspaceDescription?: Description; /** * The ID of the workspace to update. */ workspaceId: WorkspaceId; /** * A new name for the workspace to update. */ workspaceName?: WorkspaceName; /** * Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels. */ workspaceNotificationDestinations?: NotificationDestinationsList; /** * Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization. */ workspaceOrganizationalUnits?: OrganizationalUnitList; /** * The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from. If you already have a role that you want to use, specify it here. If you omit this field and you specify some Amazon Web Services resources in workspaceDataSources or workspaceNotificationDestinations, a new IAM role with the necessary permissions is automatically created. */ workspaceRoleArn?: IamRoleArn; } export interface UpdateWorkspaceResponse { /** * A structure containing data about the workspace that was created. */ workspace: WorkspaceDescription; } export interface User { /** * The ID of the user or group. */ id: SsoId; /** * Specifies whether this is a single user or a group. */ type: UserType; } export type UserList = User[]; export type UserType = "SSO_USER"|"SSO_GROUP"|string; export interface WorkspaceDescription { /** * Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If this is ORGANIZATION, the workspaceOrganizationalUnits parameter specifies which organizational units the workspace can access. */ accountAccessType?: AccountAccessType; /** * A structure that describes whether the workspace uses SAML, Amazon Web Services SSO, or both methods for user authentication. */ authentication: AuthenticationSummary; /** * The date that the workspace was created. */ created: Timestamp; /** * Specifies the Amazon Web Services data sources that have been configured to have IAM roles and permissions created to allow Amazon Managed Grafana to read data from these sources. */ dataSources: DataSourceTypesList; /** * The user-defined description of the workspace. */ description?: Description; /** * The URL that users can use to access the Grafana console in the workspace. */ endpoint: Endpoint; /** * Specifies whether this workspace has already fully used its free trial for Grafana Enterprise. */ freeTrialConsumed?: Boolean; /** * If this workspace is currently in the free trial period for Grafana Enterprise, this value specifies when that free trial ends. */ freeTrialExpiration?: Timestamp; /** * The version of Grafana supported in this workspace. */ grafanaVersion: GrafanaVersion; /** * The unique ID of this workspace. */ id: WorkspaceId; /** * If this workspace has a full Grafana Enterprise license, this specifies when the license ends and will need to be renewed. */ licenseExpiration?: Timestamp; /** * Specifies whether this workspace has a full Grafana Enterprise license or a free trial license. */ licenseType?: LicenseType; /** * The most recent date that the workspace was modified. */ modified: Timestamp; /** * The name of the workspace. */ name?: WorkspaceName; /** * The Amazon Web Services notification channels that Amazon Managed Grafana can automatically create IAM roles and permissions for, to allow Amazon Managed Grafana to use these channels. */ notificationDestinations?: NotificationDestinationsList; /** * The name of the IAM role that is used to access resources through Organizations. */ organizationRoleName?: OrganizationRoleName; /** * Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization. */ organizationalUnits?: OrganizationalUnitList; /** * If this is Service Managed, Amazon Managed Grafana automatically creates the IAM roles and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels. If this is CUSTOMER_MANAGED, you manage those roles and permissions yourself. If you are creating this workspace in a member account of an organization and that account is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose CUSTOMER_MANAGED. For more information, see Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels */ permissionType?: PermissionType; /** * The name of the CloudFormation stack set that is used to generate IAM roles to be used for this workspace. */ stackSetName?: StackSetName; /** * The current status of the workspace. */ status: WorkspaceStatus; /** * The IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from. This role must already exist. */ workspaceRoleArn?: IamRoleArn; } export type WorkspaceId = string; export type WorkspaceList = WorkspaceSummary[]; export type WorkspaceName = string; export type WorkspaceStatus = "ACTIVE"|"CREATING"|"DELETING"|"FAILED"|"UPDATING"|"UPGRADING"|"DELETION_FAILED"|"CREATION_FAILED"|"UPDATE_FAILED"|"UPGRADE_FAILED"|"LICENSE_REMOVAL_FAILED"|string; export interface WorkspaceSummary { /** * A structure containing information about the authentication methods used in the workspace. */ authentication: AuthenticationSummary; /** * The date that the workspace was created. */ created: Timestamp; /** * The customer-entered description of the workspace. */ description?: Description; /** * The URL endpoint to use to access the Grafana console in the workspace. */ endpoint: Endpoint; /** * The Grafana version that the workspace is running. */ grafanaVersion: GrafanaVersion; /** * The unique ID of the workspace. */ id: WorkspaceId; /** * The most recent date that the workspace was modified. */ modified: Timestamp; /** * The name of the workspace. */ name?: WorkspaceName; /** * The Amazon Web Services notification channels that Amazon Managed Grafana can automatically create IAM roles and permissions for, which allows Amazon Managed Grafana to use these channels. */ notificationDestinations?: NotificationDestinationsList; /** * The current status of the workspace. */ status: WorkspaceStatus; } /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2020-08-18"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the Grafana client. */ export import Types = Grafana; } export = Grafana;
the_stack
import { chain, noop, Rule, SchematicContext, Tree, } from '@angular-devkit/schematics'; import { ArrowFunction, CallExpression, SyntaxKind } from 'ts-morph'; import { featureFeatureModuleMapping, getKeyByMappingValueOrThrow, getSchematicsConfigByFeatureOrThrow, } from '../shared/schematics-config-mappings'; import { normalizeObject, removeProperty } from '../shared/utils/config-utils'; import { findFeatureModule, getModuleConfig, } from '../shared/utils/feature-utils'; import { findDynamicImport, getDynamicImportCallExpression, getDynamicImportPropertyAccess, staticImportExists, } from '../shared/utils/import-utils'; import { createSpartacusFeatureFileName, createSpartacusFeatureFolderPath, createSpartacusWrapperModuleFileName, } from '../shared/utils/lib-utils'; import { debugLogRule, formatFeatureComplete, formatFeatureStart, } from '../shared/utils/logger-utils'; import { addModuleImport, ensureModuleExists, getModulePropertyInitializer, } from '../shared/utils/new-module-utils'; import { createProgram, saveAndFormat } from '../shared/utils/program'; import { getProjectTsConfigPaths } from '../shared/utils/project-tsconfig-paths'; import { Schema as SpartacusWrapperOptions } from './schema'; /** * If the wrapper module already exists for * the given `options.markerModuleName`, it * sets it path to the `options` object. */ function checkWrapperModuleExists(options: SpartacusWrapperOptions): Rule { return (tree: Tree, context: SchematicContext) => { const feature = getKeyByMappingValueOrThrow( featureFeatureModuleMapping, options.markerModuleName ); if (options.debug) { context.logger.info( formatFeatureStart( feature, `checking the wrapper module path for ${options.markerModuleName} ...` ) ); } const featureConfig = getSchematicsConfigByFeatureOrThrow(feature); const moduleConfig = getModuleConfig( options.markerModuleName, featureConfig ); if (!moduleConfig) { return noop(); } const basePath = process.cwd(); const { buildPaths } = getProjectTsConfigPaths(tree, options.project); for (const tsconfigPath of buildPaths) { const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath); for (const sourceFile of appSourceFiles) { // check if the wrapper module already exists if ( staticImportExists( sourceFile, moduleConfig.importPath, moduleConfig.name ) ) { options.internal = { ...options.internal, wrapperModulePath: sourceFile.getFilePath(), }; if (options.debug) { context.logger.info( formatFeatureStart( feature, `found '${ options.markerModuleName }' in the existing wrapper module: ${sourceFile.getFilePath()} .` ) ); } return noop(); } } } if (options.debug) { context.logger.info( formatFeatureStart( feature, `wrapper module not found, will create a new one.` ) ); } }; } /** * Creates the wrapper module using the feature config * for the given module name. */ function createWrapperModule(options: SpartacusWrapperOptions): Rule { return (tree: Tree, context: SchematicContext) => { /** * if the wrapper module path is set, it means * the wrapper module already exists. */ if (options.internal?.wrapperModulePath) { return noop(); } const basePath = process.cwd(); const { buildPaths } = getProjectTsConfigPaths(tree, options.project); const feature = getKeyByMappingValueOrThrow( featureFeatureModuleMapping, options.markerModuleName ); if (options.debug) { context.logger.info( formatFeatureStart( feature, `creating wrapper module for ${options.markerModuleName} ...` ) ); } const featureConfig = getSchematicsConfigByFeatureOrThrow(feature); const moduleConfig = getModuleConfig( options.markerModuleName, featureConfig ); if (!moduleConfig) { return noop(); } const path = createSpartacusFeatureFolderPath(featureConfig.folderName); const name = createSpartacusWrapperModuleFileName(options.markerModuleName); const wrapperModulePath = `${path}/${name}`; /** * Mutates the options by setting * the wrapperModulePath for the next rules. */ options.internal = { ...options.internal, wrapperModulePath, }; const rules: Rule[] = []; for (const tsconfigPath of buildPaths) { const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath); const featureModule = findFeatureModule( featureConfig.featureModule, appSourceFiles ); if (!featureModule) { continue; } rules.push( ensureModuleExists({ path, name, project: options.project, /** * Only temporarily import the wrapper module to the feature module. * The import will be removed in updateFeatureModule(). * * This is a workaround for a weird behavior of the ts-morph library, * which does not "see" the newly created TS file if it is not * referenced anywhere. */ module: featureModule.getBaseNameWithoutExtension(), }) ); } rules.push( debugLogRule( formatFeatureComplete( feature, `wrapper module created for ${options.markerModuleName} in ${wrapperModulePath} .` ), options.debug ) ); return chain(rules); }; } /** * Changes the dynamic import to point to the wrapper module. * E.g. instead of: * `import('@spartacus/user/profile').then((m) => m.UserProfileModule),` * it will be changed to: * `import('./profile-wrapper.module').then((m) => m.ProfileWrapperModule),` * * It also removes the temporary static import to the wrapper * module from the ngModule's array. */ function updateFeatureModule(options: SpartacusWrapperOptions): Rule { return (tree: Tree, context: SchematicContext) => { const basePath = process.cwd(); const { buildPaths } = getProjectTsConfigPaths(tree, options.project); const feature = getKeyByMappingValueOrThrow( featureFeatureModuleMapping, options.markerModuleName ); if (options.debug) { context.logger.info( formatFeatureStart( feature, `updating feature module for '${options.markerModuleName}' ...` ) ); } const featureConfig = getSchematicsConfigByFeatureOrThrow(feature); const featureModuleConfig = getModuleConfig( options.markerModuleName, featureConfig ); if (!featureModuleConfig) { return noop(); } const rules: Rule[] = []; for (const tsconfigPath of buildPaths) { const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath); const featureModule = findFeatureModule( featureConfig.featureModule, appSourceFiles ); if (!featureModule) { continue; } const dynamicImport = findDynamicImport(featureModule, { moduleSpecifier: featureModuleConfig.importPath, namedImports: [featureModuleConfig.name], }); if (!dynamicImport) { continue; } for (const wrapperModule of appSourceFiles) { if ( !wrapperModule .getFilePath() .includes(options.internal?.wrapperModulePath ?? '') ) { continue; } const wrapperModuleClassName = wrapperModule.getClasses()[0].getName() ?? ''; updateDynamicImportPath( dynamicImport, featureModule.getRelativePathAsModuleSpecifierTo( wrapperModule.getFilePath() ) ); updateDynamicImportModuleName(dynamicImport, wrapperModuleClassName); // remove the dummy import const ngImports = getModulePropertyInitializer( featureModule, 'imports', false ); if (!ngImports) { continue; } for (const element of ngImports.getElements()) { if (element.getText() === wrapperModuleClassName) { ngImports.removeElement(element); break; } } saveAndFormat(featureModule); break; } } rules.push( debugLogRule( formatFeatureComplete( feature, `feature module updated for '${options.markerModuleName}' .` ), options.debug ) ); return chain(rules); }; } /** * Removes the dynamic imports pointing to the given * `options.featureModuleName` from the feature module. */ function removeLibraryDynamicImport(options: SpartacusWrapperOptions): Rule { return (tree: Tree, context: SchematicContext) => { const basePath = process.cwd(); const { buildPaths } = getProjectTsConfigPaths(tree, options.project); const feature = getKeyByMappingValueOrThrow( featureFeatureModuleMapping, options.featureModuleName ); const featureConfig = getSchematicsConfigByFeatureOrThrow(feature); const featureModuleConfig = getModuleConfig( options.featureModuleName, featureConfig ); if (!featureModuleConfig) { return noop(); } const path = createSpartacusFeatureFolderPath(featureConfig.folderName); const name = createSpartacusFeatureFileName(featureConfig.moduleName); const featureModulePath = `${path}/${name}`; if (options.debug) { context.logger.info( formatFeatureStart( feature, `removing dynamic import in '${featureModulePath}' for '${options.featureModuleName}' ...` ) ); } for (const tsconfigPath of buildPaths) { const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath); for (const featureModule of appSourceFiles) { if (!featureModule.getFilePath().includes(featureModulePath)) { continue; } const spartacusProvider = findDynamicImport(featureModule, { moduleSpecifier: featureModuleConfig.importPath, namedImports: [featureModuleConfig.name], })?.getFirstAncestorByKind(SyntaxKind.CallExpression); if (!spartacusProvider) { continue; } cleanupConfig(spartacusProvider); saveAndFormat(featureModule); break; } } if (options.debug) { context.logger.info( formatFeatureComplete( feature, `dynamic import removed in '${featureModulePath}' for '${options.featureModuleName}' .` ) ); } }; } /** * Takes the given spartacus provider, and removes the * 'module' configuration property from it. * If the are no other properties left, the whole * spartacus provider is removed. */ export function cleanupConfig(spartacusProvider: CallExpression): void { const objectLiteral = spartacusProvider.getFirstDescendantByKind( SyntaxKind.ObjectLiteralExpression ); if (!objectLiteral) { return; } removeProperty(objectLiteral, 'module'); if (normalizeObject(objectLiteral.getText()) === '{}') { spartacusProvider .getParentIfKindOrThrow(SyntaxKind.ArrayLiteralExpression) .removeElement(spartacusProvider); } } /** * Replaces the given dynamic import's path. * E.g. for the given `() => import('@spartacus/checkout/base')` * it replaces it with the given path: `() => import('./checkout-wrapper.module')`. */ function updateDynamicImportPath( dynamicImport: ArrowFunction, path: string ): void { getDynamicImportCallExpression(dynamicImport) ?.removeArgument(0) ?.insertArgument(0, `'${path}'`); } /** * Replaces the given dynamic import's module name. * E.g. for the given `(m) => m.CheckoutModule` * it replaces it with the given module name: `(m) => m.CheckoutWrapperModule`. */ function updateDynamicImportModuleName( dynamicImport: ArrowFunction, wrapperModuleName: string ): void { getDynamicImportPropertyAccess(dynamicImport)?.replaceWithText( `m.${wrapperModuleName}` ); } /** * Statically imports the given module. */ function updateWrapperModule( options: SpartacusWrapperOptions, moduleName: string ): Rule { return (tree: Tree, context: SchematicContext) => { const basePath = process.cwd(); const { buildPaths } = getProjectTsConfigPaths(tree, options.project); const feature = getKeyByMappingValueOrThrow( featureFeatureModuleMapping, moduleName ); const featureConfig = getSchematicsConfigByFeatureOrThrow(feature); const featureModuleConfig = getModuleConfig(moduleName, featureConfig); if (!featureModuleConfig) { return noop(); } const wrapperModulePath = options.internal?.wrapperModulePath ?? ''; if (options.debug) { context.logger.info( formatFeatureStart( feature, `importing the '${moduleName}' to the wrapper module ${wrapperModulePath} ...` ) ); } const rules: Rule[] = []; for (const tsconfigPath of buildPaths) { const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath); for (const wrapperModule of appSourceFiles) { if (!wrapperModule.getFilePath().includes(wrapperModulePath)) { continue; } addModuleImport(wrapperModule, { import: { moduleSpecifier: featureModuleConfig.importPath, namedImports: [featureModuleConfig.name], }, content: featureModuleConfig.name, }); saveAndFormat(wrapperModule); break; } } rules.push( debugLogRule( formatFeatureComplete( feature, `imported the '${moduleName}' to the wrapper module ${options.internal?.wrapperModulePath} .` ), options.debug ) ); return chain(rules); }; } /** * Generates wrapper modules for the given * Spartacus feature module. */ export function generateWrapperModule(options: SpartacusWrapperOptions): Rule { return (_tree: Tree, _context: SchematicContext): Rule => { return chain([ checkWrapperModuleExists(options), createWrapperModule(options), updateFeatureModule(options), removeLibraryDynamicImport(options), updateWrapperModule(options, options.markerModuleName), updateWrapperModule(options, options.featureModuleName), ]); }; }
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { CoreWSError } from '@classes/errors/wserror'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreCourseCommonModWSOptions } from '@features/course/services/course'; import { CoreCourseLogHelper } from '@features/course/services/log-helper'; import { CoreApp } from '@services/app'; import { CoreFilepool } from '@services/filepool'; import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreStatusWithWarningsWSResponse, CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton } from '@singletons'; import { AddonModChoiceOffline } from './choice-offline'; import { AddonModChoiceAutoSyncData, AddonModChoiceSyncProvider } from './choice-sync'; const ROOT_CACHE_KEY = 'mmaModChoice:'; /** * Service that provides some features for choices. */ @Injectable({ providedIn: 'root' }) export class AddonModChoiceProvider { static readonly COMPONENT = 'mmaModChoice'; static readonly RESULTS_NOT = 0; static readonly RESULTS_AFTER_ANSWER = 1; static readonly RESULTS_AFTER_CLOSE = 2; static readonly RESULTS_ALWAYS = 3; static readonly PUBLISH_ANONYMOUS = false; static readonly PUBLISH_NAMES = true; /** * Check if results can be seen by a student. The student can see the results if: * - they're always published, OR * - they're published after the choice is closed and it's closed, OR * - they're published after answering and the user has answered. * * @param choice Choice to check. * @param hasAnswered True if user has answered the choice, false otherwise. * @return True if the students can see the results. */ canStudentSeeResults(choice: AddonModChoiceChoice, hasAnswered: boolean): boolean { const now = Date.now(); return choice.showresults === AddonModChoiceProvider.RESULTS_ALWAYS || choice.showresults === AddonModChoiceProvider.RESULTS_AFTER_CLOSE && choice.timeclose && choice.timeclose <= now || choice.showresults === AddonModChoiceProvider.RESULTS_AFTER_ANSWER && hasAnswered; } /** * Delete responses from a choice. * * @param choiceId Choice ID. * @param name Choice name. * @param courseId Course ID the choice belongs to. * @param responses IDs of the answers. If not defined, delete all the answers of the current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: true if response was sent to server, false if stored in device. */ async deleteResponses( choiceId: number, name: string, courseId: number, responses?: number[], siteId?: string, ): Promise<boolean> { siteId = siteId || CoreSites.getCurrentSiteId(); responses = responses || []; // Convenience function to store a message to be synchronized later. const storeOffline = async (): Promise<boolean> => { await AddonModChoiceOffline.saveResponse(choiceId, name, courseId, responses!, true, siteId); return false; }; if (!CoreApp.isOnline()) { // App is offline, store the action. return storeOffline(); } // If there's already a response to be sent to the server, discard it first. await AddonModChoiceOffline.deleteResponse(choiceId, siteId); try { await this.deleteResponsesOnline(choiceId, responses, siteId); return true; } catch (error) { if (CoreUtils.isWebServiceError(error)) { // The WebService has thrown an error, this means that responses cannot be submitted. throw error; } // Couldn't connect to server, store in offline. return storeOffline(); } } /** * Delete responses from a choice. It will fail if offline or cannot connect. * * @param choiceId Choice ID. * @param responses IDs of the answers. If not defined, delete all the answers of the current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when responses are successfully deleted. */ async deleteResponsesOnline(choiceId: number, responses?: number[], siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const params: AddonModChoiceDeleteChoiceResponsesWSParams = { choiceid: choiceId, responses: responses, }; const response = await site.write<CoreStatusWithWarningsWSResponse>('mod_choice_delete_choice_responses', params); // Other errors ocurring. if (response.status === false) { if (response.warnings?.[0]) { throw new CoreWSError(response.warnings[0]); } throw new CoreError('Cannot delete responses.'); } // Invalidate related data. await CoreUtils.ignoreErrors(Promise.all([ this.invalidateOptions(choiceId, site.id), this.invalidateResults(choiceId, site.id), ])); } /** * Get cache key for choice data WS calls. * * @param courseId Course ID. * @return Cache key. */ protected getChoiceDataCacheKey(courseId: number): string { return ROOT_CACHE_KEY + 'choice:' + courseId; } /** * Get cache key for choice options WS calls. * * @param choiceId Choice ID. * @return Cache key. */ protected getChoiceOptionsCacheKey(choiceId: number): string { return ROOT_CACHE_KEY + 'options:' + choiceId; } /** * Get cache key for choice results WS calls. * * @param choiceId Choice ID. * @return Cache key. */ protected getChoiceResultsCacheKey(choiceId: number): string { return ROOT_CACHE_KEY + 'results:' + choiceId; } /** * Get a choice with key=value. If more than one is found, only the first will be returned. * * @param courseId Course ID. * @param key Name of the property to check. * @param value Value to search. * @param options Other options. * @return Promise resolved when the choice is retrieved. */ protected async getChoiceByDataKey( courseId: number, key: string, value: unknown, options: CoreSitesCommonWSOptions = {}, ): Promise<AddonModChoiceChoice> { const site = await CoreSites.getSite(options.siteId); const params: AddonModChoiceGetChoicesByCoursesWSParams = { courseids: [courseId], }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getChoiceDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModChoiceProvider.COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModChoiceGetChoicesByCoursesWSResponse>( 'mod_choice_get_choices_by_courses', params, preSets, ); const currentChoice = response.choices.find((choice) => choice[key] == value); if (currentChoice) { return currentChoice; } throw new CoreError('Choice not found.'); } /** * Get a choice by course module ID. * * @param courseId Course ID. * @param cmId Course module ID. * @param options Other options. * @return Promise resolved when the choice is retrieved. */ getChoice(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModChoiceChoice> { return this.getChoiceByDataKey(courseId, 'coursemodule', cmId, options); } /** * Get a choice by ID. * * @param courseId Course ID. * @param choiceId Choice ID. * @param options Other options. * @return Promise resolved when the choice is retrieved. */ getChoiceById(courseId: number, choiceId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModChoiceChoice> { return this.getChoiceByDataKey(courseId, 'id', choiceId, options); } /** * Get choice options. * * @param choiceId Choice ID. * @param options Other options. * @return Promise resolved with choice options. */ async getOptions(choiceId: number, options: CoreCourseCommonModWSOptions = {}): Promise<AddonModChoiceOption[]> { const site = await CoreSites.getSite(options.siteId); const params: AddonModChoiceGetChoiceOptionsWSParams = { choiceid: choiceId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getChoiceOptionsCacheKey(choiceId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModChoiceProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModChoiceGetChoiceOptionsWSResponse>( 'mod_choice_get_choice_options', params, preSets, ); return response.options; } /** * Get choice results. * * @param choiceId Choice ID. * @param options Other options. * @return Promise resolved with choice results. */ async getResults(choiceId: number, options: CoreCourseCommonModWSOptions = {}): Promise<AddonModChoiceResult[]> { const site = await CoreSites.getSite(options.siteId); const params: AddonModChoiceGetChoiceResultsWSParams = { choiceid: choiceId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getChoiceOptionsCacheKey(choiceId), component: AddonModChoiceProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModChoiceGetChoiceResultsWSResponse>( 'mod_choice_get_choice_results', params, preSets, ); return response.options; } /** * Invalidate choice data. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateChoiceData(courseId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getChoiceDataCacheKey(courseId)); } /** * Invalidate the prefetched content. * * @param moduleId The module ID. * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when data is invalidated. */ async invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); const choice = await this.getChoice(courseId, moduleId); await Promise.all([ this.invalidateChoiceData(courseId), this.invalidateOptions(choice.id), this.invalidateResults(choice.id), CoreFilepool.invalidateFilesByComponent(siteId, AddonModChoiceProvider.COMPONENT, moduleId), ]); } /** * Invalidate choice options. * * @param choiceId Choice ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateOptions(choiceId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getChoiceOptionsCacheKey(choiceId)); } /** * Invalidate choice results. * * @param choiceId Choice ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateResults(choiceId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getChoiceResultsCacheKey(choiceId)); } /** * Report the choice as being viewed. * * @param id Choice ID. * @param name Name of the choice. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ logView(id: number, name?: string, siteId?: string): Promise<void> { const params: AddonModChoiceViewChoiceWSParams = { choiceid: id, }; return CoreCourseLogHelper.logSingle( 'mod_choice_view_choice', params, AddonModChoiceProvider.COMPONENT, id, name, 'choice', {}, siteId, ); } /** * Send a response to a choice to Moodle. * * @param choiceId Choice ID. * @param name Choice name. * @param courseId Course ID the choice belongs to. * @param responses IDs of selected options. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: true if response was sent to server, false if stored in device. */ async submitResponse(choiceId: number, name: string, courseId: number, responses: number[], siteId?: string): Promise<boolean> { siteId = siteId || CoreSites.getCurrentSiteId(); // Convenience function to store a message to be synchronized later. const storeOffline = async (): Promise<boolean> => { await AddonModChoiceOffline.saveResponse(choiceId, name, courseId, responses, false, siteId); return false; }; if (!CoreApp.isOnline()) { // App is offline, store the action. return storeOffline(); } // If there's already a response to be sent to the server, discard it first. await AddonModChoiceOffline.deleteResponse(choiceId, siteId); try { await this.submitResponseOnline(choiceId, responses, siteId); return true; } catch (error) { if (CoreUtils.isWebServiceError(error)) { // The WebService has thrown an error, this means that responses cannot be submitted. throw error; } // Couldn't connect to server, store it offline. return storeOffline(); } } /** * Send a response to a choice to Moodle. It will fail if offline or cannot connect. * * @param choiceId Choice ID. * @param responses IDs of selected options. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when responses are successfully submitted. */ async submitResponseOnline(choiceId: number, responses: number[], siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const params: AddonModChoiceSubmitChoiceResponseWSParams = { choiceid: choiceId, responses: responses, }; await site.write('mod_choice_submit_choice_response', params); // Invalidate related data. await CoreUtils.ignoreErrors(Promise.all([ this.invalidateOptions(choiceId, siteId), this.invalidateResults(choiceId, siteId), ])); } } export const AddonModChoice = makeSingleton(AddonModChoiceProvider); /** * Params of mod_choice_get_choices_by_courses WS. */ export type AddonModChoiceGetChoicesByCoursesWSParams = { courseids?: number[]; // Array of course ids. }; /** * Data returned by mod_choice_get_choices_by_courses WS. */ export type AddonModChoiceGetChoicesByCoursesWSResponse = { choices: AddonModChoiceChoice[]; warnings?: CoreWSExternalWarning[]; }; /** * Choice returned by mod_choice_get_choices_by_courses. */ export type AddonModChoiceChoice = { id: number; // Choice instance id. coursemodule: number; // Course module id. course: number; // Course id. name: string; // Choice name. intro: string; // The choice intro. introformat: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). introfiles?: CoreWSExternalFile[]; // @since 3.2. publish?: boolean; // If choice is published. showresults?: number; // 0 never, 1 after answer, 2 after close, 3 always. display?: number; // Display mode (vertical, horizontal). allowupdate?: boolean; // Allow update. allowmultiple?: boolean; // Allow multiple choices. showunanswered?: boolean; // Show users who not answered yet. includeinactive?: boolean; // Include inactive users. limitanswers?: boolean; // Limit unswers. timeopen?: number; // Date of opening validity. timeclose?: number; // Date of closing validity. showpreview?: boolean; // Show preview before timeopen. timemodified?: number; // Time of last modification. completionsubmit?: boolean; // Completion on user submission. showavailable?: boolean; // Show available spaces. @since 3.10 section?: number; // Course section id. visible?: boolean; // Visible. groupmode?: number; // Group mode. groupingid?: number; // Group id. }; /** * Params of mod_choice_delete_choice_responses WS. */ export type AddonModChoiceDeleteChoiceResponsesWSParams = { choiceid: number; // Choice instance id. responses?: number[]; // Array of response ids, empty for deleting all the current user responses. }; /** * Params of mod_choice_get_choice_options WS. */ export type AddonModChoiceGetChoiceOptionsWSParams = { choiceid: number; // Choice instance id. }; /** * Data returned by mod_choice_get_choice_options WS. */ export type AddonModChoiceGetChoiceOptionsWSResponse = { options: AddonModChoiceOption[]; // Options. warnings?: CoreWSExternalWarning[]; }; /** * Option returned by mod_choice_get_choice_options. */ export type AddonModChoiceOption = { id: number; // Option id. text: string; // Text of the choice. maxanswers: number; // Maximum number of answers. displaylayout: boolean; // True for orizontal, otherwise vertical. countanswers: number; // Number of answers. checked: boolean; // We already answered. disabled: boolean; // Option disabled. }; /** * Params of mod_choice_get_choice_results WS. */ export type AddonModChoiceGetChoiceResultsWSParams = { choiceid: number; // Choice instance id. }; /** * Data returned by mod_choice_get_choice_results WS. */ export type AddonModChoiceGetChoiceResultsWSResponse = { options: AddonModChoiceResult[]; warnings?: CoreWSExternalWarning[]; }; /** * Result returned by mod_choice_get_choice_results. */ export type AddonModChoiceResult = { id: number; // Choice instance id. text: string; // Text of the choice. maxanswer: number; // Maximum number of answers. userresponses: { userid: number; // User id. fullname: string; // User full name. profileimageurl: string; // Profile user image url. answerid?: number; // Answer id. timemodified?: number; // Time of modification. }[]; numberofuser: number; // Number of users answers. percentageamount: number; // Percentage of users answers. }; /** * Params of mod_choice_view_choice WS. */ export type AddonModChoiceViewChoiceWSParams = { choiceid: number; // Choice instance id. }; /** * Params of mod_choice_submit_choice_response WS. */ export type AddonModChoiceSubmitChoiceResponseWSParams = { choiceid: number; // Choice instance id. responses: number[]; // Array of response ids. }; declare module '@singletons/events' { /** * Augment CoreEventsData interface with events specific to this service. * * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { [AddonModChoiceSyncProvider.AUTO_SYNCED]: AddonModChoiceAutoSyncData; } }
the_stack
import assert = require('assert'); import argparse = require('argparse'); import colors = require('colors'); import fs = require('fs'); import mkdirp = require('mkdirp'); import path = require('path'); import underscore = require('underscore'); import xdiff = require('xdiff'); var qunit = require('qunitjs'); import env = require('./base/env'); /** Interface for testing the values of objects during * a test. * * See http://api.qunitjs.com/category/assert/ * * The assert methods throw if an assertion fails. The test harness catches such * failures and outputs diagnostics. */ export interface Assert { notEqual<T>(actual: T, notExpected: T, message?: string): void; equal<T>(actual: T, expected: T, message?: string): void; deepEqual<T>(actual: T, expected: T, message?: string): void; strictEqual<T>(actual: T, expected: T, message?: string): void; ok<T>(result: T, message?: string): void; throws<T>(func: Function, expected?: T, message?: string): void; } interface TestCase { name: string; testFunc: (assert: Assert) => void; } var testList: TestCase[] = []; var testStartTimer: NodeJS.Timer; function scheduleAutoStart() { if (!testStartTimer) { testStartTimer = global.setTimeout(() => { start(); }, 10); } } let sourceCache: Map<string, string[]>; function extractLines(filePath: string, start: number, end: number) { if (!sourceCache) { sourceCache = new Map<string, string[]>(); } if (!sourceCache.has(filePath)) { let content = fs.readFileSync(filePath).toString('utf-8'); let lines = content.split('\n'); sourceCache.set(filePath, lines); } return sourceCache.get(filePath).slice(start, end); } // returns the root directory of the parent NPM // module containing 'filePath' function packageRoot(filePath: string) { if (filePath.length <= 1 || filePath[0] !== '/') { return ''; } let dirPath = path.dirname(filePath); while (dirPath !== '/' && !fs.existsSync(`${dirPath}/package.json`)) { dirPath = path.dirname(dirPath); } return dirPath; } /** Takes a stack trace returned by Error.stack and returns * a more easily readable version as an array of strings. * * - Path names are expressed relative to the NPM module * containing the current directory. * - Context snippets are added for each stack frame */ function formatStack(trace: string) { assert(trace); try { let traceLines = trace.split('\n'); let rootPath = packageRoot(__filename); let locationRegex = /([^() ]+):([0-9]+):([0-9]+)/; let formattedLines: string[] = []; for (let i = 0; i < traceLines.length; i++) { let line = traceLines[i].trim(); let locationMatch = line.match(locationRegex); if (locationMatch) { let filePath = locationMatch[1]; let lineNumber = parseInt(locationMatch[2]); let context = ''; try { if (filePath[0] === '/') { context = extractLines( filePath, lineNumber - 1, lineNumber )[0].trim(); } } catch (e) { context = '<source unavailable>'; } formattedLines.push( ` ${path.relative(rootPath, filePath)}:${lineNumber}: ${ context }` ); } else { formattedLines.push(` ${line}`); } } return formattedLines; } catch (ex) { return [`<failed to format stack: ${ex.toString()}>`].concat( ex.stack.split('\n') ); } } /** Add a test which either completes synchronously or returns * a promise. * * See qunit.test() */ export function addTest(name: string, testFunc: (assert: Assert) => void) { testList.push({ name, testFunc, }); scheduleAutoStart(); } export interface TestStartParams { name: string; module: string; } /** Add a setup function to invoke before each test case */ export function beforeTest(func: (details?: TestStartParams) => void) { qunit.testStart(func); } /** Registers a teardown function to be executed once all test cases * have finished. */ export function teardownSuite(func: () => void) { qunit.done(func); } interface AssertionResult { result: boolean; actual: Object; expected: Object; message: string; source?: string; module: string; name: string; } interface TestResult { name: string; module: string; failed: number; passed: number; total: number; runtime: number; } interface TestSuiteResult { failed: number; passed: number; total: number; runtime: number; } function requireNodeVersion(version: string) { var semver = require('semver'); if (env.isNodeJS() && semver.lt(process.version, version)) { console.error('Node version %s or later is required', version); process.exit(1); } } /** Start the test suite. The default mode is to run tests added with * addTest(). * * The test runner has a command-line parser which provides options * to list available tests, filter which tests are run and adjust * the verbosity of test output. * * @param args Command-line arguments for the test. */ export function start(args?: string[]) { requireNodeVersion('0.12.0'); if (!args && env.isNodeJS()) { args = process.argv.slice(2); } cancelAutoStart(); var parser = new argparse.ArgumentParser({ description: 'Unit test suite', }); parser.addArgument(['-f', '--filter'], { action: 'store', nargs: 1, dest: 'filter', help: 'Run only tests whose name matches FILTER', }); parser.addArgument(['-l', '--list'], { action: 'store', nargs: 0, dest: 'list', help: 'List names of available tests', }); parser.addArgument(['-v', '--verbose'], { action: 'store', nargs: 0, dest: 'verbose', }); var opts = parser.parseArgs(args); var tests = testList; if (opts.filter) { tests = tests.filter(testCase => { return testCase.name.indexOf(opts.filter) != -1; }); if (opts.verbose) { var testNames = tests.map(testCase => { return '"' + testCase.name + '"'; }); console.log( 'Running %d matching tests: %s', tests.length, testNames.join(', ') ); } } if (opts.list) { tests.forEach(testCase => { console.log(testCase.name); }); } else { console.log('START: %s', path.basename(process.argv[1])); run(tests); } } /** Returns the path to a temporary data directory for * use by the current test suite. */ export function tempDir() { let tmpDir: string; if (process.env.TMPDIR) { tmpDir = process.env.TMPDIR; } else { tmpDir = '/tmp'; } let testSuiteName = path.basename(process.argv[1]); let dirPath = `${tmpDir}/passcards-tests/${testSuiteName}`; mkdirp.sync(dirPath); return dirPath; } function run(tests: TestCase[]) { // randomize ordering of tests tests = underscore(tests).shuffle(); tests.forEach(testCase => { qunit.test(testCase.name, testCase.testFunc); }); if (!timeout()) { setTimeout(3000); } qunit.log((details: AssertionResult) => { if (!details.result) { let message = details.message || 'Assert failed'; console.log( colors.red( `ERROR: ${message}, actual: ${details.actual}, expected ${ details.expected }` ) ); if (details.source) { console.log( colors.yellow(formatStack(details.source).join('\n')) ); } } }); qunit.testDone((result: TestResult) => { const FORMAT_STR = '%s (%sms)'; let formatStr: string; if (result.passed === result.total) { formatStr = colors.green(`PASS: ${FORMAT_STR}`); } else { formatStr = colors.red(`FAIL: ${FORMAT_STR}`); } console.log(formatStr, result.name, result.runtime); }); qunit.done((result: TestSuiteResult) => { let colorFunc = result.failed === 0 ? colors.green : colors.yellow; console.log( colorFunc('END: Assertions: %d, Failed: %d, Duration: %dms'), result.total, result.failed, result.runtime ); if (env.isNodeJS()) { if (result.failed > 0) { process.on('exit', () => { process.exit(1); }); } } }); if (!env.isBrowser()) { qunit.load(); } } /** Compares two values (objects or arrays) and outputs a diff * between 'a' and 'b', excluding * any keys which are expected to have been added in 'b' and * any keys which are expected to have been removed in 'b' * expectedAdditions and expectedDeletions are arrays of '/'-separated paths * beginning with 'root/' */ export function compareObjects( a: any, b: any, expectedAdditions?: string[], expectedDeletions?: string[] ): any[] { var diff = xdiff.diff(a, b); if (!diff) { // objects are exactly equal return []; } expectedAdditions = expectedAdditions || []; expectedDeletions = expectedDeletions || []; return diff.filter((change: any[]) => { var type: string = change[0]; var path: string = change[1].join('/'); if (type == 'set' && expectedAdditions.indexOf(path) != -1) { return false; } else if (type == 'del' && expectedDeletions.indexOf(path) != -1) { return false; } return true; }); } /** Check that two objects or arrays are equal. * If the objects or arrays are not equal, print a diff between the two. * If @p properties is specified, only the listed properties are compared * between objects @p a and @p b. */ export function assertEqual( assert: Assert, a: any, b: any, properties?: string[], excludeProperties?: string[] ) { if (properties) { a = underscore.pick.apply(null, [a].concat(<any[]>properties)); b = underscore.pick.apply(null, [b].concat(<any[]>properties)); } else if (excludeProperties) { a = underscore.omit.apply(null, [a].concat(<any[]>excludeProperties)); b = underscore.omit.apply(null, [b].concat(<any[]>excludeProperties)); } var diff = compareObjects(a, b); if (diff.length > 0) { console.log(diff); } assert.equal(diff.length, 0, 'Check objects are equal'); } /** Cancel any pending auto-start of the test suite. * This will prevent tests auto-starting after being * added with addTest() or addTest() */ export function cancelAutoStart() { if (testStartTimer) { clearTimeout(testStartTimer); testStartTimer = null; } } /** Set the global default timeout for individual test cases. */ export function setTimeout(timeoutMs: number) { qunit.config.testTimeout = timeoutMs; } /** Returns the global default timeout for individual test * cases or undefined to use a default value. */ export function timeout() { return qunit.config.testTimeout; }
the_stack
import { Nullable } from "../../../shared/types"; import * as React from "react"; import { Classes, ButtonGroup, Button, Tabs, TabId, Tab } from "@blueprintjs/core"; import { Terminal } from "xterm"; import { FitAddon } from 'xterm-addon-fit'; import { Logger, Observable } from "babylonjs"; import { Icon } from "../gui/icon"; import { Editor } from "../editor"; export enum ConsoleLogType { /** * Just for information. */ Info = 0, /** * Shows a warning. */ Warning, /** * Shows an error. */ Error, /** * Just adds a message in its raw form. */ Raw, } export enum ConsoleLayer { /** * Defines the layer containing all common logs. */ Common = 0, /** * Defines the layer containing all the typescript logs. */ TypeScript, /** * Defines the layer containing all the webpack logs. */ WebPack, } export interface IConsoleProps { /** * The editor reference. */ editor: Editor; } export interface IConsoleState { /** * Defines the current Id of the active tab. */ tabId: TabId; /** * Defines the current width in pixels of the panel. */ width: number; /** * Defines the current height in pixels of the panel. */ height: number; } export interface IConsoleLog { /** * The type of the message. */ type: ConsoleLogType; /** * The message in the log. */ message: string; /** * Defines the layer where to write the message (log). */ layer?: ConsoleLayer; /** * Defines wether or not a separator should be drawn. */ separator?: boolean; } export class Console extends React.Component<IConsoleProps, IConsoleState> { private _terminalTypeScript: Nullable<Terminal> = null; private _terminalWebPack: Nullable<Terminal> = null; private _fitAddonCommon: FitAddon = new FitAddon(); private _fitAddonWebPack: FitAddon = new FitAddon(); private _commonDiv: Nullable<HTMLDivElement> = null; private _terminalTypeScriptDiv: Nullable<HTMLDivElement> = null; private _terminalWebPackDiv: Nullable<HTMLDivElement> = null; private _refHandler = { getCommonDiv: (ref: HTMLDivElement) => this._commonDiv = ref, getTypeScriptDiv: (ref: HTMLDivElement) => this._terminalTypeScriptDiv = ref, getWebPackDiv: (ref: HTMLDivElement) => this._terminalWebPackDiv = ref, }; /** * Notifies all listeners that the logs have been resized. */ public onResizeObservable: Observable<void> = new Observable<void>(); /** * Constructor. * @param props the component's props. */ public constructor(props: IConsoleProps) { super(props); props.editor.console = this; this.state = { tabId: "common", width: 1, height: 1 }; } /** * Renders the component. */ public render(): React.ReactNode { return ( <div style={{ width: "100%", height: "100%", overflow: "hidden" }}> <div className={Classes.FILL} key="materials-toolbar" style={{ width: "100%", height: "25px", backgroundColor: "#333333", borderRadius: "10px", marginTop: "5px" }}> <ButtonGroup> <Button key="clear" icon={<Icon src="recycle.svg" />} small={true} text="Clear" onClick={() => this.clear(this.state.tabId)} /> </ButtonGroup> </div> <Tabs animate={true} key="console-tabs" renderActiveTabPanelOnly={false} vertical={false} children={[ <Tab id="common" title="Common" key="common" panel={<div ref={this._refHandler.getCommonDiv} key="common-div" className="bp3-code-block" style={{ width: this.state.width, height: this.state.height, marginTop: "6px", overflow: "auto" }}></div>} />, <Tab id="typescript" title="TypeScript" key="typescript" panel={<div ref={this._refHandler.getTypeScriptDiv} key="typescript-div" style={{ width: "100%", height: "100%", marginTop: "6px" }}></div>} />, <Tab id="webpack" title="WebPack" key="webpack" panel={<div ref={this._refHandler.getWebPackDiv} key="webpack-div" style={{ width: "100%", height: "100%", marginTop: "6px" }}></div>} />, ]} onChange={(id) => this.setActiveTab(id)} selectedTabId={this.state.tabId} ></Tabs> </div> ); } /** * Called on the component did mount. */ public componentDidMount(): void { if (!this._commonDiv || !this._terminalTypeScriptDiv || !this._terminalWebPackDiv) { return; } // Create terminals this._terminalWebPack = this._createTerminal(this._terminalWebPackDiv, this._fitAddonWebPack); this._terminalTypeScript = this._createTerminal(this._terminalTypeScriptDiv, this._fitAddonCommon); this.logInfo("Console ready.", ConsoleLayer.Common); this.logInfo("Console ready.", ConsoleLayer.TypeScript); this.logInfo("Console ready.", ConsoleLayer.WebPack); } /** * Called on the component will unmount. */ public componentWillUnmount(): void { if (this._terminalTypeScript) { this._terminalTypeScript.dispose(); } if (this._terminalWebPack) { this._terminalWebPack.dispose(); } this._fitAddonCommon.dispose(); this._fitAddonWebPack.dispose(); } /** * Called on the panel has been resized. */ public resize(): void { setTimeout(() => { const size = this.props.editor.getPanelSize("console"); if (this._terminalTypeScriptDiv) { this._terminalTypeScriptDiv.style.width = `${size.width}px`; this._terminalTypeScriptDiv.style.height = `${size.height - 80}px`; } if (this._terminalWebPackDiv) { this._terminalWebPackDiv.style.width = `${size.width}px`; this._terminalWebPackDiv.style.height = `${size.height - 80}px`; } switch (this.state.tabId) { case "common": this.setState({ width: size.width, height: size.height - 80 }); break; case "typescript": this._terminalTypeScript?.resize(1, 1); this._fitAddonCommon.fit(); break; case "webpack": this._terminalWebPack?.resize(1, 1); this._fitAddonWebPack.fit(); break; } this.onResizeObservable.notifyObservers(); }, 0); } /** * Returns the terminal according to the given layer type. * @param type defines the type of terminal to get. */ public getTerminalByType(type: ConsoleLayer): Nullable<Terminal> { switch (type) { case ConsoleLayer.TypeScript: return this._terminalTypeScript; case ConsoleLayer.WebPack: return this._terminalWebPack; default: return null; } } /** * Logs the given message as info. * @param message defines the message to log as info. * @param layer defines the layer where to draw the output. */ public logInfo(message: string, layer?: ConsoleLayer): Nullable<HTMLParagraphElement> { return this._addLog({ type: ConsoleLogType.Info, message, layer }); } /** * Logs the given message as warning. * @param message the message to log as warning. * @param layer defines the layer where to draw the output. */ public logWarning(message: string, layer?: ConsoleLayer): Nullable<HTMLParagraphElement> { return this._addLog({ type: ConsoleLogType.Warning, message, layer }); } /** * Logs the given message as error. * @param message the message to log as error. * @param layer defines the layer where to draw the output. */ public logError(message: string, layer?: ConsoleLayer): Nullable<HTMLParagraphElement> { return this._addLog({ type: ConsoleLogType.Error, message, layer }); } /** * Logs the given message in its raw form. * @param message the message to log directly. * @param layer defines the layer where to draw the output. */ public logRaw(message: string, layer?: ConsoleLayer): void { this._addLog({ type: ConsoleLogType.Raw, message, layer }); } /** * Logs the given message using separators. Allows to create sections in logs. * @param message defines the message to log directly. */ public logSection(message: string): void { this._addLog({ type: ConsoleLogType.Info, message, separator: true }); } /** * Sets the newly active tab. * @param tabId defines the id of the tab to set as active. */ public setActiveTab(tabId: "common" | "webpack" | TabId): void { this.setState({ tabId }, () => this.resize()); } /** * Clears the terminal containing in the tab identified by the given tab Id. * @param tabId defines the id of the tab to clear. */ public clear(tabId: TabId): void { switch (tabId) { case "common": this._commonDiv && (this._commonDiv.innerHTML = ""); break; case "typescript": this._terminalTypeScript?.clear(); break; case "webpack": this._terminalWebPack?.clear(); break; default: break; } } /** * Adds the given log to the editor. */ private _addLog(log: IConsoleLog): Nullable<HTMLParagraphElement> { log.layer = log.layer ?? ConsoleLayer.Common; // Common if (log.layer === ConsoleLayer.Common) { if (!this._commonDiv) { return null; } const p = document.createElement("p"); p.style.marginBottom = "0px"; p.style.whiteSpace = "nowrap"; if (log.separator) { this._commonDiv.appendChild(document.createElement("hr")); } switch (log.type) { case ConsoleLogType.Info: p.innerText = `[INFO]: ${log.message}`; // console.info(log.message); break; case ConsoleLogType.Warning: p.innerText = `[WARN]: ${log.message}`; p.style.color = "yellow"; console.warn(log.message); break; case ConsoleLogType.Error: p.innerText = `[ERROR]: ${log.message}`; p.style.color = "red"; console.warn(log.message); break; } this._commonDiv.appendChild(p); if (log.separator) { this._commonDiv.appendChild(document.createElement("hr")); } this._commonDiv.scrollTop = this._commonDiv.scrollHeight + 25; return p; } // Terminal const terminal = log.layer === ConsoleLayer.TypeScript ? this._terminalTypeScript : this._terminalWebPack; if (!terminal) { return null; } switch (log.type) { case ConsoleLogType.Info: terminal.writeln(`[INFO]: ${log.message}`); // console.info(log.message); break; case ConsoleLogType.Warning: terminal.writeln(`[WARN]: ${log.message}`); console.warn(log.message); break; case ConsoleLogType.Error: terminal.writeln(`[ERROR]: ${log.message}`); console.error(log.message); break; case ConsoleLogType.Raw: terminal.write(log.message); // console.log(log.message.trim()); break; } return null; } /** * Creates an ew terminal opened in the given div HTML element. */ private _createTerminal(terminalDiv: HTMLDivElement, addon: FitAddon): Terminal { // Create terminal const terminal = new Terminal({ fontFamily: "Consolas, 'Courier New', monospace", fontSize: 12, fontWeight: "normal", cursorStyle: "block", cursorWidth: 1, drawBoldTextInBrightColors: true, fontWeightBold: "bold", letterSpacing: -4, // cols: 80, lineHeight: 1, rendererType: "canvas", allowTransparency: true, theme: { background: "#222222", }, }); terminal.loadAddon(addon); terminal.open(terminalDiv); return terminal; } /** * Overrides the current BabylonJS Logger class. */ public overrideLogger(): void { const log = Logger.Log; const warn = Logger.Warn; const error = Logger.Error; Logger.Log = (m) => { log(m); this.logInfo(m); } Logger.Warn = (m) => { warn(m); this.logWarning(m); } Logger.Error = (m) => { error(m); this.logError(m); } } }
the_stack
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js'; import '../settings_shared_css.js'; import '../controls/settings_toggle_button.js'; import '../prefs/prefs.js'; import './credit_card_edit_dialog.js'; import './passwords_shared_css.js'; import './payments_list.js'; import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import {CrButtonElement} from 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {SettingsToggleButtonElement} from '../controls/settings_toggle_button.js'; import {loadTimeData} from '../i18n_setup.js'; import {MetricsBrowserProxyImpl, PrivacyElementInteractions} from '../metrics_browser_proxy.js'; import {PersonalDataChangedListener} from './autofill_manager_proxy.js'; import {PaymentsManagerImpl, PaymentsManagerProxy} from './payments_manager_proxy.js'; type DotsCardMenuiClickEvent = CustomEvent<{ creditCard: chrome.autofillPrivate.CreditCardEntry, anchorElement: HTMLElement, }>; declare global { interface HTMLElementEventMap { 'dots-card-menu-click': DotsCardMenuiClickEvent; } } export interface SettingsPaymentsSectionElement { $: { addCreditCard: CrButtonElement, autofillCreditCardToggle: SettingsToggleButtonElement, canMakePaymentToggle: SettingsToggleButtonElement, creditCardSharedMenu: CrActionMenuElement, menuClearCreditCard: HTMLElement, menuEditCreditCard: HTMLElement, menuRemoveCreditCard: HTMLElement, migrateCreditCards: HTMLElement, paymentsList: HTMLElement, }; } const SettingsPaymentsSectionElementBase = I18nMixin(PolymerElement); export class SettingsPaymentsSectionElement extends SettingsPaymentsSectionElementBase { static get is() { return 'settings-payments-section'; } static get template() { return html`{__html_template__}`; } static get properties() { return { prefs: Object, /** * An array of all saved credit cards. */ creditCards: { type: Array, value: () => [], }, /** * An array of all saved UPI IDs. */ upiIds: { type: Array, value: () => [], }, /** * Set to true if user can be verified through FIDO authentication. */ userIsFidoVerifiable_: { type: Boolean, value() { return loadTimeData.getBoolean( 'fidoAuthenticationAvailableForAutofill'); }, }, /** * The model for any credit card related action menus or dialogs. */ activeCreditCard_: Object, showCreditCardDialog_: Boolean, migratableCreditCardsInfo_: String, /** * Whether migration local card on settings page is enabled. */ migrationEnabled_: { type: Boolean, value() { return loadTimeData.getBoolean('migrationEnabled'); }, readOnly: true, }, }; } prefs: {[key: string]: any}; creditCards: Array<chrome.autofillPrivate.CreditCardEntry>; upiIds: Array<string>; private userIsFidoVerifiable_: boolean; private activeCreditCard_: chrome.autofillPrivate.CreditCardEntry|null; private showCreditCardDialog_: boolean; private migratableCreditCardsInfo_: string; private migrationEnabled_: boolean; private activeDialogAnchor_: HTMLElement|null; private paymentsManager_: PaymentsManagerProxy = PaymentsManagerImpl.getInstance(); private setPersonalDataListener_: PersonalDataChangedListener|null = null; constructor() { super(); /** * The element to return focus to; when the currently active dialog is * closed. */ this.activeDialogAnchor_ = null; } ready() { super.ready(); this.addEventListener('save-credit-card', this.saveCreditCard_); this.addEventListener( 'dots-card-menu-click', this.onCreditCardDotsMenuTap_); this.addEventListener( 'remote-card-menu-click', this.onRemoteEditCreditCardTap_); } connectedCallback() { super.connectedCallback(); // Create listener function. const setCreditCardsListener = (cardList: Array<chrome.autofillPrivate.CreditCardEntry>) => { this.creditCards = cardList; }; // Update |userIsFidoVerifiable_| based on the availability of a platform // authenticator. if (window.PublicKeyCredential) { window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() .then(r => { this.userIsFidoVerifiable_ = this.userIsFidoVerifiable_ && r; }); } const setPersonalDataListener: PersonalDataChangedListener = (_addressList, cardList) => { this.creditCards = cardList; }; const setUpiIdsListener = (upiIdList: Array<string>) => { this.upiIds = upiIdList; }; // Remember the bound reference in order to detach. this.setPersonalDataListener_ = setPersonalDataListener; // Request initial data. this.paymentsManager_.getCreditCardList(setCreditCardsListener); this.paymentsManager_.getUpiIdList(setUpiIdsListener); // Listen for changes. this.paymentsManager_.setPersonalDataManagerListener( setPersonalDataListener); // Record that the user opened the payments settings. chrome.metricsPrivate.recordUserAction('AutofillCreditCardsViewed'); } disconnectedCallback() { super.disconnectedCallback(); this.paymentsManager_.removePersonalDataManagerListener( this.setPersonalDataListener_!); this.setPersonalDataListener_ = null; } /** * Opens the credit card action menu. */ private onCreditCardDotsMenuTap_(e: DotsCardMenuiClickEvent) { // Copy item so dialog won't update model on cancel. this.activeCreditCard_ = e.detail.creditCard; this.$.creditCardSharedMenu.showAt(e.detail.anchorElement); this.activeDialogAnchor_ = e.detail.anchorElement; } /** * Handles tapping on the "Add credit card" button. */ private onAddCreditCardTap_(e: Event) { e.preventDefault(); const date = new Date(); // Default to current month/year. const expirationMonth = date.getMonth() + 1; // Months are 0 based. this.activeCreditCard_ = { expirationMonth: expirationMonth.toString(), expirationYear: date.getFullYear().toString(), }; this.showCreditCardDialog_ = true; this.activeDialogAnchor_ = this.$.addCreditCard; } private onCreditCardDialogClose_() { this.showCreditCardDialog_ = false; focusWithoutInk(assert(this.activeDialogAnchor_!)); this.activeDialogAnchor_ = null; this.activeCreditCard_ = null; } /** * Handles tapping on the "Edit" credit card button. */ private onMenuEditCreditCardTap_(e: Event) { e.preventDefault(); if (this.activeCreditCard_!.metadata!.isLocal) { this.showCreditCardDialog_ = true; } else { this.onRemoteEditCreditCardTap_(); } this.$.creditCardSharedMenu.close(); } private onRemoteEditCreditCardTap_() { this.paymentsManager_.logServerCardLinkClicked(); window.open(loadTimeData.getString('manageCreditCardsUrl')); } /** * Handles tapping on the "Remove" credit card button. */ private onMenuRemoveCreditCardTap_() { this.paymentsManager_.removeCreditCard(this.activeCreditCard_!.guid!); this.$.creditCardSharedMenu.close(); this.activeCreditCard_ = null; } /** * Handles tapping on the "Clear copy" button for cached credit cards. */ private onMenuClearCreditCardTap_() { this.paymentsManager_.clearCachedCreditCard(this.activeCreditCard_!.guid!); this.$.creditCardSharedMenu.close(); this.activeCreditCard_ = null; } /** * Handles clicking on the "Migrate" button for migrate local credit * cards. */ private onMigrateCreditCardsClick_() { this.paymentsManager_.migrateCreditCards(); } /** * Records changes made to the "Allow sites to check if you have payment * methods saved" setting to a histogram. */ private onCanMakePaymentChange_() { MetricsBrowserProxyImpl.getInstance().recordSettingsPageHistogram( PrivacyElementInteractions.PAYMENT_METHOD); } /** * Listens for the save-credit-card event, and calls the private API. */ private saveCreditCard_( event: CustomEvent<chrome.autofillPrivate.CreditCardEntry>) { this.paymentsManager_.saveCreditCard(event.detail); } /** * @return Whether the user is verifiable through FIDO authentication. */ private shouldShowFidoToggle_( creditCardEnabled: boolean, userIsFidoVerifiable: boolean): boolean { return creditCardEnabled && userIsFidoVerifiable; } /** * Listens for the enable-authentication event, and calls the private API. */ private setFIDOAuthenticationEnabledState_() { this.paymentsManager_.setCreditCardFIDOAuthEnabledState( this.shadowRoot! .querySelector<SettingsToggleButtonElement>( '#autofillCreditCardFIDOAuthToggle')!.checked); } /** * @return Whether to show the migration button. */ private checkIfMigratable_( creditCards: Array<chrome.autofillPrivate.CreditCardEntry>, creditCardEnabled: boolean): boolean { // If migration prerequisites are not met, return false. if (!this.migrationEnabled_) { return false; } // If credit card enabled pref is false, return false. if (!creditCardEnabled) { return false; } const numberOfMigratableCreditCard = creditCards.filter(card => card.metadata!.isMigratable).length; // Check whether exist at least one local valid card for migration. if (numberOfMigratableCreditCard === 0) { return false; } // Update the display text depends on the number of migratable credit // cards. this.migratableCreditCardsInfo_ = numberOfMigratableCreditCard === 1 ? this.i18n('migratableCardsInfoSingle') : this.i18n('migratableCardsInfoMultiple'); return true; } } declare global { interface HTMLElementTagNameMap { 'settings-payments-section': SettingsPaymentsSectionElement; } } customElements.define( SettingsPaymentsSectionElement.is, SettingsPaymentsSectionElement);
the_stack
declare var Winreg: WinregStatic; interface WinregStatic { /** * Creates a registry object, which provides access to a single registry key. * Note: This class is returned by a call to ```require('winreg')```. * * @public * @class * * @param {@link Options} options - the options * * @example * var Registry = require('winreg') * , autoStartCurrentUser = new Registry({ * hive: Registry.HKCU, * key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' * }); */ new (options: Winreg.Options): Winreg.Registry; /** * Registry hive key HKEY_LOCAL_MACHINE. * Note: For writing to this hive your program has to run with admin privileges. */ HKLM: string; /** * Registry hive key HKEY_CURRENT_USER. */ HKCU: string; /** * Registry hive key HKEY_CLASSES_ROOT. * Note: For writing to this hive your program has to run with admin privileges. */ HKCR: string; /** * Registry hive key HKEY_USERS. * Note: For writing to this hive your program has to run with admin privileges. */ HKU: string; /** * Registry hive key HKEY_CURRENT_CONFIG. * Note: For writing to this hive your program has to run with admin privileges. */ HKCC: string; /** * Collection of available registry hive keys. */ HIVES: Array<string>; /** * Registry value type STRING. * * Values of this type contain a string. */ REG_SZ: string; /** * Registry value type MULTILINE_STRING. * * Values of this type contain a multiline string. */ REG_MULTI_SZ: string; /** * Registry value type EXPANDABLE_STRING. * * Values of this type contain an expandable string. */ REG_EXPAND_SZ: string; /** * Registry value type DOUBLE_WORD. * * Values of this type contain a double word (32 bit integer). */ REG_DWORD: string; /** * Registry value type QUAD_WORD. * * Values of this type contain a quad word (64 bit integer). */ REG_QWORD: string; /** * Registry value type BINARY. * * Values of this type contain a binary value. */ REG_BINARY: string; /** * Registry value type UNKNOWN. * * Values of this type contain a value of an unknown type. */ REG_NONE: string; /** * Collection of available registry value types. */ REG_TYPES: Array<string>; /** * The name of the default value. May be used instead of the empty string literal for better readability. */ DEFAULT_VALUE: string; } declare namespace Winreg { export interface Options { /** * Optional hostname, must start with '\\' sequence. */ host?: string; /** * Optional hive ID, default is HKLM. */ hive?: string; /** * Optional key, default is the root key. */ key?: string; /** * Optional registry hive architecture ('x86' or 'x64'; only valid on Windows 64 Bit Operating Systems). */ arch?: string; } /** * A registry object, which provides access to a single registry key. */ export interface Registry { /** * The hostname. * @readonly */ host: string; /** * The hive id. * @readonly */ hive: string; /** * The registry key name. * @readonly */ key: string; /** * The full path to the registry key. * @readonly */ path: string; /** * The registry hive architecture ('x86' or 'x64'). * @readonly */ arch: string; /** * Creates a new {@link Registry} instance that points to the parent registry key. * @readonly */ parent: Registry; /** * Retrieve all values from this registry key. * @param {valuesCallback} cb - callback function * @param {error=} cb.err - error object or null if successful * @param {array=} cb.items - an array of {@link RegistryItem} objects * @returns {Registry} this registry key object */ values(cb: (err: Error, result: Array<Winreg.RegistryItem>) => void): Registry; /** * Retrieve all subkeys from this registry key. * @param {function (err, items)} cb - callback function * @param {error=} cb.err - error object or null if successful * @param {array=} cb.items - an array of {@link Registry} objects * @returns {Registry} this registry key object */ keys(cb: (err: Error, result: Array<Registry>) => void): Registry; /** * Gets a named value from this registry key. * @param {string} name - the value name, use {@link Registry.DEFAULT_VALUE} or an empty string for the default value * @param {function (err, item)} cb - callback function * @param {error=} cb.err - error object or null if successful * @param {RegistryItem=} cb.item - the retrieved registry item * @returns {Registry} this registry key object */ get(name: string, cb: (err: Error, result: Winreg.RegistryItem) => void): Registry; /** * Sets a named value in this registry key, overwriting an already existing value. * @param {string} name - the value name, use {@link Registry.DEFAULT_VALUE} or an empty string for the default value * @param {string} type - the value type * @param {string} value - the value * @param {function (err)} cb - callback function * @param {error=} cb.err - error object or null if successful * @returns {Registry} this registry key object */ set(name: string, type: string, value: string, cb: (err: Error) => void): Registry; /** * Remove a named value from this registry key. If name is empty, sets the default value of this key. * Note: This key must be already existing. * @param {string} name - the value name, use {@link Registry.DEFAULT_VALUE} or an empty string for the default value * @param {function (err)} cb - callback function * @param {error=} cb.err - error object or null if successful * @returns {Registry} this registry key object */ remove(name: string, cb: (err: Error) => void): Registry; /** * Remove all subkeys and values (including the default value) from this registry key. * @param {function (err)} cb - callback function * @param {error=} cb.err - error object or null if successful * @returns {Registry} this registry key object */ clear(cb: (err: Error) => void): Registry; /** * Alias for the clear method to keep it backward compatible. * @method * @deprecated Use {@link Registry#clear} or {@link Registry#destroy} in favour of this method. * @param {function (err)} cb - callback function * @param {error=} cb.err - error object or null if successful * @returns {Registry} this registry key object */ erase(cb: (err: Error) => void): Registry; /** * Delete this key and all subkeys from the registry. * @param {function (err)} cb - callback function * @param {error=} cb.err - error object or null if successful * @returns {Registry} this registry key object */ destroy(cb: (err: Error) => void): Registry; /** * Create this registry key. Note that this is a no-op if the key already exists. * @param {function (err)} cb - callback function * @param {error=} cb.err - error object or null if successful * @returns {Registry} this registry key object */ create(cb: (err: Error) => void): Registry; /** * Checks if this key already exists. * @param {function (err, exists)} cb - callback function * @param {error=} cb.err - error object or null if successful * @param {boolean=} cb.exists - true if a registry key with this name already exists * @returns {Registry} this registry key object */ keyExists(cb: (err: Error, exists: boolean) => void): Registry; /** * Checks if a value with the given name already exists within this key. * @param {string} name - the value name, use {@link Registry.DEFAULT_VALUE} or an empty string for the default value * @param {function (err, exists)} cb - callback function * @param {error=} cb.err - error object or null if successful * @param {boolean=} cb.exists - true if a value with the given name was found in this key * @returns {Registry} this registry key object */ valueExists(name: string, cb: (err: Error, exists: boolean) => void): Registry; } /** * A single registry value record. * Objects of this type are created internally and returned by methods of {@link Registry} objects. */ export interface RegistryItem { /** * The hostname. * @readonly */ host: string; /** * The hive id. * @readonly */ hive: string; /** * The registry key. * @readonly */ key: string; /** * The value name. * @readonly */ name: string; /** * The value type. * @readonly */ type: string; /** * The value. * @readonly */ value: string; /** * The hive architecture. * @readonly */ arch: string; } } declare module "winreg" { export = Winreg; }
the_stack
import { Component } from 'vue-property-decorator'; import _ from 'lodash'; import template from './visual-editor.html'; import { injectNodeTemplate } from '@/components/node'; import SubsetNode from '@/components/subset-node/subset-node'; import { VisualProperties, VisualPropertyType, isNumericalVisual } from '@/data/visuals'; import { SubsetPackage } from '@/data/package'; import FormSelect from '@/components/form-select/form-select'; import FormInput from '@/components/form-input/form-input'; import ColorInput from '@/components/color-input/color-input'; import ColumnSelect from '@/components/column-select/column-select'; import ColorScaleSelect from '@/components/color-scale-select/color-scale-select'; import ColorScaleDisplay from '@/components/color-scale-display/color-scale-display'; import { getScale, GetScaleOptions, OrdinalScaleType } from '@/components/visualization'; import { getColorScale } from '@/common/color-scale'; import * as history from './history'; import { NODE_CONTENT_PADDING_PX } from '@/common/constants'; import { ValueType } from '@/data/parser'; export enum VisualEditorMode { ASSIGNMENT = 'assignment', ENCODING = 'encoding', } interface NullableVisualProperties { color: string | null; border: string | null; size: number | null; width: number | null; opacity: number | null; [prop: string]: number | string | null; } interface VisualEditorSave { mode: VisualEditorMode; visuals: NullableVisualProperties; encoding: EncodingParams; } interface EncodingParams { column: number | null; type: VisualPropertyType; colorScaleId: string; numericalScale: { min: number; max: number; }; } @Component({ template: injectNodeTemplate(template), components: { FormSelect, ColumnSelect, ColorScaleSelect, FormInput, ColorInput, ColorScaleDisplay, }, }) export default class VisualEditor extends SubsetNode { protected NODE_TYPE = 'visual-editor'; protected RESIZABLE = true; protected DEFAULT_WIDTH = 60; protected DEFAULT_HEIGHT = 60; private mode: VisualEditorMode = VisualEditorMode.ASSIGNMENT; private visuals: NullableVisualProperties = { color: null, border: null, size: null, width: null, opacity: null, }; private encoding: EncodingParams = { column: null, type: VisualPropertyType.COLOR, colorScaleId: 'red-green' , numericalScale: { min: 1, max: 1 }, }; get modeOptions(): SelectOption[] { return [ { label: 'Assignment', value: VisualEditorMode.ASSIGNMENT }, { label: 'Encoding', value: VisualEditorMode.ENCODING }, ]; } get encodingTypeOptions(): SelectOption[] { return [ { label: 'Color', value: VisualPropertyType.COLOR }, { label: 'Border', value: VisualPropertyType.BORDER }, { label: 'Size', value: VisualPropertyType.SIZE }, { label: 'Width', value: VisualPropertyType.WIDTH }, { label: 'Opacity', value: VisualPropertyType.OPACITY }, ]; } get isNumericalEncoding(): boolean { return this.encoding.column !== null && isNumericalVisual(this.encoding.type); } get displayStyle() { let width = this.visuals.width ? Math.min(this.visuals.width, this.width / 2) : 0; if (this.visuals.border && width === 0) { width = 1; // If the border color is set, show at least 1px of border. } const baseSize = Math.min(this.width, this.height) - NODE_CONTENT_PADDING_PX * 2; const size = this.visuals.size ? // If size is defined, we use the defined size. Math.min(baseSize, this.visuals.size) : // Otherwise we use 75% of node size. baseSize * .75; return { 'background-color': this.visuals.color || '', 'border-color': this.visuals.border || '', 'border-width': width + 'px', 'left': (this.width - size) / 2 + 'px', 'top': (this.height - size) / 2 + 'px', 'width': size + 'px', 'height': size + 'px', 'opacity': this.visuals.opacity || 1, }; } public setMode(mode: VisualEditorMode) { this.mode = mode; this.updateAndPropagate(); } public setVisualsColor(color: string | null) { this.visuals.color = color; this.updateAndPropagate(); } public setVisualsBorder(border: string | null) { this.visuals.border = border; this.updateAndPropagate(); } public setVisualsSize(size: number | null) { this.visuals.size = size; this.updateAndPropagate(); } public setVisualsWidth(width: number | null) { this.visuals.width = width; this.updateAndPropagate(); } public setVisualsOpacity(opacity: number | null) { if (opacity === null) { delete this.visuals.opacity; } else { this.visuals.opacity = opacity; } this.updateAndPropagate(); } public setEncodingColumn(column: number | null) { this.encoding.column = column; this.updateAndPropagate(); } public setEncodingType(type: VisualPropertyType) { this.encoding.type = type; this.updateAndPropagate(); } public setEncodingColorScale(colorScaleId: string) { this.encoding.colorScaleId = colorScaleId; this.updateAndPropagate(); } public setEncodingScaleMin(value: number | null) { this.encoding.numericalScale.min = value || 0; this.updateAndPropagate(); } public setEncodingScaleMax(value: number | null) { this.encoding.numericalScale.max = value || 0; this.updateAndPropagate(); } public getMode(): VisualEditorMode { return this.mode; } public getVisualsAssignment(): NullableVisualProperties { return _.clone(this.visuals); } public getVisualsEncoding(): EncodingParams { return _.clone(this.encoding); } protected onDatasetChange() { this.encoding.column = this.updateColumnOnDatasetChange(this.encoding.column); } protected update() { if (!this.checkDataset()) { return; } this.dye(); } protected created() { this.serializationChain.push((): VisualEditorSave => ({ mode: this.mode, visuals: this.visuals, encoding: this.encoding, })); } protected updateAndPropagate() { this.update(); this.propagate(); } private dye() { let pkg: SubsetPackage; if (this.mode === VisualEditorMode.ASSIGNMENT) { pkg = this.dyeAssignment(); } else { // VisualEditorMode.ENCODING pkg = this.dyeEncoding(); } this.updateOutput(pkg); } private dyeAssignment(): SubsetPackage { const pkg = this.inputPortMap.in.getSubsetPackage().clone(); const visuals = this.removeNullVisuals(this.visuals); // Remove undefined to use _.extend later. _.each(visuals, (value, prop) => { if (visuals[prop] === undefined) { delete visuals[prop]; } }); pkg.getItems().forEach(item => { _.extend(item.visuals, visuals); }); return pkg; } private dyeEncoding(): SubsetPackage { const pkg = this.inputPortMap.in.getSubsetPackage().clone(); if (this.encoding.column === null || (!this.isNumericalEncoding && !this.encoding.colorScaleId)) { return pkg; } const dataset = this.getDataset(); const itemIndices = pkg.getItemIndices(); if (isNumericalVisual(this.encoding.type)) { const scale = getScale( dataset.getColumnType(this.encoding.column), dataset.getDomain(this.encoding.column, itemIndices), [this.encoding.numericalScale.min, this.encoding.numericalScale.max], ); pkg.getItems().forEach(item => { const value = dataset.getCell(item, this.encoding.column as number); _.extend(item.visuals, { [this.encoding.type]: scale(value) }); }); } else { // color visual const colorScale = getColorScale(this.encoding.colorScaleId); // Create a scale that maps dataset values to [0, 1] to be further used by colorScale. let domain; let columnType; let range; const options: GetScaleOptions = { domainMargin: 0 }; if (this.encoding.colorScaleId === 'categorical') { // When the color scale is categorical, we need to use an ordinal scale that maps all distinct domain values // to integers in [0, domain.length). columnType = ValueType.STRING; domain = dataset.getDomainValues(this.encoding.column, itemIndices, true); range = _.range(domain.length); options.ordinal = { type: OrdinalScaleType.ORDINAL }; } else { columnType = dataset.getColumnType(this.encoding.column); domain = dataset.getDomain(this.encoding.column, itemIndices); range = [0, 1]; } const scale = getScale(columnType, domain, range, options); pkg.getItems().forEach(item => { const value = dataset.getCell(item, this.encoding.column as number); const colorScaleValue = scale(value); _.extend(item.visuals, { [this.encoding.type]: colorScale(colorScaleValue) }); }); } return pkg; } // Reset unset falsy properties to undefined to avoid sending falsy values like // color = '' or color = null to the downflow. private removeNullVisuals(visuals: NullableVisualProperties): VisualProperties { const cleanVisuals: VisualProperties = {}; _.each(visuals, (value: string | number | null, prop: string) => { if (value !== null) { cleanVisuals[prop] = value; } }); return cleanVisuals; } private onSelectMode(mode: VisualEditorMode, prevMode: VisualEditorMode) { this.commitHistory(history.selectModeEvent(this, mode, prevMode)); this.setMode(mode); } private onInputVisualsColor(color: string | null, prevColor: string | null) { this.commitHistory(history.inputVisualsColorEvent(this, color, prevColor)); this.setVisualsColor(color); } private onInputVisualsBorder(border: string | null, prevBorder: string | null) { this.commitHistory(history.inputVisualsBorderEvent(this, border, prevBorder)); this.setVisualsBorder(border); } private onInputVisualsSize(size: number | null, prevSize: number | null) { this.commitHistory(history.inputVisualsSizeEvent(this, size, prevSize)); this.setVisualsSize(size); } private onInputVisualsWidth(width: number | null, prevWidth: number | null) { this.commitHistory(history.inputVisualsWidthEvent(this, width, prevWidth)); this.setVisualsWidth(width); } private onInputVisualsOpacity(opacity: number | null, prevOpacity: number | null) { this.commitHistory(history.inputVisualsOpacityEvent(this, opacity, prevOpacity)); this.setVisualsOpacity(opacity); } private onSelectEncodingColumn(column: number, prevColumn: number | null) { this.commitHistory(history.selectEncodingColumnEvent(this, column, prevColumn)); this.setEncodingColumn(column); } private onSelectEncodingType(type: VisualPropertyType, prevType: VisualPropertyType) { this.commitHistory(history.selectEncodingTypeEvent(this, type, prevType)); this.setEncodingType(type); } private onSelectEncodingColorScale(colorScaleId: string, prevColorScaleId: string) { this.commitHistory(history.selectEncodingColorScaleEvent(this, colorScaleId, prevColorScaleId)); this.setEncodingColorScale(colorScaleId); } private onInputEncodingScaleMin(value: number | null, prevValue: number | null) { this.commitHistory(history.inputEncodingScaleMinEvent(this, value, prevValue)); this.setEncodingScaleMin(value); } private onInputEncodingScaleMax(value: number | null, prevValue: number | null) { this.commitHistory(history.inputEncodingScaleMaxEvent(this, value, prevValue)); this.setEncodingScaleMax(value); } }
the_stack
import { Injectable, HostBinding, EventEmitter, Output } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { ProgressWindow } from '../pages/generator/progressWindow/progressWindow.component'; import * as post from 'post-robot'; @Injectable() export class GUIGlobal { //Globals for GUI HTML public generator_tabsVisibilityMap: Object = {}; public generator_settingsVisibilityMap: Object = {}; public generator_settingsMap: Object = {}; public generator_customColorMap: Object = {}; public generator_presets: Object = {}; globalVars: Map<string, any>; electronEvents: Array<any> = []; @HostBinding('class.indigo-pink') materialStyleIndigo: boolean = true; @Output() globalEmitter: EventEmitter<object> = new EventEmitter(); constructor(private http: HttpClient) { this.globalVars = new Map<string, any>([ ["appReady", false], ["appType", null], ["electronAvailable", false], ["webSourceVersion", ""], ["webIsMasterVersion", false], ["generatorSettingsArray", []], ["generatorSettingsObj", {}], ["generatorCosmeticsArray", []], ["generatorCosmeticsObj", {}], ["generatorGoalDistros", []] ]); } globalInit(appType: string) { if (!appType) appType = "generator"; //Generator is the default console.log("APP Type:", appType); this.setGlobalVar("appType", appType); if ((<any>window).electronAvailable) { //Electron/Offline mode if ((<any>window).apiPythonSourceFound) { this.setGlobalVar("electronAvailable", true); console.log("Electron API available"); console.log("Running on OS:", (<any>window).apiPlatform); this.createElectronEvents(); this.electronInit(); } else { console.error("Improper setup, exit GUI"); } } else { //Online/Web mode console.log("Electron API not available, assume web mode"); if (!(<any>window).pythonSourceVersion) { console.error("No python version defined, exit"); return; } this.setGlobalVar("webSourceVersion", (<any>window).pythonSourceVersion); if ((<any>window).pythonSourceIsMasterVersion) this.setGlobalVar("webIsMasterVersion", (<any>window).pythonSourceIsMasterVersion); console.log("Web version: " + (<any>window).pythonSourceVersion + " ; master version:", this.getGlobalVar("webIsMasterVersion")); this.webInit(); } } ngOnDestroy() { if ((<any>window).electronAvailable) { this.destroyElectronEvents(); } } createElectronEvents() { //Electron only var self = this; let maximizedEvent = post.on('window-maximized', function (event) { let res = event.data; if (res == true) self.globalEmitter.emit({ name: "window_maximized" }); else self.globalEmitter.emit({ name: "window_unmaximized" }); }); this.electronEvents.push(maximizedEvent); } createWebEvents() { //Web only var self = this; (<any>window).addEventListener('emscripten_cache_file_found', function (event) { let detail = event.detail; //Update settings entry for cached file and then refresh GUI if (detail) { if (detail.name == "ROM") self.generator_settingsMap["rom"] = "<using cached ROM>"; else if (detail.name == "WAD") self.generator_settingsMap["web_wad_file"] = "<using cached WAD>"; else if (detail.name == "COMMONKEY") self.generator_settingsMap["web_common_key_file"] = "<using cached common key>"; self.globalEmitter.emit({ name: "refresh_gui" }); } }, false); } destroyElectronEvents() { this.electronEvents.forEach(postRobotEvent => { postRobotEvent.cancel(); }); } electronInit() { this.electronLoadGeneratorGUISettings().then(() => { this.setGlobalVar("appReady", true); this.globalEmitter.emit({ name: "init_finished" }); }).catch(err => { console.error("exit due error:", err); }); } webInit() { this.webLoadGeneratorGUISettings().then(() => { this.setGlobalVar("appReady", true); this.globalEmitter.emit({ name: "init_finished" }); }).catch(err => { console.error("exit due error:", err); }); } setGlobalVar(key: string, value: any) { if (this.globalVars.has(key)) { this.globalVars.set(key, value); } } getGlobalVar(key: string) { if (this.globalVars.has(key)) return this.globalVars.get(key); return "error"; } copyToClipboard(content: string) { if (this.getGlobalVar('electronAvailable')) { //Electron post.send(window, 'copyToClipboard', { content: content }).then(event => { console.log('copied to clipboard'); }).catch(err => { console.error(err); }); } else { //Web let selBox = document.createElement('textarea'); selBox.style.position = 'fixed'; selBox.style.left = '0'; selBox.style.top = '0'; selBox.style.opacity = '0'; selBox.value = content; document.body.appendChild(selBox); selBox.focus(); selBox.select(); document.execCommand('copy'); document.body.removeChild(selBox); } } async browseForFile(fileTypes: any) { //Electron only if (!this.getGlobalVar('electronAvailable')) throw Error("electron_not_available"); let event = await post.send(window, 'browseForFile', { fileTypes: fileTypes }); let res = event.data; if (!res || res.length != 1 || !res[0] || res[0].length < 1) throw Error("dialog_cancelled"); return res[0]; } async browseForDirectory() { //Electron only if (!this.getGlobalVar('electronAvailable')) throw Error("electron_not_available"); let event = await post.send(window, 'browseForDirectory'); let res = event.data; if (!res || res.length != 1 || !res[0] || res[0].length < 1) throw Error("dialog_cancelled"); return res[0]; } async createAndOpenPath(path: string) { //Electron only if (!this.getGlobalVar('electronAvailable')) throw Error("electron_not_available"); let event = await post.send(window, 'createAndOpenPath', path); let res = event.data; if (res == true) return true; else throw Error("path_not_opened"); } minimizeWindow() { //Electron only if (!this.getGlobalVar('electronAvailable')) return; post.send(window, 'window-minimize').then(() => { console.log('window minimized'); }).catch(err => { console.error(err); }); } maximizeWindow() { //Electron only if (!this.getGlobalVar('electronAvailable')) return; post.send(window, 'window-maximize').then(() => { console.log('window maximize state updated'); }).catch(err => { console.error(err); }); } async isWindowMaximized() { //Electron only if (!this.getGlobalVar('electronAvailable')) throw Error("electron_not_available"); try { let event = await post.send(window, 'window-is-maximized'); let res = event.data; //console.log("window maximized state:", res); return res; } catch (err) { console.error(err); throw Error(err); } } closeWindow() { //Electron only if (!this.getGlobalVar('electronAvailable')) return; this.saveCurrentSettingsToFile(); setTimeout(() => { post.send(window, 'window-close').then(() => { console.log('window closed'); }).catch(err => { console.error(err); }); }); } async electronLoadGeneratorGUISettings() { var guiSettings = post.send(window, 'getGeneratorGUISettings'); var lastUserSettings = post.send(window, 'getGeneratorGUILastUserSettings'); try { var results = await Promise.all([guiSettings, lastUserSettings]); let res = JSON.parse(results[0].data); let userSettings = results[1].data; if (userSettings) userSettings = JSON.parse(userSettings); this.parseGeneratorGUISettings(res, userSettings); } catch (err) { console.error(err); throw Error(err); } } async webLoadGeneratorGUISettings() { var res = null; var userSettings = null; //Get generator settings if ((<any>window).webGeneratorSettingsMap) { //Master versions on the web pre-define a settings map to use before Angular will load res = (<any>window).webGeneratorSettingsMap; console.log("Settings map is available from the DOM"); } else { //Dev versions on the web request a pre-built settings map from the server at runtime let url = (<any>window).location.protocol + "//" + (<any>window).location.host + "/angular/dev/" + this.getGlobalVar("webSourceVersion").replace(/ /g, "_") + "/utils/settings_list.json"; console.log("Settings map is not available. Request it:", url); res = await this.http.get(url, { responseType: "json" }).toPromise(); } //Get last user settings from browser cache for the appropriate app try { userSettings = localStorage.getItem(this.getGlobalVar("appType") == "generator" ? "generatorSettings_" + this.getGlobalVar("webSourceVersion") : "patcherSettings_" + this.getGlobalVar("webSourceVersion")); if (userSettings && userSettings.length > 0) { userSettings = JSON.parse(userSettings); } else { //Try the opposite app type to see if a cached settings map is available there userSettings = localStorage.getItem(this.getGlobalVar("appType") == "generator" ? "patcherSettings_" + this.getGlobalVar("webSourceVersion") : "generatorSettings_" + this.getGlobalVar("webSourceVersion")); if (userSettings && userSettings.length > 0) { userSettings = JSON.parse(userSettings); } } } catch (err) { console.error("Local storage not available"); } //Get user presets if appType = generator if (this.getGlobalVar("appType") == "generator") { let userPresets = null; try { userPresets = localStorage.getItem("generatorPresets_" + this.getGlobalVar("webSourceVersion")); } catch { } if (userPresets && userPresets.length > 0) { userPresets = JSON.parse(userPresets); let adjustedUserPresets = {}; //Tag user presets appropiately Object.keys(userPresets).forEach(presetName => { if (!(presetName in res.presets)) adjustedUserPresets[presetName] = { settings: userPresets[presetName] }; }); Object.assign(res.presets, adjustedUserPresets); } } this.parseGeneratorGUISettings(res, userSettings); //Check for cached files and then create web events after if ((<any>window).emscriptenFoundCachedROMFile) this.generator_settingsMap["rom"] = "<using cached ROM>"; if ((<any>window).emscriptenFoundCachedWADFile) this.generator_settingsMap["web_wad_file"] = "<using cached WAD>"; if ((<any>window).emscriptenFoundCachedCommonKeyFile) this.generator_settingsMap["web_common_key_file"] = "<using cached common key>"; this.createWebEvents(); } parseGeneratorGUISettings(guiSettings, userSettings) { const isRGBHex = /[0-9A-Fa-f]{6}/; //Intialize settings maps for (let tabIndex = 0; tabIndex < guiSettings.settingsArray.length; tabIndex++) { let tab = guiSettings.settingsArray[tabIndex]; //Skip tabs that don't belong to this app and delete them from the guiSettings if ("app_type" in tab && tab.app_type && tab.app_type.indexOf(this.getGlobalVar("appType")) == -1) { guiSettings.settingsArray.splice(tabIndex, 1); tabIndex--; let index = guiSettings.cosmeticsArray.findIndex(entry => entry.name == tab.name); if (index != -1) guiSettings.cosmeticsArray.splice(index, 1); delete guiSettings.settingsObj[tab.name]; delete guiSettings.cosmeticsObj[tab.name]; continue; } this.generator_tabsVisibilityMap[tab.name] = true; tab.sections.forEach(section => { section.settings.forEach(setting => { this.generator_settingsVisibilityMap[setting.name] = true; if (setting.type == "SearchBox" && userSettings && setting.name in userSettings) { //Special parsing for SearchBox data let valueArray = []; userSettings[setting.name].forEach(entry => { let optionEntry = setting.options.find(option => { if (option.name == entry) return true; return false; }); if (optionEntry) valueArray.push(optionEntry); }); this.generator_settingsMap[setting.name] = valueArray; } else if (setting.type == "Combobox" && userSettings && setting.name in userSettings) { //Ensure combobox option exists before applying it (in case of outdated settings being loaded) if (section.is_colors && typeof (userSettings[setting.name]) == "string" && isRGBHex.test(userSettings[setting.name])) { //Custom Color is treated as an exception this.generator_settingsMap[setting.name] = userSettings[setting.name]; } else { let optionEntry = setting.options.find(option => { if (option.name == userSettings[setting.name]) return true; return false; }); this.generator_settingsMap[setting.name] = optionEntry ? userSettings[setting.name] : setting.default; } } else if (userSettings && setting.name in userSettings && (setting.type == "Scale" || setting.type == "Numberinput")) { //Validate numberic values again before applying them this.verifyNumericSetting(userSettings, setting, false); this.generator_settingsMap[setting.name] = userSettings[setting.name]; } else { //Everything else this.generator_settingsMap[setting.name] = userSettings && setting.name in userSettings ? userSettings[setting.name] : setting.default; } //Color section handling if (section.is_colors) { if (typeof (this.generator_settingsMap[setting.name]) == "string" && isRGBHex.test(this.generator_settingsMap[setting.name])) { //Resolve Custom Color this.generator_customColorMap[setting.name] = "#" + this.generator_settingsMap[setting.name]; this.generator_settingsMap[setting.name] = "Custom Color"; } else { this.generator_customColorMap[setting.name] = ""; } } }); }); } //Add GUI only options this.generator_settingsMap["settings_string"] = userSettings && "settings_string" in userSettings ? userSettings["settings_string"] : ""; this.generator_settingsVisibilityMap["settings_string"] = true; console.log("JSON Settings Data:", guiSettings); console.log("Last User Settings:", userSettings); console.log("Final Settings Map", this.generator_settingsMap); console.log("Goal Hint Distros", guiSettings.distroArray); //Save settings after parsing them this.setGlobalVar('generatorSettingsArray', guiSettings.settingsArray); this.setGlobalVar('generatorSettingsObj', guiSettings.settingsObj); this.setGlobalVar('generatorCosmeticsArray', guiSettings.cosmeticsArray); this.setGlobalVar('generatorCosmeticsObj', guiSettings.cosmeticsObj); this.setGlobalVar('generatorGoalDistros', guiSettings.distroArray); this.generator_presets = guiSettings.presets; } async versionCheck() { //Electron only if (!this.getGlobalVar('electronAvailable')) throw Error("electron_not_available"); try { var event = await post.send(window, 'getCurrentSourceVersion'); var res: string = event.data; var result = { hasUpdate: false, currentVersion: "", latestVersion: "" }; if (res && res.length > 0) { console.log("Local:", res); result.currentVersion = res; this.globalEmitter.emit({ name: "local_version_checked", version: res }); let branch = res.includes("Release") ? "release" : "Dev"; var remoteFile = await this.http.get("https://raw.githubusercontent.com/TestRunnerSRL/OoT-Randomizer/" + branch + "/version.py", { responseType: "text" }).toPromise(); let remoteVersion = remoteFile.substr(remoteFile.indexOf("'") + 1); remoteVersion = remoteVersion.substr(0, remoteVersion.indexOf("'")); console.log("Remote:", remoteVersion); result.latestVersion = remoteVersion; //Compare versions result.hasUpdate = this.isVersionNewer(remoteVersion, res); return result; } else { return result; } } catch (err) { console.error(err); throw Error(err); } } isVersionNewer(newVersion: string, oldVersion: string) { //Strip away dev strings if (oldVersion.startsWith("dev") && oldVersion.includes("_")) oldVersion = oldVersion.split("_")[1]; if (newVersion.startsWith("dev") && newVersion.includes("_")) newVersion = newVersion.split("_")[1]; let oldSplit = oldVersion.replace('v', '').replace(' ', '.').split('.'); let newSplit = newVersion.replace('v', '').replace(' ', '.').split('.'); //Version is not newer if the new version doesn't satisfy the format if (newSplit.length < 3) return false; //Version is newer if the old version doesn't satisfy the format if (oldSplit.length < 3) return true; //Compare major.minor.revision if (Number(newSplit[0]) > Number(oldSplit[0])) { return true; } else if (Number(newSplit[0]) == Number(oldSplit[0])) { if (Number(newSplit[1]) > Number(oldSplit[1])) { return true; } else if (Number(newSplit[1]) == Number(oldSplit[1])) { if (Number(newSplit[2]) > Number(oldSplit[2])) { return true; } } } return false; } findSettingByName(settingName: string) { for (let tabIndex = 0; tabIndex < this.getGlobalVar('generatorSettingsArray').length; tabIndex++) { let tab = this.getGlobalVar('generatorSettingsArray')[tabIndex]; for (let sectionIndex = 0; sectionIndex < tab.sections.length; sectionIndex++) { let section = tab.sections[sectionIndex]; for (let settingIndex = 0; settingIndex < section.settings.length; settingIndex++) { let setting = section.settings[settingIndex]; if (setting.name == settingName) return setting; } } } return false; } verifyNumericSetting(settingsFile: any, setting: any, syncToGlobalMap: boolean = false) { let settingValue: any = settingsFile[setting.name]; let error = false; let didCast = false; if (typeof (settingValue) != "string" && typeof (settingValue) != "number") { //Can't recover, bad type error = true; } else if (typeof (settingValue) == "string") { //Try to cast it if (Number(parseInt(settingValue)) != Number(settingValue)) { //Cast failed, not numeric error = true; } else { settingValue = parseInt(settingValue); didCast = true; } } if (!error) { //Min/Max check let settingMin: number = setting["min"]; let settingMax: number = setting["max"]; if (("min" in setting) && settingValue < settingMin) { settingsFile[setting.name] = settingMin; if (syncToGlobalMap) { //Global too if needed and refresh GUI after to signal change this.generator_settingsMap[setting.name] = settingMin; this.globalEmitter.emit({ name: "refresh_gui" }); } error = true; } else if (("max" in setting) && settingValue > settingMax) { settingsFile[setting.name] = settingMax; if (syncToGlobalMap) { //Global too if needed and refresh GUI after to signal change this.generator_settingsMap[setting.name] = settingMax; this.globalEmitter.emit({ name: "refresh_gui" }); } error = true; } if (!error && didCast) { //No error, but setting had to be casted from string, fix it settingsFile[setting.name] = settingValue; if (syncToGlobalMap) { //Global too if needed and refresh GUI after to signal change this.generator_settingsMap[setting.name] = settingValue; this.globalEmitter.emit({ name: "refresh_gui" }); } } } else { //Critical error, reset local value to default settingsFile[setting.name] = setting.default; if (syncToGlobalMap) { //Global too if needed and refresh GUI after to signal change this.generator_settingsMap[setting.name] = setting.default; this.globalEmitter.emit({ name: "refresh_gui" }); } } return error; } applySettingsObject(settingsObj) { if (!settingsObj) return; const isRGBHex = /[0-9A-Fa-f]{6}/; this.getGlobalVar('generatorSettingsArray').forEach(tab => { tab.sections.forEach(section => { section.settings.forEach(setting => { if (setting.name in settingsObj) { if (setting.type == "SearchBox") { //Special parsing for SearchBox data let valueArray = []; settingsObj[setting.name].forEach(entry => { let optionEntry = setting.options.find(option => { if (option.name == entry) return true; return false; }); if (optionEntry) valueArray.push(optionEntry); }); this.generator_settingsMap[setting.name] = valueArray; } else if (setting.type == "Combobox") { //Ensure combobox option exists before applying it (in case of outdated settings being loaded) let optionEntry = setting.options.find(option => { if (option.name == settingsObj[setting.name]) return true; return false; }); if (optionEntry) this.generator_settingsMap[setting.name] = settingsObj[setting.name]; } else if (setting.type == "Scale" || setting.type == "Numberinput") { //Validate numberic values again before applying them this.verifyNumericSetting(settingsObj, setting, false); this.generator_settingsMap[setting.name] = settingsObj[setting.name]; } else { //Everything else this.generator_settingsMap[setting.name] = settingsObj[setting.name]; } //Color section handling if (section.is_colors) { if (typeof (settingsObj[setting.name]) == "string" && isRGBHex.test(settingsObj[setting.name])) { //Resolve Custom Color this.generator_customColorMap[setting.name] = "#" + settingsObj[setting.name]; this.generator_settingsMap[setting.name] = "Custom Color"; } else { this.generator_customColorMap[setting.name] = ""; } } } }); }); }); } applyDefaultSettings() { let cleanSettings = this.createSettingsFileObject(false, true, !this.getGlobalVar('electronAvailable')); this.getGlobalVar('generatorSettingsArray').forEach(tab => { tab.sections.forEach(section => { section.settings.forEach(setting => { if (setting.name in cleanSettings) { this.generator_settingsMap[setting.name] = setting.default; } }); }); }); } deleteSettingsFromMapWithCondition(settingsMap: any, keyName: string, keyValue: any) { this.getGlobalVar("generatorSettingsArray").forEach(tab => { tab.sections.forEach(section => { section.settings.forEach(setting => { if (keyName in setting && setting[keyName] == keyValue) { delete settingsMap[setting.name]; } }); }); }); } createSettingsFileObject(includeFromPatchFileSettings: boolean = true, includeSeedSettingsOnly: boolean = false, sanitizeForBrowserCache: boolean = false, cancelWhenError: boolean = false) { let settingsFile: any = {}; Object.assign(settingsFile, this.generator_settingsMap); //Add in custom colors Object.keys(this.generator_customColorMap).forEach(colorSettingName => { if (this.generator_customColorMap[colorSettingName].length > 0 && settingsFile[colorSettingName] === "Custom Color") { settingsFile[colorSettingName] = this.generator_customColorMap[colorSettingName].substr(1); } }); let invalidSettingsList = []; //Resolve search box entries (name only) this.getGlobalVar("generatorSettingsArray").forEach(tab => { tab.sections.forEach(section => { section.settings.forEach(setting => { if (setting.type == "SearchBox") { let valueArray = []; settingsFile[setting.name].forEach(entry => { valueArray.push(entry.name); }); settingsFile[setting.name] = valueArray; } else if (setting.type == "Scale" || setting.type == "Numberinput") { //Validate numberic values again before saving them let error = this.verifyNumericSetting(settingsFile, setting, true); if (error) { //Input could not be recovered, abort invalidSettingsList.push(setting.text); } } }); }); }); //Abort if any invalid settings were found if (invalidSettingsList && invalidSettingsList.length > 0) { this.globalEmitter.emit({ name: "dialog_error", message: "Some invalid settings were detected and had to be reset! This can happen if you type too fast into an input box. Please try again. The following settings were affected: " + invalidSettingsList.join(", ") }); if (cancelWhenError) return null; } //Delete keys the python source doesn't need delete settingsFile["presets"]; delete settingsFile["open_output_dir"]; delete settingsFile["open_python_dir"]; delete settingsFile["generate_from_file"]; //Delete fromPatchFile keys if mode is fromSeed if (!includeFromPatchFileSettings) { delete settingsFile["patch_file"]; delete settingsFile["repatch_cosmetics"]; //Web only keys if (!this.getGlobalVar('electronAvailable')) { delete settingsFile["web_persist_in_cache"]; } } //Delete keys not included in the seed if (includeSeedSettingsOnly) { //Not mapped settings need to be deleted manually delete settingsFile["settings_string"]; //Delete all shared = false keys from map since they aren't included in the seed this.deleteSettingsFromMapWithCondition(settingsFile, "shared", false); } //Delete keys the browser can't save (web only) if (sanitizeForBrowserCache) { //Delete all settings of type Fileinput/Directoryinput. File objects can not be saved due browser sandbox this.deleteSettingsFromMapWithCondition(settingsFile, "type", "Fileinput"); this.deleteSettingsFromMapWithCondition(settingsFile, "type", "Directoryinput"); } return settingsFile; } saveCurrentSettingsToFile() { if (this.getGlobalVar('electronAvailable')) { //Electron post.send(window, 'saveCurrentSettingsToFile', this.createSettingsFileObject()).then(event => { console.log("settings saved to file"); }).catch(err => { console.error(err); }); } else { //Web try { localStorage.setItem(this.getGlobalVar("appType") == "generator" ? "generatorSettings_" + this.getGlobalVar("webSourceVersion") : "patcherSettings_" + this.getGlobalVar("webSourceVersion"), JSON.stringify(this.createSettingsFileObject(true, false, true))); } catch { } } } convertSettingsToString() { var self = this; return new Promise<string>(function (resolve, reject) { if (self.getGlobalVar('electronAvailable')) { //Electron post.send(window, 'convertSettingsToString', self.createSettingsFileObject(false, true)).then(event => { var listenerSuccess = post.once('convertSettingsToStringSuccess', function (event) { listenerError.cancel(); let data = event.data; resolve(data); }); var listenerError = post.once('convertSettingsToStringError', function (event) { listenerSuccess.cancel(); let data = event.data; console.error("[convertSettingsToString] Python Error:", data); reject(data); }); }).catch(err => { console.error("[convertSettingsToString] Post-Robot Error:", err); reject(err); }); } else { //Web let url = (<any>window).location.protocol + "//" + (<any>window).location.host + "/settings/parse?version=" + self.getGlobalVar("webSourceVersion"); console.log("Request string from:", url); self.http.post(url, JSON.stringify(self.createSettingsFileObject(false, true, true)), { responseType: "text", headers: { "Content-Type": "application/json" } }).toPromise().then(res => { resolve(res); }).catch(err => { console.error("[convertSettingsToString] Web Error:", err); reject(err); }); } }); } convertStringToSettings(settingsString: string) { var self = this; return new Promise(function (resolve, reject) { if (self.getGlobalVar('electronAvailable')) { //Electron post.send(window, 'convertStringToSettings', settingsString).then(event => { var listenerSuccess = post.once('convertStringToSettingsSuccess', function (event) { listenerError.cancel(); let data = JSON.parse(event.data); resolve(data); }); var listenerError = post.once('convertStringToSettingsError', function (event) { listenerSuccess.cancel(); let data = event.data; console.error("[convertStringToSettings] Python Error:", data); reject(data); }); }).catch(err => { console.error("[convertStringToSettings] Post-Robot Error:", err); reject(err); }); } else { //Web let url = (<any>window).location.protocol + "//" + (<any>window).location.host + "/settings/get?version=" + self.getGlobalVar("webSourceVersion") + "&settingsString=" + settingsString; console.log("Request settings from:", url); self.http.get(url, { responseType: "json" }).toPromise().then(res => { resolve(res); }).catch(err => { console.error("[convertStringToSettings] Web Error:", err); reject(err); }); } }); } createPresetFileObject() { let presetsFile: any = {}; //Create presets object Object.keys(this.generator_presets).forEach(presetKey => { let preset = this.generator_presets[presetKey]; if (!("isNewPreset" in preset) && !("isDefaultPreset" in preset) && !("isProtectedPreset" in preset) && ("settings" in preset) && typeof (preset.settings) == "object" && Object.keys(preset.settings).length > 0) { //console.log("store " + presetKey, preset.settings); presetsFile[presetKey] = preset.settings; } }); return presetsFile; } saveCurrentPresetsToFile() { if (this.getGlobalVar('electronAvailable')) { //Electron post.send(window, 'saveCurrentPresetsToFile', JSON.stringify(this.createPresetFileObject(), null, 4)).then(event => { console.log("presets saved to file"); }).catch(err => { console.error(err); }); } else { //Web if (this.getGlobalVar("appType") == "generator") { //Generator only try { localStorage.setItem("generatorPresets_" + this.getGlobalVar("webSourceVersion"), JSON.stringify(this.createPresetFileObject(), null, 4)); } catch { } } } } generateSeedElectron(progressWindowRef: ProgressWindow, fromPatchFile: boolean = false, useStaticSeed: string = "") { //Electron only var self = this; return new Promise(function (resolve, reject) { let settingsMap = self.createSettingsFileObject(fromPatchFile, false, false, true); if (!settingsMap) { reject({ short: "Generation aborted.", long: "Generation aborted." }); return; } //Hack: fromPatchFile forces generation count to 1 to avoid wrong percentage calculation if (fromPatchFile) settingsMap["count"] = 1; post.send(window, 'generateSeed', { settingsFile: settingsMap, staticSeed: useStaticSeed }).then(event => { var listenerProgress = post.on('generateSeedProgress', function (event) { let data = event.data; //console.log("progress report", data); if (progressWindowRef) { progressWindowRef.currentGenerationIndex = data.generationIndex; progressWindowRef.progressPercentageCurrent = data.progressCurrent; progressWindowRef.progressPercentageTotal = data.progressTotal; progressWindowRef.progressMessage = data.message; progressWindowRef.refreshLayout(); } }); var listenerSuccess = post.once('generateSeedSuccess', function (event) { listenerProgress.cancel(); listenerCancel.cancel(); listenerError.cancel(); let data = event.data; resolve(); }); var listenerError = post.once('generateSeedError', function (event) { listenerProgress.cancel(); listenerCancel.cancel(); listenerSuccess.cancel(); let data = event.data; console.error("[generateSeedElectron] Python Error:", data); reject(data); }); var listenerCancel = post.once('generateSeedCancelled', function (event) { listenerProgress.cancel(); listenerSuccess.cancel(); listenerError.cancel(); reject({ short: "Generation cancelled.", long: "Generation cancelled." }); }); }).catch(err => { console.error("[generateSeedElectron] Post-Robot Error:", err); reject({ short: err, long: err }); }); }); } async cancelGenerateSeedElectron() { //Electron only if (!this.getGlobalVar('electronAvailable')) throw Error("electron_not_available"); try { let event = await post.send(window, 'cancelGenerateSeed'); let data = event.data; if (data == true) return; else throw Error("cancel_failed"); } catch (err) { console.error("[cancelGenerateSeedElectron] Couldn't cancel due Post-Robot Error:", err); throw Error(err); } } hasRomExtension(fileName: string) { fileName = fileName.toLowerCase(); return fileName.endsWith(".z64") || fileName.endsWith(".n64") || fileName.endsWith(".v64"); } isValidFileObjectWeb(file: any) { //Web only return file && typeof (file) == "object" && file.name && file.name.length > 0; } readFileIntoMemoryWeb(fileObject: any, useArrayBuffer: boolean) { //Web only return new Promise<any>(function (resolve, reject) { let fileReader = new FileReader(); fileReader.onabort = function (event) { console.error("Loading of the file was aborted unexpectedly!"); reject(); }; fileReader.onerror = function (event) { console.error("An error occurred during the loading of the file!"); reject(); }; fileReader.onload = function (event) { console.log("Read in file successfully"); resolve(event.target["result"]); }; if (useArrayBuffer) fileReader.readAsArrayBuffer(fileObject); else fileReader.readAsText(fileObject); }); } async readJsonFileIntoMemoryWeb(file: any, sizeLimit: number) { //Web only let fileJSON; if (this.hasRomExtension(file.name)) { //Not a ROM check... throw { error: "file_extension_was_rom" }; } try { fileJSON = await this.readFileIntoMemoryWeb(file, false); } catch (ex) { throw { error: "file_read_error" }; } if (!fileJSON || fileJSON.length < 1) { throw { error: "file_not_valid" }; } if (fileJSON.length > sizeLimit) { //Impose size limit to avoid server overload throw { error: "file_too_big" }; } //Test JSON parse it try { let jsonFileParsed = JSON.parse(fileJSON); if (!jsonFileParsed || Object.keys(jsonFileParsed).length < 1) { throw { error: "file_not_valid_json_empty" }; } } catch (err) { console.error(err); throw { error: "file_not_valid_json_syntax", message: err.message }; } return fileJSON; } async readPlandoFileIntoMemoryWeb(settingName: string, settingText: string) { //Web only let plandoFile = this.generator_settingsMap[settingName]; if (!this.isValidFileObjectWeb(plandoFile)) return null; //Try to resolve the plando file by reading it into memory console.log("Read Plando JSON file: " + plandoFile.name); try { let plandoFileText = await this.readJsonFileIntoMemoryWeb(plandoFile, 500000); //Will return the JSON file contents as text return plandoFileText; } catch (ex) { switch (ex.error) { case "file_read_error": { throw { error: `An error occurred during the loading of the ${settingText}! Please try to enter it again.` }; } case "file_not_valid": { throw { error: `The ${settingText} specified is not valid!` }; } case "file_too_big": { throw { error: `The ${settingText} specified is too big! The maximum file size allowed is 500 KB.` }; } case "file_not_valid_json_empty": { throw { error: `The ${settingText} specified is not valid JSON! Please verify the syntax.` }; } case "file_not_valid_json_syntax": { throw { error: `The ${settingText} specified is not valid JSON! Please verify the syntax. Detail: ${ex.message}` }; } default: { //Bubble error upwards throw ex; } } } } async generateSeedWeb(raceSeed: boolean = false, useStaticSeed: string = "") { //Web only //Plando Seed Logic let plandoFileSeed = null; if (this.generator_settingsMap["enable_distribution_file"]) { if (raceSeed) { //No support for race seeds throw { error: "Plandomizer for seed creation is currently not supported for race seeds due security concerns. Please use a normal seed instead!" }; } let setting = this.findSettingByName("distribution_file"); try { plandoFileSeed = await this.readPlandoFileIntoMemoryWeb("distribution_file", setting.text); } catch (ex) { switch (ex.error) { case "file_extension_was_rom": { throw { error_rom_in_plando: "Your Ocarina of Time ROM doesn't belong in a plandomizer setting. This entirely optional setting is used to plan out seeds before generation by manipulating spoiler log files. If you want to generate a normal seed instead, please click YES!", type: "distribution_file" }; } default: { //Bubble error upwards throw ex; } } } } //Plando Cosmetics Logic let plandoFileCosmetics = null; if (this.generator_settingsMap["enable_cosmetic_file"]) { let setting = this.findSettingByName("cosmetic_file"); try { plandoFileCosmetics = await this.readPlandoFileIntoMemoryWeb("cosmetic_file", setting.text); } catch (ex) { switch (ex.error) { case "file_extension_was_rom": { throw { error_rom_in_plando: "Your Ocarina of Time ROM doesn't belong in a plandomizer setting. This entirely optional setting is used to give you more control over your cosmetic and sound settings. If you want to generate a normal seed with regular cosmetics instead, please click YES!", type: "cosmetic_file" }; } default: { //Bubble error upwards throw ex; } } } } let settingsFile = this.createSettingsFileObject(false, false, true, true); if (!settingsFile) { throw { error: "The generation was aborted due to previous errors!" }; } //Add distribution file back into map as string if available, else clear it if (plandoFileSeed) { settingsFile["distribution_file"] = plandoFileSeed; } else { settingsFile["enable_distribution_file"] = false; settingsFile["distribution_file"] = ""; } //Add cosmetics plando file back into map as string if available, else clear it if (plandoFileCosmetics) { settingsFile["cosmetic_file"] = plandoFileCosmetics; } else { settingsFile["enable_cosmetic_file"] = false; settingsFile["cosmetic_file"] = ""; } if (raceSeed) { useStaticSeed = ""; //Static seeds aren't allowed in race mode settingsFile["create_spoiler"] = true; //Force spoiler mode to on settingsFile["encrypt"] = true; } else { delete settingsFile["encrypt"]; } if (useStaticSeed) { console.log("Use Static Seed:", useStaticSeed); settingsFile["seed"] = useStaticSeed; } else { delete settingsFile["seed"]; } //If spoiler log creation was intentionally disabled, warn user one time about the consequences try { let spoilerLogWarningSeen = localStorage.getItem("spoilerLogWarningSeen"); if ((!spoilerLogWarningSeen || spoilerLogWarningSeen == "false") && settingsFile["create_spoiler"] == false) { localStorage.setItem("spoilerLogWarningSeen", JSON.stringify(true)); throw { error_spoiler_log_disabled: "Generating a seed without a spoiler log means you won't be able to receive any help in case you get stuck! Would you rather generate a seed WITH a spoiler log?" }; } } catch (err) { //Bubble through in case the warning should be displayed, ignore if local storage is not available if (err.hasOwnProperty('error_spoiler_log_disabled')) throw err; } console.log(settingsFile); console.log("Race Seed:", raceSeed); //Request Seed Generation let url = (<any>window).location.protocol + "//" + (<any>window).location.host + "/seed/create?version=" + this.getGlobalVar("webSourceVersion"); console.log("Request seed id from:", url); try { let res = await this.http.post(url, JSON.stringify(settingsFile), { responseType: "text", headers: { "Content-Type": "application/json" } }).toPromise(); return res; } catch (err) { console.error("[generateSeedWeb] Web Error:", err); throw err; } } async patchROMWeb() { //Web only //Plando Cosmetics Logic let plandoFileCosmetics = null; if (this.generator_settingsMap["enable_cosmetic_file"]) { try { plandoFileCosmetics = await this.readPlandoFileIntoMemoryWeb("cosmetic_file", "Cosmetic Plandomizer File"); } catch (ex) { switch (ex.error) { case "file_extension_was_rom": { throw { error_rom_in_plando: "Your Ocarina of Time ROM doesn't belong in a plandomizer setting. This entirely optional setting is used to give you more control over your cosmetic and sound settings. If you want to patch your ROM with regular cosmetics instead, please click YES!", type: "cosmetic_file" }; } default: { //Bubble error upwards throw ex; } } } } let settingsFile = this.createSettingsFileObject(true, false, false, true); if (!settingsFile) { throw { error: "The patching was aborted due to previous errors!" }; } //Add cosmetics plando file back into map as string if available, else clear it if (plandoFileCosmetics) { settingsFile["cosmetic_file"] = plandoFileCosmetics; } else { settingsFile["enable_cosmetic_file"] = false; settingsFile["cosmetic_file"] = ""; } if (typeof (<any>window).patchROM === "function") { //Try to call patchROM function on the DOM //Delay this so the async function can return early with "success" setTimeout(() => { (<any>window).patchROM(5, settingsFile); //Patch Version 5 }, 0); } else { console.error("[patchROMWeb] Patcher not available!"); throw { error: "Patcher not available!" }; } } }
the_stack
import BigNumber from 'bignumber.js'; import { Provider } from 'web3/providers'; import Web3 from 'web3'; import PromiEvent from 'web3/promiEvent'; import { TransactionReceipt } from 'web3/types'; import { TransactionObject, Block, Tx } from 'web3/eth/types'; // Contracts import { SoloMargin } from '../../build/wrappers/SoloMargin'; import { IErc20 as ERC20 } from '../../build/wrappers/IErc20'; import { IInterestSetter as InterestSetter } from '../../build/wrappers/IInterestSetter'; import { IPriceOracle as PriceOracle } from '../../build/wrappers/IPriceOracle'; import { Expiry } from '../../build/wrappers/Expiry'; import { ExpiryV2 } from '../../build/wrappers/ExpiryV2'; import { FinalSettlement } from '../../build/wrappers/FinalSettlement'; import { Refunder } from '../../build/wrappers/Refunder'; import { DaiMigrator } from '../../build/wrappers/DaiMigrator'; import { LimitOrders } from '../../build/wrappers/LimitOrders'; import { StopLimitOrders } from '../../build/wrappers/StopLimitOrders'; import { CanonicalOrders } from '../../build/wrappers/CanonicalOrders'; import { PayableProxyForSoloMargin as PayableProxy, } from '../../build/wrappers/PayableProxyForSoloMargin'; import { SignedOperationProxy } from '../../build/wrappers/SignedOperationProxy'; import { LiquidatorProxyV1ForSoloMargin as LiquidatorProxyV1, } from '../../build/wrappers/LiquidatorProxyV1ForSoloMargin'; import { PolynomialInterestSetter } from '../../build/wrappers/PolynomialInterestSetter'; import { DoubleExponentInterestSetter } from '../../build/wrappers/DoubleExponentInterestSetter'; import { WethPriceOracle } from '../../build/wrappers/WethPriceOracle'; import { DaiPriceOracle } from '../../build/wrappers/DaiPriceOracle'; import { UsdcPriceOracle } from '../../build/wrappers/UsdcPriceOracle'; import { Weth } from '../../build/wrappers/Weth'; // JSON import soloMarginJson from '../../build/published_contracts/SoloMargin.json'; import erc20Json from '../../build/published_contracts/IErc20.json'; import interestSetterJson from '../../build/published_contracts/IInterestSetter.json'; import priceOracleJson from '../../build/published_contracts/IPriceOracle.json'; import expiryJson from '../../build/published_contracts/Expiry.json'; import expiryV2Json from '../../build/published_contracts/ExpiryV2.json'; import finalSettlementJson from '../../build/published_contracts/FinalSettlement.json'; import refunderJson from '../../build/published_contracts/Refunder.json'; import daiMigratorJson from '../../build/published_contracts/DaiMigrator.json'; import limitOrdersJson from '../../build/published_contracts/LimitOrders.json'; import stopLimitOrdersJson from '../../build/published_contracts/StopLimitOrders.json'; import canonicalOrdersJson from '../../build/published_contracts/CanonicalOrders.json'; import payableProxyJson from '../../build/published_contracts/PayableProxyForSoloMargin.json'; import signedOperationProxyJson from '../../build/published_contracts/SignedOperationProxy.json'; import liquidatorV1Json from '../../build/published_contracts/LiquidatorProxyV1ForSoloMargin.json'; import polynomialInterestSetterJson from '../../build/published_contracts/PolynomialInterestSetter.json'; import doubleExponentInterestSetterJson from '../../build/published_contracts/DoubleExponentInterestSetter.json'; import wethPriceOracleJson from '../../build/published_contracts/WethPriceOracle.json'; import daiPriceOracleJson from '../../build/published_contracts/DaiPriceOracle.json'; import usdcPriceOracleJson from '../../build/published_contracts/UsdcPriceOracle.json'; import wethJson from '../../build/published_contracts/Weth.json'; import { ADDRESSES, SUBTRACT_GAS_LIMIT } from './Constants'; import { TxResult, address, SoloOptions, ConfirmationType, TxOptions, CallOptions, NativeSendOptions, SendOptions, } from '../types'; interface CallableTransactionObject<T> { call(tx?: Tx, blockNumber?: number | string): Promise<T>; } export class Contracts { private blockGasLimit: number; private autoGasMultiplier: number; private defaultConfirmations: number; private confirmationType: ConfirmationType; private defaultGas: string | number; private defaultGasPrice: string | number; protected web3: Web3; // Contract instances public soloMargin: SoloMargin; public erc20: ERC20; public interestSetter: InterestSetter; public priceOracle: PriceOracle; public expiry: Expiry; public expiryV2: ExpiryV2; public finalSettlement: FinalSettlement; public refunder: Refunder; public daiMigrator: DaiMigrator; public limitOrders: LimitOrders; public stopLimitOrders: StopLimitOrders; public canonicalOrders: CanonicalOrders; public payableProxy: PayableProxy; public signedOperationProxy: SignedOperationProxy; public liquidatorProxyV1: LiquidatorProxyV1; public polynomialInterestSetter: PolynomialInterestSetter; public doubleExponentInterestSetter: DoubleExponentInterestSetter; public wethPriceOracle: WethPriceOracle; public daiPriceOracle: DaiPriceOracle; public saiPriceOracle: DaiPriceOracle; public usdcPriceOracle: UsdcPriceOracle; public weth: Weth; constructor( provider: Provider, networkId: number, web3: Web3, options: SoloOptions, ) { this.web3 = web3; this.defaultConfirmations = options.defaultConfirmations; this.autoGasMultiplier = options.autoGasMultiplier || 1.5; this.confirmationType = options.confirmationType || ConfirmationType.Confirmed; this.defaultGas = options.defaultGas; this.defaultGasPrice = options.defaultGasPrice; this.blockGasLimit = options.blockGasLimit; // Contracts this.soloMargin = new this.web3.eth.Contract(soloMarginJson.abi) as SoloMargin; this.erc20 = new this.web3.eth.Contract(erc20Json.abi) as ERC20; this.interestSetter = new this.web3.eth.Contract(interestSetterJson.abi) as InterestSetter; this.priceOracle = new this.web3.eth.Contract(priceOracleJson.abi) as PriceOracle; this.expiry = new this.web3.eth.Contract(expiryJson.abi) as Expiry; this.expiryV2 = new this.web3.eth.Contract(expiryV2Json.abi) as ExpiryV2; this.finalSettlement = new this.web3.eth.Contract(finalSettlementJson.abi) as FinalSettlement; this.refunder = new this.web3.eth.Contract(refunderJson.abi) as Refunder; this.daiMigrator = new this.web3.eth.Contract(daiMigratorJson.abi) as DaiMigrator; this.limitOrders = new this.web3.eth.Contract(limitOrdersJson.abi) as LimitOrders; this.stopLimitOrders = new this.web3.eth.Contract(stopLimitOrdersJson.abi) as StopLimitOrders; this.canonicalOrders = new this.web3.eth.Contract(canonicalOrdersJson.abi) as CanonicalOrders; this.payableProxy = new this.web3.eth.Contract(payableProxyJson.abi) as PayableProxy; this.signedOperationProxy = new this.web3.eth.Contract(signedOperationProxyJson.abi) as SignedOperationProxy; this.liquidatorProxyV1 = new this.web3.eth.Contract(liquidatorV1Json.abi) as LiquidatorProxyV1; this.polynomialInterestSetter = new this.web3.eth.Contract(polynomialInterestSetterJson.abi) as PolynomialInterestSetter; this.doubleExponentInterestSetter = new this.web3.eth.Contract( doubleExponentInterestSetterJson.abi) as DoubleExponentInterestSetter; this.wethPriceOracle = new this.web3.eth.Contract(wethPriceOracleJson.abi) as WethPriceOracle; this.daiPriceOracle = new this.web3.eth.Contract(daiPriceOracleJson.abi) as DaiPriceOracle; this.saiPriceOracle = new this.web3.eth.Contract(daiPriceOracleJson.abi) as DaiPriceOracle; this.usdcPriceOracle = new this.web3.eth.Contract(usdcPriceOracleJson.abi) as UsdcPriceOracle; this.weth = new this.web3.eth.Contract(wethJson.abi) as Weth; this.setProvider(provider, networkId); this.setDefaultAccount(this.web3.eth.defaultAccount); } public setProvider( provider: Provider, networkId: number, ): void { this.soloMargin.setProvider(provider); const contracts = [ // contracts { contract: this.soloMargin, json: soloMarginJson }, { contract: this.erc20, json: erc20Json }, { contract: this.interestSetter, json: interestSetterJson }, { contract: this.priceOracle, json: priceOracleJson }, { contract: this.expiry, json: expiryJson }, { contract: this.expiryV2, json: expiryV2Json }, { contract: this.finalSettlement, json: finalSettlementJson }, { contract: this.refunder, json: refunderJson }, { contract: this.daiMigrator, json: daiMigratorJson }, { contract: this.limitOrders, json: limitOrdersJson }, { contract: this.stopLimitOrders, json: stopLimitOrdersJson }, { contract: this.canonicalOrders, json: canonicalOrdersJson }, { contract: this.payableProxy, json: payableProxyJson }, { contract: this.signedOperationProxy, json: signedOperationProxyJson }, { contract: this.liquidatorProxyV1, json: liquidatorV1Json }, { contract: this.polynomialInterestSetter, json: polynomialInterestSetterJson }, { contract: this.doubleExponentInterestSetter, json: doubleExponentInterestSetterJson }, { contract: this.wethPriceOracle, json: wethPriceOracleJson }, { contract: this.daiPriceOracle, json: daiPriceOracleJson }, { contract: this.saiPriceOracle, json: daiPriceOracleJson, overrides: { 1: '0x787F552BDC17332c98aA360748884513e3cB401a', 42: '0x8a6629fEba4196E0A61B8E8C94D4905e525bc055', 1001: ADDRESSES.TEST_SAI_PRICE_ORACLE, 1002: ADDRESSES.TEST_SAI_PRICE_ORACLE, } }, { contract: this.usdcPriceOracle, json: usdcPriceOracleJson }, { contract: this.weth, json: wethJson }, ]; contracts.forEach(contract => this.setContractProvider( contract.contract, contract.json, provider, networkId, contract.overrides, ), ); } public setDefaultAccount( account: address, ): void { // Contracts this.soloMargin.options.from = account; this.erc20.options.from = account; this.interestSetter.options.from = account; this.priceOracle.options.from = account; this.expiry.options.from = account; this.expiryV2.options.from = account; this.finalSettlement.options.from = account; this.refunder.options.from = account; this.daiMigrator.options.from = account; this.limitOrders.options.from = account; this.stopLimitOrders.options.from = account; this.canonicalOrders.options.from = account; this.payableProxy.options.from = account; this.signedOperationProxy.options.from = account; this.liquidatorProxyV1.options.from = account; this.polynomialInterestSetter.options.from = account; this.doubleExponentInterestSetter.options.from = account; this.wethPriceOracle.options.from = account; this.daiPriceOracle.options.from = account; this.saiPriceOracle.options.from = account; this.usdcPriceOracle.options.from = account; this.weth.options.from = account; } public async send<T>( method: TransactionObject<T>, options: SendOptions = {}, ): Promise<TxResult> { const { confirmations, confirmationType, autoGasMultiplier, ...txOptions } = options; if (!this.blockGasLimit) { await this.setGasLimit(); } if (!txOptions.gasPrice && this.defaultGasPrice) { txOptions.gasPrice = this.defaultGasPrice; } if (confirmationType === ConfirmationType.Simulate || !options.gas) { let gasEstimate: number; if (this.defaultGas && confirmationType !== ConfirmationType.Simulate) { txOptions.gas = this.defaultGas; } else { try { gasEstimate = await method.estimateGas(this.toEstimateOptions(txOptions)); } catch (error) { const data = method.encodeABI(); const { from, value } = options; const to = (method as any)._parent._address; error.transactionData = { from, value, data, to }; throw error; } const multiplier = autoGasMultiplier || this.autoGasMultiplier; const totalGas: number = Math.floor(gasEstimate * multiplier); txOptions.gas = totalGas < this.blockGasLimit ? totalGas : this.blockGasLimit; } if (confirmationType === ConfirmationType.Simulate) { return { gasEstimate, gas: Number(txOptions.gas) }; } } if (txOptions.value) { txOptions.value = new BigNumber(txOptions.value).toFixed(0); } else { txOptions.value = '0'; } const promi: PromiEvent<T> = method.send(this.toNativeSendOptions(txOptions)); const OUTCOMES = { INITIAL: 0, RESOLVED: 1, REJECTED: 2, }; let hashOutcome = OUTCOMES.INITIAL; let confirmationOutcome = OUTCOMES.INITIAL; const t = confirmationType !== undefined ? confirmationType : this.confirmationType; if (!Object.values(ConfirmationType).includes(t)) { throw new Error(`Invalid confirmation type: ${t}`); } let hashPromise: Promise<string>; let confirmationPromise: Promise<TransactionReceipt>; if (t === ConfirmationType.Hash || t === ConfirmationType.Both) { hashPromise = new Promise( (resolve, reject) => { promi.on('error', (error: Error) => { if (hashOutcome === OUTCOMES.INITIAL) { hashOutcome = OUTCOMES.REJECTED; reject(error); const anyPromi = promi as any; anyPromi.off(); } }); promi.on('transactionHash', (txHash: string) => { if (hashOutcome === OUTCOMES.INITIAL) { hashOutcome = OUTCOMES.RESOLVED; resolve(txHash); if (t !== ConfirmationType.Both) { const anyPromi = promi as any; anyPromi.off(); } } }); }, ); } if (t === ConfirmationType.Confirmed || t === ConfirmationType.Both) { confirmationPromise = new Promise( (resolve, reject) => { promi.on('error', (error: Error) => { if ( (t === ConfirmationType.Confirmed || hashOutcome === OUTCOMES.RESOLVED) && confirmationOutcome === OUTCOMES.INITIAL ) { confirmationOutcome = OUTCOMES.REJECTED; reject(error); const anyPromi = promi as any; anyPromi.off(); } }); const desiredConf = confirmations || this.defaultConfirmations; if (desiredConf) { promi.on('confirmation', (confNumber: number, receipt: TransactionReceipt) => { if (confNumber >= desiredConf) { if (confirmationOutcome === OUTCOMES.INITIAL) { confirmationOutcome = OUTCOMES.RESOLVED; resolve(receipt); const anyPromi = promi as any; anyPromi.off(); } } }); } else { promi.on('receipt', (receipt: TransactionReceipt) => { confirmationOutcome = OUTCOMES.RESOLVED; resolve(receipt); const anyPromi = promi as any; anyPromi.off(); }); } }, ); } if (t === ConfirmationType.Hash) { const transactionHash = await hashPromise; return this.normalizeResponse({ transactionHash }); } if (t === ConfirmationType.Confirmed) { return confirmationPromise; } const transactionHash = await hashPromise; return this.normalizeResponse({ transactionHash, confirmation: confirmationPromise, }); } public async call<T>( method: TransactionObject<T>, options: CallOptions = {}, ): Promise<T> { const { blockNumber, ...txOptions } = this.toCallOptions(options); const m2 = method as CallableTransactionObject<T>; return m2.call(txOptions, blockNumber || 'latest'); } private async setGasLimit(): Promise<void> { const block: Block = await this.web3.eth.getBlock('latest'); this.blockGasLimit = block.gasLimit - SUBTRACT_GAS_LIMIT; } protected setContractProvider( contract: any, contractJson: any, provider: Provider, networkId: number, overrides: any, ): void { contract.setProvider(provider); const contractAddress = contractJson.networks[networkId] && contractJson.networks[networkId].address; const overrideAddress = overrides && overrides[networkId]; contract.options.address = overrideAddress || contractAddress; } // ============ Parse Options ============ private toEstimateOptions( txOptions: SendOptions, ): TxOptions { return { from: txOptions.from, value: txOptions.value, }; } private toCallOptions( options: any, ): CallOptions { return { from: options.from, value: options.value, blockNumber: options.blockNumber, }; } private toNativeSendOptions( options: any, ): NativeSendOptions { return { from: options.from, value: options.value, gasPrice: options.gasPrice, gas: options.gas, nonce: options.nonce, }; } private normalizeResponse( txResult: any, ): any { const txHash = txResult.transactionHash; if (txHash) { const { transactionHash: internalHash, nonce: internalNonce, } = txHash; if (internalHash) { txResult.transactionHash = internalHash; } if (internalNonce) { txResult.nonce = internalNonce; } } return txResult; } }
the_stack
import { BaseResource, CloudError } from "ms-rest-azure"; import * as moment from "moment"; export { BaseResource, CloudError }; /** * Error Details object. */ export interface StorageSyncErrorDetails { /** * Error code of the given entry. */ code?: string; /** * Error message of the given entry. */ message?: string; /** * Target of the given entry. */ target?: string; } /** * Error type */ export interface StorageSyncApiError { /** * Error code of the given entry. */ code?: string; /** * Error message of the given entry. */ message?: string; /** * Target of the given error entry. */ target?: string; /** * Error details of the given entry. */ details?: StorageSyncErrorDetails; } /** * Error type */ export interface StorageSyncError { /** * Error details of the given entry. */ error?: StorageSyncApiError; /** * Error details of the given entry. */ innererror?: StorageSyncApiError; } /** * Subscription State object. */ export interface SubscriptionState { /** * State of Azure Subscription. Possible values include: 'Registered', 'Unregistered', 'Warned', * 'Suspended', 'Deleted' */ state?: string; /** * Is Transitioning */ readonly istransitioning?: boolean; /** * Subscription state properties. */ properties?: any; } export interface Resource extends BaseResource { /** * Fully qualified resource Id for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ readonly id?: string; /** * The name of the resource */ readonly name?: string; /** * The type of the resource. Ex- Microsoft.Compute/virtualMachines or * Microsoft.Storage/storageAccounts. */ readonly type?: string; } /** * The resource model definition for a ARM tracked top level resource */ export interface TrackedResource extends Resource { /** * Resource tags. */ tags?: { [propertyName: string]: string }; /** * The geo-location where the resource lives */ location: string; } /** * Storage Sync Service object. */ export interface StorageSyncService extends TrackedResource { /** * Storage Sync service status. */ readonly storageSyncServiceStatus?: number; /** * Storage Sync service Uid */ readonly storageSyncServiceUid?: string; } /** * The resource model definition for a ARM proxy resource. It will have everything other than * required location and tags */ export interface ProxyResource extends Resource { } /** * Sync Group object. */ export interface SyncGroup extends ProxyResource { /** * Unique Id */ uniqueId?: string; /** * Sync group status */ readonly syncGroupStatus?: string; } /** * Cloud Endpoint object. */ export interface CloudEndpoint extends ProxyResource { /** * Storage Account Resource Id */ storageAccountResourceId?: string; /** * Azure file share name */ azureFileShareName?: string; /** * Storage Account Tenant Id */ storageAccountTenantId?: string; /** * Partnership Id */ partnershipId?: string; /** * Friendly Name */ friendlyName?: string; /** * Backup Enabled */ readonly backupEnabled?: string; /** * CloudEndpoint Provisioning State */ provisioningState?: string; /** * CloudEndpoint lastWorkflowId */ lastWorkflowId?: string; /** * Resource Last Operation Name */ lastOperationName?: string; } /** * The parameters used when calling recall action on server endpoint. */ export interface RecallActionParameters { /** * Pattern of the files. */ pattern?: string; /** * Recall path. */ recallPath?: string; } /** * The parameters used when creating a storage sync service. */ export interface StorageSyncServiceCreateParameters { /** * Required. Gets or sets the location of the resource. This will be one of the supported and * registered Azure Geo Regions (e.g. West US, East US, Southeast Asia, etc.). The geo region of * a resource cannot be changed once it is created, but if an identical geo region is specified * on update, the request will succeed. */ location: string; /** * Gets or sets a list of key value pairs that describe the resource. These tags can be used for * viewing and grouping this resource (across resource groups). A maximum of 15 tags can be * provided for a resource. Each tag must have a key with a length no greater than 128 characters * and a value with a length no greater than 256 characters. */ tags?: { [propertyName: string]: string }; properties?: any; } /** * The parameters used when creating a sync group. */ export interface SyncGroupCreateParameters extends ProxyResource { /** * The parameters used to create the sync group */ properties?: any; } /** * The parameters used when creating a cloud endpoint. */ export interface CloudEndpointCreateParameters extends ProxyResource { /** * Storage Account Resource Id */ storageAccountResourceId?: string; /** * Azure file share name */ azureFileShareName?: string; /** * Storage Account Tenant Id */ storageAccountTenantId?: string; } /** * The parameters used when creating a server endpoint. */ export interface ServerEndpointCreateParameters extends ProxyResource { /** * Server Local path. */ serverLocalPath?: string; /** * Cloud Tiering. Possible values include: 'on', 'off' */ cloudTiering?: string; /** * Level of free space to be maintained by Cloud Tiering if it is enabled. */ volumeFreeSpacePercent?: number; /** * Tier files older than days. */ tierFilesOlderThanDays?: number; /** * Friendly Name */ friendlyName?: string; /** * Server Resource Id. */ serverResourceId?: string; /** * Offline data transfer. Possible values include: 'on', 'off' */ offlineDataTransfer?: string; /** * Offline data transfer share name */ offlineDataTransferShareName?: string; } /** * Trigger Rollover Request. */ export interface TriggerRolloverRequest { /** * Certificate Data */ serverCertificate?: string; } /** * The parameters used when creating a registered server. */ export interface RegisteredServerCreateParameters extends ProxyResource { /** * Registered Server Certificate */ serverCertificate?: string; /** * Registered Server Agent Version */ agentVersion?: string; /** * Registered Server OS Version */ serverOSVersion?: string; /** * Registered Server last heart beat */ lastHeartBeat?: string; /** * Registered Server serverRole */ serverRole?: string; /** * Registered Server clusterId */ clusterId?: string; /** * Registered Server clusterName */ clusterName?: string; /** * Registered Server serverId */ serverId?: string; /** * Friendly Name */ friendlyName?: string; } /** * Parameters for updating an Server Endpoint. */ export interface ServerEndpointUpdateParameters { /** * Cloud Tiering. Possible values include: 'on', 'off' */ cloudTiering?: string; /** * Level of free space to be maintained by Cloud Tiering if it is enabled. */ volumeFreeSpacePercent?: number; /** * Tier files older than days. */ tierFilesOlderThanDays?: number; /** * Offline data transfer. Possible values include: 'on', 'off' */ offlineDataTransfer?: string; /** * Offline data transfer share name */ offlineDataTransferShareName?: string; } /** * Files not syncing error object */ export interface FilesNotSyncingError { /** * Error code (HResult) */ readonly errorCode?: number; /** * Count of persistent files not syncing with the specified error code */ readonly persistentCount?: number; /** * Count of transient files not syncing with the specified error code */ readonly transientCount?: number; } /** * Sync Session status object. */ export interface SyncSessionStatus { /** * Last sync result (HResult) */ readonly lastSyncResult?: number; /** * Last sync timestamp */ readonly lastSyncTimestamp?: Date; /** * Last sync success timestamp */ readonly lastSyncSuccessTimestamp?: Date; /** * Last sync per item error count. */ readonly lastSyncPerItemErrorCount?: number; /** * Count of persistent files not syncing. Reserved for future use. */ readonly persistentFilesNotSyncingCount?: number; /** * Count of transient files not syncing. Reserved for future use. */ readonly transientFilesNotSyncingCount?: number; /** * Array of per-item errors coming from the last sync session. Reserved for future use. */ readonly filesNotSyncingErrors?: FilesNotSyncingError[]; } /** * Sync Session status object. */ export interface SyncActivityStatus { /** * Timestamp when properties were updated */ readonly timestamp?: Date; /** * Per item error count */ readonly perItemErrorCount?: number; /** * Applied item count. */ readonly appliedItemCount?: number; /** * Total item count (if available) */ readonly totalItemCount?: number; /** * Applied bytes */ readonly appliedBytes?: number; /** * Total bytes (if available) */ readonly totalBytes?: number; } /** * Server Endpoint sync status */ export interface ServerEndpointSyncStatus { /** * Download Health Status. Possible values include: 'Healthy', 'Error', 'SyncBlockedForRestore', * 'SyncBlockedForChangeDetectionPostRestore', 'NoActivity' */ readonly downloadHealth?: string; /** * Upload Health Status. Possible values include: 'Healthy', 'Error', 'SyncBlockedForRestore', * 'SyncBlockedForChangeDetectionPostRestore', 'NoActivity' */ readonly uploadHealth?: string; /** * Combined Health Status. Possible values include: 'Healthy', 'Error', 'SyncBlockedForRestore', * 'SyncBlockedForChangeDetectionPostRestore', 'NoActivity' */ readonly combinedHealth?: string; /** * Sync activity. Possible values include: 'Upload', 'Download', 'UploadAndDownload' */ readonly syncActivity?: string; /** * Total count of persistent files not syncing (combined upload + download). Reserved for future * use. */ readonly totalPersistentFilesNotSyncingCount?: number; /** * Last Updated Timestamp */ readonly lastUpdatedTimestamp?: Date; /** * Upload Status */ readonly uploadStatus?: SyncSessionStatus; /** * Download Status */ readonly downloadStatus?: SyncSessionStatus; /** * Upload sync activity */ readonly uploadActivity?: SyncActivityStatus; /** * Download sync activity */ readonly downloadActivity?: SyncActivityStatus; /** * Offline Data Transfer State. Possible values include: 'InProgress', 'Stopping', 'NotRunning', * 'Complete' */ readonly offlineDataTransferStatus?: string; } /** * Server Endpoint object. */ export interface ServerEndpoint extends ProxyResource { /** * Server Local path. */ serverLocalPath?: string; /** * Cloud Tiering. Possible values include: 'on', 'off' */ cloudTiering?: string; /** * Level of free space to be maintained by Cloud Tiering if it is enabled. */ volumeFreeSpacePercent?: number; /** * Tier files older than days. */ tierFilesOlderThanDays?: number; /** * Friendly Name */ friendlyName?: string; /** * Server Resource Id. */ serverResourceId?: string; /** * ServerEndpoint Provisioning State */ readonly provisioningState?: string; /** * ServerEndpoint lastWorkflowId */ readonly lastWorkflowId?: string; /** * Resource Last Operation Name */ readonly lastOperationName?: string; /** * Server Endpoint sync status */ readonly syncStatus?: ServerEndpointSyncStatus; /** * Offline data transfer. Possible values include: 'on', 'off' */ offlineDataTransfer?: string; /** * Offline data transfer storage account resource ID */ readonly offlineDataTransferStorageAccountResourceId?: string; /** * Offline data transfer storage account tenant ID */ readonly offlineDataTransferStorageAccountTenantId?: string; /** * Offline data transfer share name */ offlineDataTransferShareName?: string; } /** * Registered Server resource. */ export interface RegisteredServer extends ProxyResource { /** * Registered Server Certificate */ serverCertificate?: string; /** * Registered Server Agent Version */ agentVersion?: string; /** * Registered Server OS Version */ serverOSVersion?: string; /** * Registered Server Management Error Code */ serverManagementErrorCode?: number; /** * Registered Server last heart beat */ lastHeartBeat?: string; /** * Registered Server Provisioning State */ provisioningState?: string; /** * Registered Server serverRole */ serverRole?: string; /** * Registered Server clusterId */ clusterId?: string; /** * Registered Server clusterName */ clusterName?: string; /** * Registered Server serverId */ serverId?: string; /** * Registered Server storageSyncServiceUid */ storageSyncServiceUid?: string; /** * Registered Server lastWorkflowId */ lastWorkflowId?: string; /** * Resource Last Operation Name */ lastOperationName?: string; /** * Resource discoveryEndpointUri */ discoveryEndpointUri?: string; /** * Resource Location */ resourceLocation?: string; /** * Service Location */ serviceLocation?: string; /** * Friendly Name */ friendlyName?: string; /** * Management Endpoint Uri */ managementEndpointUri?: string; /** * Monitoring Configuration */ monitoringConfiguration?: string; } /** * Resource Move Info. */ export interface ResourcesMoveInfo { /** * Target resource group. */ targetResourceGroup?: string; /** * Collection of Resources. */ resources?: string[]; } /** * Workflow resource. */ export interface Workflow extends ProxyResource { /** * last step name */ lastStepName?: string; /** * workflow status. Possible values include: 'active', 'expired', 'succeeded', 'aborted', * 'failed' */ status?: string; /** * operation direction. Possible values include: 'do', 'undo', 'cancel' */ operation?: string; /** * workflow steps */ steps?: string; /** * workflow last operation identifier. */ lastOperationId?: string; } /** * The operation supported by storage sync. */ export interface OperationDisplayInfo { /** * The description of the operation. */ description?: string; /** * The action that users can perform, based on their permission level. */ operation?: string; /** * Service provider: Microsoft StorageSync. */ provider?: string; /** * Resource on which the operation is performed. */ resource?: string; } /** * The operation supported by storage sync. */ export interface OperationEntity { /** * Operation name: {provider}/{resource}/{operation}. */ name?: string; /** * The operation supported by storage sync. */ display?: OperationDisplayInfo; /** * The origin. */ origin?: string; } /** * Operation Display Resource object. */ export interface OperationDisplayResource { /** * Operation Display Resource Provider. */ provider?: string; /** * Operation Display Resource. */ resource?: string; /** * Operation Display Resource Operation. */ operation?: string; /** * Operation Display Resource Description. */ description?: string; } /** * Parameters for a check name availability request. */ export interface CheckNameAvailabilityParameters { /** * The name to check for availability */ name: string; } /** * The CheckNameAvailability operation response. */ export interface CheckNameAvailabilityResult { /** * Gets a boolean value that indicates whether the name is available for you to use. If true, the * name is available. If false, the name has already been taken or invalid and cannot be used. */ readonly nameAvailable?: boolean; /** * Gets the reason that a Storage Sync Service name could not be used. The Reason element is only * returned if NameAvailable is false. Possible values include: 'Invalid', 'AlreadyExists' */ readonly reason?: string; /** * Gets an error message explaining the Reason value in more detail. */ readonly message?: string; } /** * Restore file spec. */ export interface RestoreFileSpec { /** * Restore file spec path */ path?: string; /** * Restore file spec isdir */ readonly isdir?: boolean; } /** * Post Restore Request */ export interface PostRestoreRequest { /** * Post Restore partition. */ partition?: string; /** * Post Restore replica group. */ replicaGroup?: string; /** * Post Restore request id. */ requestId?: string; /** * Post Restore Azure file share uri. */ azureFileShareUri?: string; /** * Post Restore Azure status. */ status?: string; /** * Post Restore Azure source azure file share uri. */ sourceAzureFileShareUri?: string; /** * Post Restore Azure failed file list. */ failedFileList?: string; /** * Post Restore restore file spec array. */ restoreFileSpec?: RestoreFileSpec[]; } /** * Pre Restore request object. */ export interface PreRestoreRequest { /** * Pre Restore partition. */ partition?: string; /** * Pre Restore replica group. */ replicaGroup?: string; /** * Pre Restore request id. */ requestId?: string; /** * Pre Restore Azure file share uri. */ azureFileShareUri?: string; /** * Pre Restore Azure status. */ status?: string; /** * Pre Restore Azure source azure file share uri. */ sourceAzureFileShareUri?: string; /** * Pre Restore backup metadata property bag. */ backupMetadataPropertyBag?: string; /** * Pre Restore restore file spec array. */ restoreFileSpec?: RestoreFileSpec[]; /** * Pre Restore pause wait for sync drain time period in seconds. */ pauseWaitForSyncDrainTimePeriodInSeconds?: number; } /** * Backup request */ export interface BackupRequest { /** * Azure File Share. */ azureFileShare?: string; } /** * Post Backup Response */ export interface PostBackupResponse { /** * cloud endpoint Name. */ readonly cloudEndpointName?: string; } /** * Parameters for updating an Storage sync service. */ export interface StorageSyncServiceUpdateParameters { /** * The user-specified tags associated with the storage sync service. */ tags?: { [propertyName: string]: string }; /** * The properties of the storage sync service. */ properties?: any; } /** * The resource model definition for a Azure Resource Manager resource with an etag. */ export interface AzureEntityResource extends Resource { /** * Resource Etag. */ readonly etag?: string; } /** * The list of storage sync operations. */ export interface OperationEntityListResult extends Array<OperationEntity> { /** * The link used to get the next page of operations. */ nextLink?: string; } /** * Array of StorageSyncServices */ export interface StorageSyncServiceArray extends Array<StorageSyncService> { } /** * Array of SyncGroup */ export interface SyncGroupArray extends Array<SyncGroup> { } /** * Array of CloudEndpoint */ export interface CloudEndpointArray extends Array<CloudEndpoint> { } /** * Array of ServerEndpoint */ export interface ServerEndpointArray extends Array<ServerEndpoint> { } /** * Array of RegisteredServer */ export interface RegisteredServerArray extends Array<RegisteredServer> { } /** * Array of Workflow */ export interface WorkflowArray extends Array<Workflow> { }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * An interval in time specifying the date and time for the inclusive start and exclusive end, i.e. * `[start, end)`. */ export interface DateTimeInterval { /** * A datetime indicating the inclusive/closed start of the time interval, i.e. `[`**`start`**`, * end)`. Specifying a `start` that occurs chronologically after `end` will result in an error. */ start: Date; /** * A datetime indicating the exclusive/open end of the time interval, i.e. `[start, * `**`end`**`)`. Specifying an `end` that occurs chronologically before `start` will result in * an error. */ end: Date; } /** * Specifies the date and time interval for a changes request. */ export interface ResourceChangesRequestParametersInterval extends DateTimeInterval {} /** * The parameters for a specific changes request. */ export interface ResourceChangesRequestParameters { /** * Specifies the list of resources for a changes request. */ resourceIds?: string[]; /** * The subscription id of resources to query the changes from. */ subscriptionId?: string; /** * Specifies the date and time interval for a changes request. */ interval: ResourceChangesRequestParametersInterval; /** * Acts as the continuation token for paged responses. */ skipToken?: string; /** * The maximum number of changes the client can accept in a paged response. */ top?: number; /** * The table name to query resources from. */ table?: string; /** * The flag if set to true will fetch property changes */ fetchPropertyChanges?: boolean; /** * The flag if set to true will fetch change snapshots */ fetchSnapshots?: boolean; } /** * Data on a specific resource snapshot. */ export interface ResourceSnapshotData { /** * The ID of the snapshot. */ snapshotId?: string; /** * The time when the snapshot was created. * The snapshot timestamp provides an approximation as to when a modification to a resource was * detected. There can be a difference between the actual modification time and the detection * time. This is due to differences in how operations that modify a resource are processed, * versus how operation that record resource snapshots are processed. */ timestamp: Date; /** * The resource snapshot content (in resourceChangeDetails response only). */ content?: any; } /** * The snapshot before the change. */ export interface ResourceChangeDataBeforeSnapshot extends ResourceSnapshotData {} /** * The snapshot after the change. */ export interface ResourceChangeDataAfterSnapshot extends ResourceSnapshotData {} /** * The resource property change */ export interface ResourcePropertyChange { /** * The property name */ propertyName: string; /** * The property value in before snapshot */ beforeValue?: string; /** * The property value in after snapshot */ afterValue?: string; /** * The change category. Possible values include: 'User', 'System' */ changeCategory: ChangeCategory; /** * The property change Type. Possible values include: 'Insert', 'Update', 'Remove' */ propertyChangeType: PropertyChangeType; } /** * Data on a specific change, represented by a pair of before and after resource snapshots. */ export interface ResourceChangeData { /** * The resource for a change. */ resourceId?: string; /** * The change ID. Valid and unique within the specified resource only. */ changeId: string; /** * The snapshot before the change. */ beforeSnapshot: ResourceChangeDataBeforeSnapshot; /** * The snapshot after the change. */ afterSnapshot: ResourceChangeDataAfterSnapshot; /** * The change type for snapshot. PropertyChanges will be provided in case of Update change type. * Possible values include: 'Create', 'Update', 'Delete' */ changeType?: ChangeType; /** * An array of resource property change */ propertyChanges?: ResourcePropertyChange[]; } /** * A list of changes associated with a resource over a specific time interval. */ export interface ResourceChangeList { /** * The pageable value returned by the operation, i.e. a list of changes to the resource. * * - The list is ordered from the most recent changes to the least recent changes. * - This list will be empty if there were no changes during the requested interval. * - The `Before` snapshot timestamp value of the oldest change can be outside of the specified * time interval. */ changes?: ResourceChangeData[]; /** * Skip token that encodes the skip information while executing the current request */ skipToken?: any; } /** * The parameters for a specific change details request. */ export interface ResourceChangeDetailsRequestParameters { /** * Specifies the list of resources for a change details request. */ resourceIds: string[]; /** * Specifies the list of change IDs for a change details request. */ changeIds: string[]; } /** * An interface representing ErrorDetails. * @summary Error details. */ export interface ErrorDetails { /** * Error code identifying the specific error. */ code: string; /** * A human readable error message. */ message: string; /** * Describes unknown properties. The value of an unknown property can be of "any" type. */ [property: string]: any; } /** * Error details. * @summary Error info. */ export interface ErrorModel { /** * Error code identifying the specific error. */ code: string; /** * A human readable error message. */ message: string; /** * Error details */ details?: ErrorDetails[]; } /** * An error response from the API. * @summary Error response. */ export interface ErrorResponse { /** * Error information. */ error: ErrorModel; } /** * The options for query evaluation */ export interface QueryRequestOptions { /** * Continuation token for pagination, capturing the next page size and offset, as well as the * context of the query. */ skipToken?: string; /** * The maximum number of rows that the query should return. Overrides the page size when * ```$skipToken``` property is present. */ top?: number; /** * The number of rows to skip from the beginning of the results. Overrides the next page offset * when ```$skipToken``` property is present. */ skip?: number; /** * Defines in which format query result returned. Possible values include: 'table', * 'objectArray'. Default value: 'objectArray'. */ resultFormat?: ResultFormat; /** * Only applicable for tenant and management group level queries to decide whether to allow * partial scopes for result in case the number of subscriptions exceed allowed limits. Default * value: false. */ allowPartialScopes?: boolean; } /** * The options for facet evaluation */ export interface FacetRequestOptions { /** * The column name or query expression to sort on. Defaults to count if not present. */ sortBy?: string; /** * The sorting order by the selected column (count by default). Possible values include: 'asc', * 'desc'. Default value: 'desc'. */ sortOrder?: FacetSortOrder; /** * Specifies the filter condition for the 'where' clause which will be run on main query's * result, just before the actual faceting. */ filter?: string; /** * The maximum number of facet rows that should be returned. */ top?: number; } /** * A request to compute additional statistics (facets) over the query results. */ export interface FacetRequest { /** * The column or list of columns to summarize by */ expression: string; /** * The options for facet evaluation */ options?: FacetRequestOptions; } /** * Describes a query to be executed. */ export interface QueryRequest { /** * Azure subscriptions against which to execute the query. */ subscriptions?: string[]; /** * Azure management groups against which to execute the query. Example: [ 'mg1', 'mg2' ] */ managementGroups?: string[]; /** * The resources query. */ query: string; /** * The query evaluation options */ options?: QueryRequestOptions; /** * An array of facet requests to be computed against the query result. */ facets?: FacetRequest[]; } /** * Contains the possible cases for Facet. */ export type FacetUnion = Facet | FacetResult | FacetError; /** * A facet containing additional statistics on the response of a query. Can be either FacetResult * or FacetError. */ export interface Facet { /** * Polymorphic Discriminator */ resultType: "Facet"; /** * Facet expression, same as in the corresponding facet request. */ expression: string; } /** * Query result. */ export interface QueryResponse { /** * Number of total records matching the query. */ totalRecords: number; /** * Number of records returned in the current response. In the case of paging, this is the number * of records in the current page. */ count: number; /** * Indicates whether the query results are truncated. Possible values include: 'true', 'false' */ resultTruncated: ResultTruncated; /** * When present, the value can be passed to a subsequent query call (together with the same query * and scopes used in the current request) to retrieve the next page of data. */ skipToken?: string; /** * Query output in JObject array or Table format. */ data: any; /** * Query facets. */ facets?: FacetUnion[]; } /** * Query result column descriptor. */ export interface Column { /** * Column name. */ name: string; /** * Column data type. Possible values include: 'string', 'integer', 'number', 'boolean', 'object' */ type: ColumnDataType; } /** * Query output in tabular format. */ export interface Table { /** * Query result column descriptors. */ columns: Column[]; /** * Query result rows. */ rows: any[][]; } /** * Successfully executed facet containing additional statistics on the response of a query. */ export interface FacetResult { /** * Polymorphic Discriminator */ resultType: "FacetResult"; /** * Facet expression, same as in the corresponding facet request. */ expression: string; /** * Number of total records in the facet results. */ totalRecords: number; /** * Number of records returned in the facet response. */ count: number; /** * A JObject array or Table containing the desired facets. Only present if the facet is valid. */ data: any; } /** * A facet whose execution resulted in an error. */ export interface FacetError { /** * Polymorphic Discriminator */ resultType: "FacetError"; /** * Facet expression, same as in the corresponding facet request. */ expression: string; /** * An array containing detected facet errors with details. */ errors: ErrorDetails[]; } /** * Display metadata associated with the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft Resource Graph. */ provider?: string; /** * Resource on which the operation is performed etc. */ resource?: string; /** * Type of operation: get, read, delete, etc. */ operation?: string; /** * Description for the operation. */ description?: string; } /** * Resource Graph REST API operation definition. */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation} */ name?: string; /** * Display metadata associated with the operation. */ display?: OperationDisplay; /** * The origin of operations. */ origin?: string; } /** * An interface representing ResourcesHistoryRequestOptions. */ export interface ResourcesHistoryRequestOptions { interval?: DateTimeInterval; top?: number; skip?: number; skipToken?: string; /** * Possible values include: 'table', 'objectArray' */ resultFormat?: ResultFormat1; } /** * An interface representing ResourcesHistoryRequest. */ export interface ResourcesHistoryRequest { subscriptions?: string[]; query?: string; options?: ResourcesHistoryRequestOptions; managementGroupId?: string; } /** * An interface representing ResourceGraphClientOptions. */ export interface ResourceGraphClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * Result of the request to list Resource Graph operations. It contains a list of operations and a * URL link to get the next set of results. * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> {} /** * Defines values for ChangeType. * Possible values include: 'Create', 'Update', 'Delete' * @readonly * @enum {string} */ export type ChangeType = "Create" | "Update" | "Delete"; /** * Defines values for ChangeCategory. * Possible values include: 'User', 'System' * @readonly * @enum {string} */ export type ChangeCategory = "User" | "System"; /** * Defines values for PropertyChangeType. * Possible values include: 'Insert', 'Update', 'Remove' * @readonly * @enum {string} */ export type PropertyChangeType = "Insert" | "Update" | "Remove"; /** * Defines values for ResultFormat. * Possible values include: 'table', 'objectArray' * @readonly * @enum {string} */ export type ResultFormat = "table" | "objectArray"; /** * Defines values for FacetSortOrder. * Possible values include: 'asc', 'desc' * @readonly * @enum {string} */ export type FacetSortOrder = "asc" | "desc"; /** * Defines values for ResultTruncated. * Possible values include: 'true', 'false' * @readonly * @enum {string} */ export type ResultTruncated = "true" | "false"; /** * Defines values for ColumnDataType. * Possible values include: 'string', 'integer', 'number', 'boolean', 'object' * @readonly * @enum {string} */ export type ColumnDataType = "string" | "integer" | "number" | "boolean" | "object"; /** * Defines values for ResultFormat1. * Possible values include: 'table', 'objectArray' * @readonly * @enum {string} */ export type ResultFormat1 = "table" | "objectArray"; /** * Contains response data for the resourceChanges operation. */ export type ResourceChangesResponse = ResourceChangeList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ResourceChangeList; }; }; /** * Contains response data for the resourceChangeDetails operation. */ export type ResourceChangeDetailsResponse = Array<ResourceChangeData> & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ResourceChangeData[]; }; }; /** * Contains response data for the resources operation. */ export type ResourcesResponse = QueryResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: QueryResponse; }; }; /** * Contains response data for the resourcesHistory operation. */ export type ResourcesHistoryResponse = { /** * The parsed response body. */ body: any; /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: any; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; };
the_stack
import * as i18n from '../../../../core/i18n/i18n.js'; import * as Platform from '../../../../core/platform/platform.js'; import * as TextUtils from '../../../../models/text_utils/text_utils.js'; import * as UI from '../../legacy.js'; const UIStrings = { /** *@description Text to find an item */ find: 'Find', }; const str_ = i18n.i18n.registerUIStrings('ui/legacy/components/source_frame/XMLView.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class XMLView extends UI.Widget.Widget implements UI.SearchableView.Searchable { private readonly treeOutline: UI.TreeOutline.TreeOutlineInShadow; private searchableView!: UI.SearchableView.SearchableView|null; private currentSearchFocusIndex: number; private currentSearchTreeElements: XMLViewNode[]; private searchConfig!: UI.SearchableView.SearchConfig|null; constructor(parsedXML: Document) { super(true); this.registerRequiredCSS('ui/legacy/components/source_frame/xmlView.css'); this.contentElement.classList.add('shadow-xml-view', 'source-code'); this.treeOutline = new UI.TreeOutline.TreeOutlineInShadow(); this.treeOutline.registerRequiredCSS('ui/legacy/components/source_frame/xmlTree.css'); this.contentElement.appendChild(this.treeOutline.element); this.currentSearchFocusIndex = 0; this.currentSearchTreeElements = []; XMLViewNode.populate(this.treeOutline, parsedXML, this); const firstChild = this.treeOutline.firstChild(); if (firstChild) { firstChild.select(true /* omitFocus */, false /* selectedByUser */); } } static createSearchableView(parsedXML: Document): UI.SearchableView.SearchableView { const xmlView = new XMLView(parsedXML); const searchableView = new UI.SearchableView.SearchableView(xmlView, null); searchableView.setPlaceholder(i18nString(UIStrings.find)); xmlView.searchableView = searchableView; xmlView.show(searchableView.element); return searchableView; } static parseXML(text: string, mimeType: string): Document|null { let parsedXML; try { switch (mimeType) { case 'application/xhtml+xml': case 'application/xml': case 'image/svg+xml': case 'text/html': case 'text/xml': parsedXML = (new DOMParser()).parseFromString(text, mimeType); } } catch (e) { return null; } if (!parsedXML || parsedXML.body) { return null; } return parsedXML; } private jumpToMatch(index: number, shouldJump: boolean): void { if (!this.searchConfig) { return; } const regex = this.searchConfig.toSearchRegex(true); const previousFocusElement = this.currentSearchTreeElements[this.currentSearchFocusIndex]; if (previousFocusElement) { previousFocusElement.setSearchRegex(regex); } const newFocusElement = this.currentSearchTreeElements[index]; if (newFocusElement) { this.updateSearchIndex(index); if (shouldJump) { newFocusElement.reveal(true); } newFocusElement.setSearchRegex(regex, UI.UIUtils.highlightedCurrentSearchResultClassName); } else { this.updateSearchIndex(0); } } private updateSearchCount(count: number): void { if (!this.searchableView) { return; } this.searchableView.updateSearchMatchesCount(count); } private updateSearchIndex(index: number): void { this.currentSearchFocusIndex = index; if (!this.searchableView) { return; } this.searchableView.updateCurrentMatchIndex(index); } innerPerformSearch(shouldJump: boolean, jumpBackwards?: boolean): void { if (!this.searchConfig) { return; } let newIndex: number = this.currentSearchFocusIndex; const previousSearchFocusElement = this.currentSearchTreeElements[newIndex]; this.innerSearchCanceled(); this.currentSearchTreeElements = []; const regex = this.searchConfig.toSearchRegex(true); for (let element: (UI.TreeOutline.TreeElement|null) = (this.treeOutline.rootElement() as UI.TreeOutline.TreeElement | null); element; element = element.traverseNextTreeElement(false)) { if (!(element instanceof XMLViewNode)) { continue; } const hasMatch = element.setSearchRegex(regex); if (hasMatch) { this.currentSearchTreeElements.push(element); } if (previousSearchFocusElement === element) { const currentIndex = this.currentSearchTreeElements.length - 1; if (hasMatch || jumpBackwards) { newIndex = currentIndex; } else { newIndex = currentIndex + 1; } } } this.updateSearchCount(this.currentSearchTreeElements.length); if (!this.currentSearchTreeElements.length) { this.updateSearchIndex(0); return; } newIndex = Platform.NumberUtilities.mod(newIndex, this.currentSearchTreeElements.length); this.jumpToMatch(newIndex, shouldJump); } private innerSearchCanceled(): void { for (let element: (UI.TreeOutline.TreeElement|null) = (this.treeOutline.rootElement() as UI.TreeOutline.TreeElement | null); element; element = element.traverseNextTreeElement(false)) { if (!(element instanceof XMLViewNode)) { continue; } element.revertHighlightChanges(); } this.updateSearchCount(0); this.updateSearchIndex(0); } searchCanceled(): void { this.searchConfig = null; this.currentSearchTreeElements = []; this.innerSearchCanceled(); } performSearch(searchConfig: UI.SearchableView.SearchConfig, shouldJump: boolean, jumpBackwards?: boolean): void { this.searchConfig = searchConfig; this.innerPerformSearch(shouldJump, jumpBackwards); } jumpToNextSearchResult(): void { if (!this.currentSearchTreeElements.length) { return; } const newIndex = Platform.NumberUtilities.mod(this.currentSearchFocusIndex + 1, this.currentSearchTreeElements.length); this.jumpToMatch(newIndex, true); } jumpToPreviousSearchResult(): void { if (!this.currentSearchTreeElements.length) { return; } const newIndex = Platform.NumberUtilities.mod(this.currentSearchFocusIndex - 1, this.currentSearchTreeElements.length); this.jumpToMatch(newIndex, true); } supportsCaseSensitiveSearch(): boolean { return true; } supportsRegexSearch(): boolean { return true; } } export class XMLViewNode extends UI.TreeOutline.TreeElement { private readonly node: Node|ParentNode; private readonly closeTag: boolean; private highlightChanges: UI.UIUtils.HighlightChange[]; private readonly xmlView: XMLView; constructor(node: Node|ParentNode, closeTag: boolean, xmlView: XMLView) { super('', !closeTag && 'childElementCount' in node && Boolean(node.childElementCount)); this.node = node; this.closeTag = closeTag; this.selectable = true; this.highlightChanges = []; this.xmlView = xmlView; this.updateTitle(); } static populate( root: UI.TreeOutline.TreeOutline|UI.TreeOutline.TreeElement, xmlNode: Node|ParentNode, xmlView: XMLView): void { if (!(xmlNode instanceof Node)) { return; } let node: (ChildNode|null) = xmlNode.firstChild; while (node) { const currentNode = node; node = node.nextSibling; const nodeType = currentNode.nodeType; // ignore empty TEXT if (nodeType === 3 && currentNode.nodeValue && currentNode.nodeValue.match(/\s+/)) { continue; } // ignore ATTRIBUTE, ENTITY_REFERENCE, ENTITY, DOCUMENT, DOCUMENT_TYPE, DOCUMENT_FRAGMENT, NOTATION if ((nodeType !== 1) && (nodeType !== 3) && (nodeType !== 4) && (nodeType !== 7) && (nodeType !== 8)) { continue; } root.appendChild(new XMLViewNode(currentNode, false, xmlView)); } } setSearchRegex(regex: RegExp|null, additionalCssClassName?: string): boolean { this.revertHighlightChanges(); if (!regex) { return false; } if (this.closeTag && this.parent && !this.parent.expanded) { return false; } regex.lastIndex = 0; let cssClasses = UI.UIUtils.highlightedSearchResultClassName; if (additionalCssClassName) { cssClasses += ' ' + additionalCssClassName; } if (!this.listItemElement.textContent) { return false; } const content = this.listItemElement.textContent.replace(/\xA0/g, ' '); let match = regex.exec(content); const ranges = []; while (match) { ranges.push(new TextUtils.TextRange.SourceRange(match.index, match[0].length)); match = regex.exec(content); } if (ranges.length) { UI.UIUtils.highlightRangesWithStyleClass(this.listItemElement, ranges, cssClasses, this.highlightChanges); } return Boolean(this.highlightChanges.length); } revertHighlightChanges(): void { UI.UIUtils.revertDomChanges(this.highlightChanges); this.highlightChanges = []; } private updateTitle(): void { const node = this.node; if (!('nodeType' in node)) { return; } switch (node.nodeType) { case 1: { // ELEMENT if (node instanceof Element) { const tag = node.tagName; if (this.closeTag) { this.setTitle(['</' + tag + '>', 'shadow-xml-view-tag']); return; } const titleItems = ['<' + tag, 'shadow-xml-view-tag']; const attributes = node.attributes; for (let i = 0; i < attributes.length; ++i) { const attributeNode = attributes.item(i); if (!attributeNode) { return; } titleItems.push( '\xA0', 'shadow-xml-view-tag', attributeNode.name, 'shadow-xml-view-attribute-name', '="', 'shadow-xml-view-tag', attributeNode.value, 'shadow-xml-view-attribute-value', '"', 'shadow-xml-view-tag'); } if (!this.expanded) { if (node.childElementCount) { titleItems.push( '>', 'shadow-xml-view-tag', '…', 'shadow-xml-view-comment', '</' + tag, 'shadow-xml-view-tag'); } else if (node.textContent) { titleItems.push( '>', 'shadow-xml-view-tag', node.textContent, 'shadow-xml-view-text', '</' + tag, 'shadow-xml-view-tag'); } else { titleItems.push(' /', 'shadow-xml-view-tag'); } } titleItems.push('>', 'shadow-xml-view-tag'); this.setTitle(titleItems); return; } return; } case 3: { // TEXT if (node.nodeValue) { this.setTitle([node.nodeValue, 'shadow-xml-view-text']); } return; } case 4: { // CDATA if (node.nodeValue) { this.setTitle([ '<![CDATA[', 'shadow-xml-view-cdata', node.nodeValue, 'shadow-xml-view-text', ']]>', 'shadow-xml-view-cdata', ]); } return; } case 7: { // PROCESSING_INSTRUCTION if (node.nodeValue) { this.setTitle(['<?' + node.nodeName + ' ' + node.nodeValue + '?>', 'shadow-xml-view-processing-instruction']); } return; } case 8: { // COMMENT this.setTitle(['<!--' + node.nodeValue + '-->', 'shadow-xml-view-comment']); return; } } } private setTitle(items: string[]): void { const titleFragment = document.createDocumentFragment(); for (let i = 0; i < items.length; i += 2) { titleFragment.createChild('span', items[i + 1]).textContent = items[i]; } this.title = titleFragment; this.xmlView.innerPerformSearch(false, false); } onattach(): void { this.listItemElement.classList.toggle('shadow-xml-view-close-tag', this.closeTag); } onexpand(): void { this.updateTitle(); } oncollapse(): void { this.updateTitle(); } async onpopulate(): Promise<void> { XMLViewNode.populate(this, this.node, this.xmlView); this.appendChild(new XMLViewNode(this.node, true, this.xmlView)); } }
the_stack
import { IRawModel, getMeta, setMeta, isArrayLike, mobx, IObservable, IObservableArray, removeFromArray, replaceInArray } from '@datx/utils'; import { PureModel } from './PureModel'; import { IType } from './interfaces/IType'; import { TFilterFn } from './interfaces/TFilterFn'; import { IIdentifier } from './interfaces/IIdentifier'; import { IModelRef } from './interfaces/IModelRef'; import { IModelConstructor } from './interfaces/IModelConstructor'; import { isModelReference, getModelType, getModelId, getModelCollection, updateModel, updateModelCollection, modelToJSON, } from './helpers/model/utils'; import { PatchType } from './enums/PatchType'; import { triggerAction } from './helpers/patch'; import { upsertModel, initModels } from './helpers/collection'; import { MetaClassField } from './enums/MetaClassField'; import { IFieldDefinition } from './Attribute'; import { IBucket } from './interfaces/IBucket'; import { MetaModelField } from './enums/MetaModelField'; import { IRawView } from './interfaces/IRawView'; import { IRawCollection } from './interfaces/IRawCollection'; import { View } from './View'; import { error } from './helpers/format'; export class PureCollection { public static types: Array<typeof PureModel> = []; public static defaultModel?: typeof PureModel = PureModel; public static views: Record< string, { modelType: IType | PureModel; sortMethod?: string | ((PureModel) => any); unique?: boolean; mixins?: Array<(view: any) => any>; } > = {}; private readonly __data: IObservableArray<PureModel> = mobx.observable.array([], { deep: false }); private readonly __views: Array<string> = []; private __dataMap: Record<string, Record<string, PureModel>> = (mobx.observable.object({}, undefined, { deep: false, }) as unknown) as Record<string, Record<string, PureModel>>; private __dataList: Record<string, IObservableArray<PureModel>> = (mobx.observable.object({}, undefined, { deep: false, }) as unknown) as Record<string, IObservableArray<PureModel>>; constructor(data: Array<IRawModel> | IRawCollection = []) { mobx.extendObservable(this, {}); if (isArrayLike(data)) { this.insert(data as Array<IRawModel>); } else if (data && 'models' in data) { this.insert(data.models); } const staticCollection = this.constructor as typeof PureCollection; const initViews = data && 'views' in data ? data.views : {}; Object.keys(staticCollection.views).forEach((key) => { const view = staticCollection.views[key]; const init = initViews[key] || view; this.addView(key, init.modelType, { mixins: view.mixins, models: init.models || [], sortMethod: view.sortMethod, unique: init.unique, }); }); } public addView<T extends PureModel = PureModel>( name: string, type: IModelConstructor<T> | IType, { sortMethod, models = [], unique, mixins, }: { sortMethod?: string | ((item: T) => any); models?: Array<IIdentifier | T>; unique?: boolean; mixins?: Array<(view: any) => any>; } = {}, ): View<T> { if (name in this && this[name]) { throw error('The name is already taken'); } const ViewConstructor = mixins ? (mixins.reduce((view: any, mixin: (view: any) => any) => { return mixin(view); }, View) as typeof View) : View; this.__views.push(name); this[name] = new ViewConstructor<T>(type, this, sortMethod, models, unique); return this[name]; } /** * Function for inserting raw models into the collection. Used when hydrating the collection * * @param {Array<IRawModel>} data Raw model data * @returns {Array<PureModel>} A list of initialized models * @memberof Collection */ public insert(data: Array<Partial<IRawModel>>): Array<PureModel> { const models = initModels(this, data); this.__insertModel(models); return models; } public hasItem(model: PureModel): boolean { const id = getModelId(model); return Boolean(this.findOne(model, id)); } public add<T extends PureModel>(data: T): T; public add<T extends PureModel>(data: Array<T>): Array<T>; public add<T extends PureModel>( data: Array<IRawModel | Record<string, any>>, model: IType | IModelConstructor<T>, ): Array<T>; public add<T extends PureModel>( data: IRawModel | Record<string, any>, model: IType | IModelConstructor<T>, ): T; public add( data: | PureModel | IRawModel | Record<string, any> | Array<PureModel | IRawModel | Record<string, any>>, model?: IType | IModelConstructor, ): PureModel | Array<PureModel> { return isArrayLike(data) ? this.__addArray(data as Array<PureModel | IRawModel | Record<string, any>>, model) : this.__addSingle(data, model); } public filter(test: TFilterFn): Array<PureModel> { return this.__data.filter(test); } public findOne<T extends PureModel>( type: IType | T | IModelConstructor<T>, id: IIdentifier | PureModel, ): T | null; public findOne<T extends PureModel>(ref: IModelRef): T | null; public findOne( model: IType | typeof PureModel | IModelRef, id?: IIdentifier | PureModel, ): PureModel | null { if (id instanceof PureModel) { return id; } if (isModelReference(model)) { return this.__findOneByType((model as IModelRef).type, (model as IModelRef).id); } if (id === null || id === undefined) { // ID mybe `""` or `0` throw new Error('The identifier is missing'); } return this.__findOneByType(model as typeof PureModel, id); } public findAll<T extends PureModel>(model?: IType | IModelConstructor<T>): IObservableArray<T> { if (model) { const type = getModelType(model); if (!(type in this.__dataList)) { mobx.runInAction(() => { mobx.set(this.__dataList, { [type]: mobx.observable.array([]) }); }); } return this.__dataList[type] as IObservableArray<T>; } return this.__data as IObservableArray<T>; } public find(test: TFilterFn): PureModel | null { return this.__data.find(test) || null; } public removeOne(type: IType | typeof PureModel, id: IIdentifier): void; public removeOne(model: PureModel | IModelRef): void; public removeOne(obj: IType | typeof PureModel | PureModel | IModelRef, id?: IIdentifier): void { let model: PureModel | null = null; if (typeof obj === 'object') { model = obj; } else if (id) { model = this.findOne(obj, id); } if (model) { this.__removeModel(model); } } public removeAll(type: IType | typeof PureModel): void { this.__removeModel(this.findAll(type).slice()); } public reset(): void { this.__data.forEach((model) => { setMeta(model, MetaModelField.Collection, undefined); triggerAction( { oldValue: modelToJSON(model) as Record<string, any>, patchType: PatchType.REMOVE, }, model, ); }); replaceInArray(this.__data, []); this.__dataList = (mobx.observable.object({}, {}, { deep: false }) as unknown) as IObservable & Record<string, IObservableArray<PureModel>>; this.__dataMap = (mobx.observable.object({}, {}, { deep: false }) as unknown) as IObservable & Record<string, Record<string, PureModel>>; } public toJSON(): IRawCollection { const views: Record<string, IRawView> = {}; this.__views.forEach((key) => { views[key] = this[key].toJSON(); }); return { models: this.__data.map(modelToJSON), views, }; } public get snapshot(): IRawCollection { return this.toJSON(); } @mobx.computed public get length(): number { return this.__data.length; } public getAllModels(): Array<PureModel> { return this.__data.slice(); } private __findOneByType( model: IType | typeof PureModel | PureModel, id: IIdentifier, ): PureModel | null { const type = getModelType(model); if (!type) { return null; } const stringType = type.toString(); const stringId = id.toString(); mobx.runInAction(() => { if (!(type in this.__dataMap)) { mobx.set( this.__dataMap, stringType, mobx.observable.object({ [stringId]: null }, {}, { deep: false }), ); } else if (!(stringId in this.__dataMap[stringType])) { mobx.set(this.__dataMap[stringType], stringId, null); } }); return this.__dataMap[stringType][stringId] || null; } private __addArray<T extends PureModel>(data: Array<T>): Array<T>; private __addArray<T extends PureModel>( data: Array<Record<string, any>>, model?: IType | IModelConstructor<T>, ): Array<T>; private __addArray( data: Array<PureModel | Record<string, any>>, model?: IType | IModelConstructor, ): Array<PureModel> { return data.filter(Boolean).map((item) => this.__addSingle(item, model)); } private __addSingle<T extends PureModel>(data: T): T; private __addSingle<T extends PureModel>( data: Record<string, any>, model?: IType | IModelConstructor<T>, ): T; private __addSingle( data: PureModel | Record<string, any> | IIdentifier | IModelRef, model?: number | IType | IModelConstructor, ): PureModel { if (!data || typeof data === 'number' || typeof data === 'string' || isModelReference(data)) { return data; } if (data instanceof PureModel) { if (!this.hasItem(data)) { this.__insertModel(data); } return data; } if (!model && model !== 0) { throw error('The type needs to be defined if the object is not an instance of the model.'); } const type = getModelType(model as IType | typeof PureModel); const modelInstance = upsertModel(data, type, this); const collectionTypes = (this.constructor as typeof PureCollection).types.map(getModelType); if (!collectionTypes.includes(type) && (typeof model === 'object' || typeof model === 'function')) { throw new Error(`The model type ${type} was not found. Did you forget to add it to collection types?`); } this.__insertModel(modelInstance, type); return modelInstance; } protected __removeModel(model: PureModel | Array<PureModel>, type?: IType, id?: IIdentifier): void { if (isArrayLike(model)) { (model as Array<PureModel>).forEach((item) => { this.__removeModel(item, type, id); }); return; } const modelType = type || getModelType(model); const modelId = id || getModelId(model); triggerAction( { oldValue: mobx.toJS(modelToJSON(model)) as Record<string, any>, patchType: PatchType.REMOVE, }, model, ); mobx.runInAction(() => { removeFromArray(this.__data, model); removeFromArray(this.__dataList[modelType], model); mobx.set(this.__dataMap[modelType], modelId.toString(), undefined); }); this.__data.forEach((item) => { const fields = getMeta<Record<string, IFieldDefinition>>( item, MetaClassField.Fields, {}, true, true, ); const refKeys = Object.keys(fields || {}); refKeys .map((key) => getMeta(item, `ref_${key}`)) .filter(Boolean) .forEach((bucket: IBucket<PureModel>) => { if (isArrayLike(bucket.value) && (bucket.value as Array<PureModel>).includes(item)) { bucket.value = (bucket.value as Array<PureModel>).filter( (bucketModel) => bucketModel !== item, ); } else if (bucket.value === item) { bucket.value = null; } }); }); updateModelCollection(model, undefined); } private __insertModel(model: PureModel | Array<PureModel>, type?: IType, id?: IIdentifier): void { if (isArrayLike(model)) { (model as Array<PureModel>).forEach((item) => { this.__insertModel(item, type, id); }); return; } const collection = getModelCollection(model); if (collection && collection !== this) { throw error('A model can be in a single collection at once'); } const modelType = type || getModelType(model); const modelId = id || getModelId(model); const stringType = modelType.toString(); const existingModel = this.findOne(modelType, modelId); if (existingModel) { if (existingModel !== model) { updateModel(existingModel, model); } return; } mobx.runInAction(() => { this.__data.push(model); if (modelType in this.__dataList) { this.__dataList[modelType].push(model); } else { mobx.set(this.__dataList, stringType, mobx.observable.array([model], { deep: false })); } if (modelType in this.__dataMap) { mobx.set(this.__dataMap[modelType], modelId.toString(), model); } else { mobx.set( this.__dataMap, stringType, mobx.observable.object({ [modelId]: model }, {}, { deep: false }), ); } updateModelCollection(model, this); }); triggerAction( { newValue: modelToJSON(model) as Record<string, any>, patchType: PatchType.CRATE, }, model, ); } // @ts-ignore - Used outside of the class, but marked as private to avoid undocumented use private __changeModelId(oldId: IIdentifier, newId: IIdentifier, type: IType): void { this.__dataMap[type][newId] = this.__dataMap[type][oldId]; delete this.__dataMap[type][oldId]; } }
the_stack
import { expect, test } from '@jest/globals'; import { float, float32, int8, integer, PrimaryKey, Reference } from '../src/reflection/type'; import { is } from '../src/typeguard'; test('primitive string', () => { expect(is<string>('a')).toEqual(true); expect(is<string>(123)).toEqual(false); expect(is<string>(true)).toEqual(false); expect(is<string>({})).toEqual(false); }); test('primitive number', () => { expect(is<number>('a')).toEqual(false); expect(is<number>(123)).toEqual(true); expect(is<number>(true)).toEqual(false); expect(is<number>({})).toEqual(false); }); test('primitive number integer', () => { expect(is<integer>('a')).toEqual(false); expect(is<integer>(123)).toEqual(true); expect(is<integer>(123.4)).toEqual(false); expect(is<integer>(true)).toEqual(false); expect(is<integer>({})).toEqual(false); }); test('primitive number int8', () => { expect(is<int8>('a')).toEqual(false); expect(is<int8>(123)).toEqual(true); expect(is<int8>(123.4)).toEqual(false); expect(is<int8>(true)).toEqual(false); expect(is<int8>({})).toEqual(false); expect(is<int8>(127)).toEqual(true); expect(is<int8>(128)).toEqual(false); expect(is<int8>(-128)).toEqual(true); expect(is<int8>(-129)).toEqual(false); expect(is<int8>(129)).toEqual(false); }); test('primitive number float', () => { expect(is<float>('a')).toEqual(false); expect(is<float>(123)).toEqual(true); expect(is<float>(123.4)).toEqual(true); expect(is<float>(true)).toEqual(false); expect(is<float>({})).toEqual(false); }); test('primitive number float32', () => { expect(is<float32>('a')).toEqual(false); expect(is<float32>(123)).toEqual(true); expect(is<float32>(123.4)).toEqual(true); expect(is<float32>(3.40282347e+38)).toEqual(true); //JS precision issue: expect(is<float32>(3.40282347e+38 + 100000000000000000000000)).toEqual(false); expect(is<float32>(-3.40282347e+38)).toEqual(true); expect(is<float32>(-3.40282347e+38 - 100000000000000000000000)).toEqual(false); expect(is<float32>(true)).toEqual(false); expect(is<float32>({})).toEqual(false); }); test('enum', () => { enum MyEnum { a, b, c } expect(is<MyEnum>(0)).toEqual(true); expect(is<MyEnum>(1)).toEqual(true); expect(is<MyEnum>(2)).toEqual(true); expect(is<MyEnum>(3)).toEqual(false); expect(is<MyEnum>(undefined)).toEqual(false); expect(is<MyEnum>({})).toEqual(false); expect(is<MyEnum>(true)).toEqual(false); }); test('enum const', () => { const enum MyEnum { a, b, c } expect(is<MyEnum>(0)).toEqual(true); expect(is<MyEnum>(1)).toEqual(true); expect(is<MyEnum>(2)).toEqual(true); expect(is<MyEnum>(3)).toEqual(false); expect(is<MyEnum>(undefined)).toEqual(false); expect(is<MyEnum>({})).toEqual(false); expect(is<MyEnum>(true)).toEqual(false); }); test('enum string', () => { enum MyEnum { a = 'a', b = 'b', c = 'c' } expect(is<MyEnum>('a')).toEqual(true); expect(is<MyEnum>('b')).toEqual(true); expect(is<MyEnum>('c')).toEqual(true); expect(is<MyEnum>(0)).toEqual(false); expect(is<MyEnum>(1)).toEqual(false); expect(is<MyEnum>(2)).toEqual(false); expect(is<MyEnum>(3)).toEqual(false); expect(is<MyEnum>(undefined)).toEqual(false); expect(is<MyEnum>({})).toEqual(false); expect(is<MyEnum>(true)).toEqual(false); }); test('array string', () => { expect(is<string[]>(['a'])).toEqual(true); expect(is<string[]>(['a', 'b'])).toEqual(true); expect(is<string[]>([1])).toEqual(false); expect(is<string[]>([1, 2])).toEqual(false); expect(is<string[]>(['a', 2])).toEqual(false); }); test('tuple', () => { expect(is<[string]>(['a'])).toEqual(true); expect(is<[string]>([2])).toEqual(false); expect(is<[string, string]>(['a', 'b'])).toEqual(true); expect(is<[string, string]>(['a'])).toEqual(false); expect(is<[string, number]>(['a', 3])).toEqual(true); expect(is<[string, number]>(['a', undefined])).toEqual(false); expect(is<[string, ...number[]]>(['a', 3])).toEqual(true); expect(is<[string, ...number[]]>(['a', 3, 4])).toEqual(true); expect(is<[string, ...number[]]>(['a', 3, 4, 5])).toEqual(true); expect(is<[string, ...number[]]>([3, 3, 4, 5])).toEqual(false); }); test('set', () => { expect(is<Set<string>>(new Set(['a']))).toEqual(true); expect(is<Set<string>>(new Set(['a', 'b']))).toEqual(true); expect(is<Set<string>>(new Set(['a', 2]))).toEqual(false); expect(is<Set<string>>(new Set([2, 3]))).toEqual(false); expect(is<Set<string>>([2, 3])).toEqual(false); }); test('map', () => { expect(is<Map<string, number>>(new Map([['a', 1]]))).toEqual(true); expect(is<Map<string, number>>(new Map([['a', 1], ['b', 2]]))).toEqual(true); expect(is<Map<string, number>>(new Map<any, any>([['a', 1], ['b', 'b']]))).toEqual(false); expect(is<Map<string, number>>(new Map<any, any>([[2, 1]]))).toEqual(false); }); test('literal', () => { expect(is<1>(1)).toEqual(true); expect(is<1>(2)).toEqual(false); expect(is<'abc'>('abc')).toEqual(true); expect(is<'abc'>('ab')).toEqual(false); expect(is<false>(false)).toEqual(true); expect(is<false>(true)).toEqual(false); expect(is<true>(true)).toEqual(true); expect(is<true>(false)).toEqual(false); }); test('union', () => { expect(is<string | number>(1)).toEqual(true); expect(is<string | number>('abc')).toEqual(true); expect(is<string | number>(false)).toEqual(false); }); test('deep union', () => { expect(is<string | (number | bigint)[]>(1)).toEqual(false); expect(is<string | (number | bigint)[]>('1')).toEqual(true); expect(is<string | (number | bigint)[]>([1])).toEqual(true); expect(is<string | (number | bigint)[]>([1n])).toEqual(true); expect(is<string | (number | bigint)[]>(['1'])).toEqual(false); }); test('object literal', () => { expect(is<{ a: string }>({ a: 'abc' })).toEqual(true); expect(is<{ a: string }>({ a: 123 })).toEqual(false); expect(is<{ a: string }>({})).toEqual(false); expect(is<{ a?: string }>({})).toEqual(true); expect(is<{ a?: string }>({ a: 'abc' })).toEqual(true); expect(is<{ a?: string }>({ a: 123 })).toEqual(false); expect(is<{ a: string, b: number }>({ a: 'a', b: 12 })).toEqual(true); expect(is<{ a: string, b: number }>({ a: 'a', b: 'asd' })).toEqual(false); }); test('class', () => { class A { a!: string; } class A2 { a?: string; } class A3 { a!: string; b!: number; } expect(is<A>({ a: 'abc' })).toEqual(true); expect(is<A>({ a: 123 })).toEqual(false); expect(is<A>({})).toEqual(false); expect(is<A2>({})).toEqual(true); expect(is<A2>({ a: 'abc' })).toEqual(true); expect(is<A2>({ a: 123 })).toEqual(false); expect(is<A3>({ a: 'a', b: 12 })).toEqual(true); expect(is<A3>({ a: 'a', b: 'asd' })).toEqual(false); }); test('index signature', () => { expect(is<{ [name: string]: string }>({})).toEqual(true); expect(is<{ [name: string]: string }>({ a: 'abc' })).toEqual(true); expect(is<{ [name: string]: string }>({ a: 123 })).toEqual(false); expect(is<{ [name: number]: string }>({ 1: 'abc' })).toEqual(true); expect(is<{ [name: number]: string }>({ 1: 123 })).toEqual(false); expect(is<{ [name: number]: string }>({ a: 'abc' })).toEqual(false); }); test('object literal methods', () => { expect(is<{ m: () => void }>({ m: (): void => undefined })).toEqual(true); expect(is<{ m: () => void }>({ m: false })).toEqual(false); expect(is<{ m: (name: string) => void }>({ m: () => undefined })).toEqual(true); //`() => undefined` has no types, so no __type emitted. Means return=any expect(is<{ m: (name: string) => void }>({ m: (name: string): void => undefined })).toEqual(true); expect(is<{ m: (name: string) => string }>({ m: (name: string): string => 'asd' })).toEqual(true); expect(is<{ m: (name: string) => string }>({ m: (name: string) => 'asd' })).toEqual(true); expect(is<{ m: (name: string) => string }>({ m: (name: number): string => 'asd' })).toEqual(false); expect(is<{ m: (name: string) => string }>({ m: (name: string): number => 2 })).toEqual(false); expect(is<{ m: (name: string) => any }>({ m: (name: string): number => 2 })).toEqual(true); expect(is<{ m: (name: any) => number }>({ m: (name: string): number => 2 })).toEqual(true); }); test('multiple index signature', () => { expect(is<{ [name: string]: string | number, [name: number]: string }>({})).toEqual(true); expect(is<{ [name: string]: string | number, [name: number]: number }>({ a: 'abc' })).toEqual(true); expect(is<{ [name: string]: string | number, [name: number]: number }>({ a: 123 })).toEqual(true); expect(is<{ [name: string]: string | number, [name: number]: number }>({ 1: 123 })).toEqual(true); expect(is<{ [name: string]: string | number, [name: number]: number }>({ 1: 'abc' })).toEqual(false); }); test('brands', () => { expect(is<number & PrimaryKey>(2)).toEqual(true); expect(is<number & PrimaryKey>('2')).toEqual(false); }); test('generic interface', () => { interface List<T> { items: T[]; } expect(is<List<number>>({ items: [1] })).toEqual(true); expect(is<List<string>>({ items: [1] })).toEqual(false); expect(is<List<string>>({ items: null })).toEqual(false); expect(is<List<string>>({ items: ['abc'] })).toEqual(true); }); test('generic alias', () => { type List<T> = T[]; expect(is<List<number>>([1])).toEqual(true); expect(is<List<string>>([1])).toEqual(false); expect(is<List<string>>(null)).toEqual(false); expect(is<List<string>>(['abc'])).toEqual(true); }); test('index signature ', () => { interface BagOfNumbers { [name: string]: number; } interface BagOfStrings { [name: string]: string; } expect(is<BagOfNumbers>({ a: 1 })).toEqual(true); expect(is<BagOfNumbers>({ a: 1, b: 2 })).toEqual(true); expect(is<BagOfNumbers>({ a: 'b' })).toEqual(false); expect(is<BagOfNumbers>({ a: 'b', b: 'c' })).toEqual(false); expect(is<BagOfStrings>({ a: 1 })).toEqual(false); expect(is<BagOfStrings>({ a: 1, b: 2 })).toEqual(false); expect(is<BagOfStrings>({ a: 'b' })).toEqual(true); expect(is<BagOfStrings>({ a: 'b', b: 'c' })).toEqual(true); }); test('reference', () => { class Image { id: number = 0; } class User { image?: Image & Reference; } expect(is<Image>({})).toEqual(false); expect(is<Image>({ id: 0 })).toEqual(true); expect(is<User>({})).toEqual(true); expect(is<User>({ image: undefined })).toEqual(true); expect(is<User>({ image: { id: 1 } })).toEqual(true); expect(is<User>({ image: { id: false } })).toEqual(false); expect(is<User>({ image: false })).toEqual(false); expect(is<User>({ image: null })).toEqual(false); expect(is<User>({ image: {} })).toEqual(false); }); test('template literal', () => { expect(is<`abc`>('abc')).toBe(true); expect(is<`abc`>('abce')).toBe(false); expect(is<`ab${string}`>('abc')).toBe(true); expect(is<`ab${string}`>('ab3')).toBe(true); type a = 'ab3' extends `ab${string}` ? true : false; type a2 = 'ab' extends `ab${string}` ? true : false; type a3 = 'a' extends `ab${string}` ? true : false; expect(is<`ab${string}`>('ab3')).toBe(true); expect(is<`ab${string}`>('ab')).toBe(true); expect(is<`ab${string}`>('a')).toBe(false); type b = 'ab3' extends `ab${number}` ? true : false; type b2 = 'ab' extends `ab${number}` ? true : false; type b3 = 'a' extends `ab${number}` ? true : false; type b4 = 'abc' extends `ab${number}` ? true : false; expect(is<`ab${number}`>('ab3')).toBe(true); expect(is<`ab${number}`>('ab')).toBe(false); expect(is<`ab${number}`>('a')).toBe(false); expect(is<`ab${number}`>('abc')).toBe(false); }); test('union template literal', () => { expect(is<`abc${number}` | number>('abc2')).toBe(true); expect(is<`abc${number}` | number>(23)).toBe(true); expect(is<`abc${number}` | number>('abcd')).toBe(false); expect(is<`abc${number}` | number>('abc')).toBe(false); }); test('class with literal and default', () => { class ConnectionOptions { readConcernLevel: 'local' = 'local'; } expect(is<ConnectionOptions>({readConcernLevel: 'local'})).toBe(true); expect(is<ConnectionOptions>({readConcernLevel: 'local2'})).toBe(false); }); test('union literal', () => { class ConnectionOptions { readConcernLevel: 'local' | 'majority' | 'linearizable' | 'available' = 'majority'; } expect(is<ConnectionOptions>({readConcernLevel: 'majority'})).toBe(true); expect(is<ConnectionOptions>({readConcernLevel: 'majority2'})).toBe(false); });
the_stack
declare function escape(str: any): any; declare function unescape(str: any): any; declare function config(configs: ConfigOption): void; declare const isNumber: (obj: any) => boolean; declare const isString: (obj: any) => boolean; declare function arrayPush(arr1: any, arr2: any): number; declare function arraySlice(arrLike?: any, start?: number, end?: number): any[]; declare function isObject(obj: any): boolean; declare function isArrayLike(obj: any): boolean; declare function each(obj: any, func: Function, isArr?: boolean): void; declare function noop(): void; declare const assign: { <T, U>(target: T, source: U): T & U; <T_1, U_1, V>(target: T_1, source1: U_1, source2: V): T_1 & U_1 & V; <T_2, U_2, V_1, W>(target: T_2, source1: U_2, source2: V_1, source3: W): T_2 & U_2 & V_1 & W; (target: object, ...sources: any[]): any; }; declare function upperFirst(str: string): string; declare function lowerFirst(str: string): string; declare function capitalize(str: string): string; declare function as<R, T = any>(value: T): R; declare const compile: (tmpl: any, tmplKey: any, fileName?: string, delimiters?: object, tmplRule?: object) => any; declare const compileH: (tmpl: any, tmplKey: any, fileName?: string, delimiters?: object, tmplRule?: object) => any; declare function precompile(tmpl: any, outputH?: boolean, tmplRule?: object, hasAst?: boolean): { useString: any; _no: number; _firstNode: boolean; } | { fns: { useString: any; _no: number; _firstNode: boolean; }; ast: any; }; declare const render: (tmpl: any, options: any) => any; declare const renderH: (tmpl: any, options: any) => any; declare const buildRender: (tmpl: any, params: any) => any; declare const buildRenderH: (tmpl: any, params: any) => any; declare const extensions: { [name: string]: ExtensionDelegate | ExtensionDelegateMultiParams; }; declare const extensionConfig: { [name: string]: ExtensionOption; }; declare function registerExtension<T extends ExtensionDelegate>(options: { [name: string]: T | { extension?: T; options?: ExtensionOption; }; }): void; declare function registerExtension<T extends ExtensionDelegate>(name: string, extension: T, options?: ExtensionOption, mergeConfig?: boolean): void; declare const filters: { [name: string]: FilterDelegate; }; declare const filterConfig: { [name: string]: FilterOption; }; declare function registerFilter(options: { [name: string]: FilterDelegate | { filter?: FilterDelegate; options?: FilterOption; }; }): void; declare function registerFilter(name: string, filter: FilterDelegate, options?: FilterOption, mergeConfig?: boolean): void; declare type ComponentOptionOrFunc = ComponentOption | ComponentOptionFunc; declare const components: { [name: string]: Component; }; declare const componentConfig: Map<Component, ComponentOptionOrFunc>; declare function registerComponent(options: { [name: string]: Component | { component?: Component; options?: ComponentOptionOrFunc; }; }): Component | Component[]; declare function registerComponent(name: string, component: Component, options?: ComponentOptionOrFunc): Component | Component[]; declare function getComponentConfig(name: Component): ComponentOptionOrFunc; declare function copyComponentConfig(component: Component, from: Component): Component; declare function getData(this: Template.Context | void, prop: any, data: any, hasSource?: any): any; declare type ElementType<P = any> = { [K in keyof JSX.IntrinsicElements]: P extends JSX.IntrinsicElements[K] ? K : never; }[keyof JSX.IntrinsicElements] | React.ComponentType<P>; /** * React(or other such as Preact) components. */ declare type Component = string | ElementType; /** * Properties of React(or other such as Preact) components. */ interface ComponentProps { [name: string]: any; } interface ComponentOption { hasEventObject?: boolean; targetPropName?: string; valuePropName?: string; getValueFromEvent?: Function; changeEventName?: string; needToJS?: boolean; [key: string]: any; } interface ComponentOptionFunc { (...args: any[]): ComponentOption; } declare namespace Template { interface Global { tmplKey: string; [key: string]: any; } interface Data { components?: Component | Component[]; [key: string]: any; } /** * React(or other such as Preact) component instance. */ interface ContextThis { [key: string]: any; } interface Context { $this: ContextThis; data: Data[] | any[]; getData: typeof getData; parent: Context; index: number; item: any; [key: string]: any; } interface ChildrenParams { data?: Data[] | any[]; index?: number; item?: any; newParent?: boolean; [key: string]: any; } interface RenderChildren { (params?: ChildrenParams): JSX.Element | any; } /** * NornJ render function, example: * * `template({ ...args1 }, { ...args2 }, ...)` */ interface RenderFunc { (...args: Data[]): any; } } interface FilterDelegateOption { _njOpts: number; useString?: boolean; global?: Template.Global; context?: Template.Context; outputH?: boolean; level?: number; } interface FilterDelegate { (...args: any[]): any; } interface FilterOption { onlyGlobal?: boolean; hasOptions?: boolean; isOperator?: boolean; hasLevel?: boolean; hasTmplCtx?: boolean; alias?: string; symbol?: string; placeholder?: string; [key: string]: any; } interface ExtensionDelegateOption extends FilterDelegateOption { name?: string; tagName?: Component; setTagName?(tagName: Component): void; tagProps?: ComponentProps; props?: ComponentProps; children?: Template.RenderChildren; value?: Template.RenderChildren; } interface ExtensionDelegate { (options?: ExtensionDelegateOption): any; } interface ExtensionDelegateMultiParams extends FilterDelegate { } declare enum ExtensionPrefixConfig { onlyLowerCase = "onlyLowerCase", onlyUpperCase = "onlyUpperCase", free = "free" } interface ExtensionOption { onlyGlobal?: boolean; useString?: boolean; newContext?: boolean | object; isSubTag?: boolean; isDirective?: boolean; isBindable?: boolean; useExpressionInProps?: boolean; hasName?: boolean; noTagName?: boolean; hasTagProps?: boolean; hasTmplCtx?: boolean; hasOutputH?: boolean; needPrefix?: boolean | keyof typeof ExtensionPrefixConfig; [key: string]: any; } interface ConfigOption { delimiters?: object; includeParser?: Function; createElement?: Function; outputH?: boolean; textMode?: boolean; noWsMode?: boolean; fixTagName?: boolean; } declare type JSXNode = JSX.Element | string | number | boolean | null | undefined; declare type JSXChild = JSXNode | Array<JSXNode>; interface Childrenable { children?: JSXChild; } interface Export { /** * `nj.taggedTmplH`, NornJ tagged templates syntax `nj` and `html`. */ (strs: TemplateStringsArray, ...args: any[]): Template.RenderFunc; components?: typeof components; componentConfig?: typeof componentConfig; /** * `nj.registerComponent`, support to register single or batch components to the NornJ. */ registerComponent?: typeof registerComponent; getComponentConfig?: typeof getComponentConfig; copyComponentConfig?: typeof copyComponentConfig; filters?: typeof filters; filterConfig?: typeof filterConfig; /** * `nj.registerFilter`, support to register single or batch filters and expressions to the NornJ. */ registerFilter?: typeof registerFilter; extensions?: typeof extensions; extensionConfig?: typeof extensionConfig; /** * `nj.registerExtension`, support to register single or batch tags and directives to the NornJ. */ registerExtension?: typeof registerExtension; /** * `nj.taggedTmpl`, NornJ tagged templates syntax `njs`. */ taggedTmpl?(strs: TemplateStringsArray, ...args: any[]): Template.RenderFunc; /** * `nj.htmlString`, NornJ tagged templates syntax `njs`. */ htmlString?(strs: TemplateStringsArray, ...args: any[]): Template.RenderFunc; /** * `nj.taggedTmplH`, NornJ tagged templates syntax `nj` and `html`. */ taggedTmplH?(strs: TemplateStringsArray, ...args: any[]): Template.RenderFunc; /** * `nj.taggedTmplH`, NornJ tagged templates syntax `nj` and `html`. */ html?(strs: TemplateStringsArray, ...args: any[]): Template.RenderFunc; /** * `nj.template`, NornJ tagged templates syntax `t`. */ template?(strs: TemplateStringsArray, ...args: any[]): any; /** * `nj.expression`, NornJ tagged templates syntax `n`. */ expression?(strs: TemplateStringsArray, ...args: any[]): any; /** * `nj.css`, NornJ tagged templates syntax `s`. */ css?(strs: TemplateStringsArray, ...args: any[]): any; compile?: typeof compile; compileH?: typeof compileH; precompile?: typeof precompile; render?: typeof render; renderH?: typeof renderH; buildRender?: typeof buildRender; buildRenderH?: typeof buildRenderH; arrayPush?: typeof arrayPush; arraySlice?: typeof arraySlice; isObject?: typeof isObject; isNumber?: typeof isNumber; isString?: typeof isString; isArrayLike?: typeof isArrayLike; each?: typeof each; noop?: typeof noop; assign?: typeof assign; upperFirst?: typeof upperFirst; lowerFirst?: typeof lowerFirst; capitalize?: typeof capitalize; as?: typeof as; config?: typeof config; includeParser?: Function; createElement?: Function; createRegexOperators?: Function; createFilterAlias?: Function; preAsts: { [name: string]: any; }; asts: { [name: string]: any; }; templates: { [name: string]: any; }; errorTitle: string; tmplRule: { [name: string]: any; }; textTag: string; noWsTag: string; outputH: boolean; textMode: boolean; noWsMode: boolean; fixTagName: boolean; escape?: typeof escape; unescape?: typeof unescape; global: { [name: string]: any; }; default?: Export; } declare const nj: Export; declare const taggedTmpl: (strs: TemplateStringsArray, ...args: any[]) => Template.RenderFunc; declare const taggedTmplH: (strs: TemplateStringsArray, ...args: any[]) => Template.RenderFunc; declare function template(strs: TemplateStringsArray, ...args: any[]): any; declare function expression(strs: TemplateStringsArray, ...args: any[]): any; declare function css(strs: TemplateStringsArray, ...args: any[]): any; export default nj; export { Childrenable, Component, ComponentOption, ComponentOptionFunc, ComponentProps, ConfigOption, ElementType, Export, ExtensionDelegate, ExtensionDelegateMultiParams, ExtensionDelegateOption, ExtensionOption, ExtensionPrefixConfig, FilterDelegate, FilterDelegateOption, FilterOption, JSXChild, JSXNode, Template, as, compile, compileH, css, expression, taggedTmplH as html, taggedTmpl as htmlString, registerComponent, registerExtension, registerFilter, render, renderH, taggedTmpl, taggedTmplH, template };
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { DiagramElement } from '../../../src/diagram/core/elements/diagram-element'; import { Canvas } from '../../../src/diagram/core/containers/canvas'; import { GridPanel, RowDefinition, ColumnDefinition } from '../../../src/diagram/core/containers/grid'; import { Margin } from '../../../src/diagram/core/appearance'; import { NodeConstraints } from '../../../src/diagram/enum/enum'; import { NodeModel } from '../../../src/diagram/objects/node-model'; import { MouseEvents } from '../../../spec/diagram/interaction/mouseevents.spec'; import { Selector } from '../../../src/diagram/objects/node'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; function resize(diagram: Diagram, direction: string): void { if ((diagram.selectedItems as Selector).nodes.length) { let diagramCanvas: HTMLElement; let left: number; let top: number; diagramCanvas = document.getElementById(diagram.element.id + 'content'); left = diagram.element.offsetLeft; top = diagram.element.offsetTop; let element: HTMLElement = document.getElementById('borderRect'); let mouseEvents: MouseEvents = new MouseEvents(); let x: number; let y: number; switch (direction) { case 'resizeSouth': x = Number(element.getAttribute('x')) + Number(element.getAttribute('width')) / 2; y = Number(element.getAttribute('y')) + Number(element.getAttribute('height')); break; case 'resizeEast': x = Number(element.getAttribute('x')) + Number(element.getAttribute('width')); y = Number(element.getAttribute('y')) + Number(element.getAttribute('height')) / 2; break; case 'resizeNorth': x = Number(element.getAttribute('x')) + Number(element.getAttribute('width')) / 2; y = Number(element.getAttribute('y')); break; case 'resizeWest': x = Number(element.getAttribute('x')); y = Number(element.getAttribute('y')) + Number(element.getAttribute('height')) / 2; break; } mouseEvents.mouseDownEvent(diagramCanvas, x + diagram.element.offsetLeft, y + diagram.element.offsetTop); mouseEvents.mouseMoveEvent(diagramCanvas, x + diagram.element.offsetLeft + 20, y + diagram.element.offsetTop); mouseEvents.mouseMoveEvent(diagramCanvas, x + diagram.element.offsetLeft + 20, y + diagram.element.offsetTop + 20); mouseEvents.mouseUpEvent(diagramCanvas, x + diagram.element.offsetLeft + 20, y + diagram.element.offsetTop + 20); } } describe('Diagram Control', () => { describe('Simple Grid panel without rows and columns', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram16' }); document.body.appendChild(ele); let grid: GridPanel = new GridPanel(); grid.offsetX = 300; grid.offsetY = 200; grid.width = 100; grid.height = 100; grid.style.fill = 'red'; diagram = new Diagram({ width: 1000, height: 1000, basicElements: [grid] }); diagram.appendTo('#diagram16'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking grid panel without rows and columns', (done: Function) => { expect(diagram.basicElements[0].actualSize.width == 100 && diagram.basicElements[0].actualSize.height == 100).toBe(true); done(); }); }); describe('Grid panel with row and without column', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram17' }); document.body.appendChild(ele); let grid: GridPanel = new GridPanel(); grid.offsetX = 300; grid.offsetY = 200; grid.width = 100; grid.height = 100; grid.style.fill = 'blue'; //Row Definition let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let colDefns: ColumnDefinition[] = []; /* let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 100; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 200; colDefns.push(colDefn2);*/ grid.setDefinitions(rowDefns, colDefns); diagram = new Diagram({ width: 1000, height: 1000, basicElements: [grid] }); diagram.appendTo('#diagram17'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking grid panel without rows and columns', (done: Function) => { expect(diagram.basicElements[0].actualSize.width == 100 && diagram.basicElements[0].actualSize.height == 100).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children.length == 2)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[0].bounds.x == 250 && (diagram.basicElements[0] as GridPanel).children[0].bounds.y == 150 && (diagram.basicElements[0] as GridPanel).children[0].bounds.width == 100 && (diagram.basicElements[0] as GridPanel).children[0].bounds.height == 50)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[1].bounds.x == 250 && (diagram.basicElements[0] as GridPanel).children[1].bounds.y == 200 && (diagram.basicElements[0] as GridPanel).children[1].bounds.width == 100 && (diagram.basicElements[0] as GridPanel).children[1].bounds.height == 50)).toBe(true); done(); }); }); describe('Grid panel with two rows and two columns', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram18' }); document.body.appendChild(ele); let grid: GridPanel = new GridPanel(); grid.offsetX = 300; grid.offsetY = 200; // grid.width = 100; // grid.height = 100; grid.style.fill = 'blue'; //Row Definition let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 100; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 200; colDefns.push(colDefn2); grid.setDefinitions(rowDefns, colDefns); diagram = new Diagram({ width: 1000, height: 1000, basicElements: [grid] }); diagram.appendTo('#diagram18'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking grid panel without rows and columns', (done: Function) => { expect(diagram.basicElements[0].actualSize.width == 300 && diagram.basicElements[0].actualSize.height == 100).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children.length == 4)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[0].bounds.x == 150 && (diagram.basicElements[0] as GridPanel).children[0].bounds.y == 150 && (diagram.basicElements[0] as GridPanel).children[0].bounds.width == 100 && (diagram.basicElements[0] as GridPanel).children[0].bounds.height == 50)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[1].bounds.x == 250 && (diagram.basicElements[0] as GridPanel).children[1].bounds.y == 150 && (diagram.basicElements[0] as GridPanel).children[1].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[1].bounds.height == 50)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[2].bounds.x == 150 && (diagram.basicElements[0] as GridPanel).children[2].bounds.y == 200 && (diagram.basicElements[0] as GridPanel).children[2].bounds.width == 100 && (diagram.basicElements[0] as GridPanel).children[2].bounds.height == 50)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[3].bounds.x == 250 && (diagram.basicElements[0] as GridPanel).children[3].bounds.y == 200 && (diagram.basicElements[0] as GridPanel).children[3].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[3].bounds.height == 50)).toBe(true); done(); }); }); describe('Grid Panel with row span', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram20' }); document.body.appendChild(ele); let grid: GridPanel = new GridPanel(); grid.offsetX = 300; grid.offsetY = 200; // grid.width = 100; // grid.height = 100; // grid.style.fill = 'wheat'; grid.cellStyle.fill = 'none'; grid.cellStyle.strokeColor = 'none'; let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 200; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 200; colDefns.push(colDefn2); grid.setDefinitions(rowDefns, colDefns); let child1: DiagramElement = new DiagramElement(); // child1.margin = new Margin(0, 0, 0, 0); grid.addObject(child1, 0, 0, 2); let child2: DiagramElement = new DiagramElement(); grid.addObject(child2, 1, 1); let child3: DiagramElement = new DiagramElement(); grid.addObject(child3, 1, 1); diagram = new Diagram({ width: 1000, height: 1000, basicElements: [grid] }); diagram.appendTo('#diagram20'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking grid panel without rows and columns', (done: Function) => { expect(diagram.basicElements[0].actualSize.width == 400 && diagram.basicElements[0].actualSize.height == 100).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children.length == 3)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[0].bounds.x == 100 && (diagram.basicElements[0] as GridPanel).children[0].bounds.y == 150 && (diagram.basicElements[0] as GridPanel).children[0].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[0].bounds.height == 100 && ((diagram.basicElements[0] as GridPanel).children[0] as Canvas).children.length == 1)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[1].bounds.x == 300 && (diagram.basicElements[0] as GridPanel).children[1].bounds.y == 150 && (diagram.basicElements[0] as GridPanel).children[1].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[1].bounds.height == 50)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[2].bounds.x == 300 && (diagram.basicElements[0] as GridPanel).children[2].bounds.y == 200 && (diagram.basicElements[0] as GridPanel).children[2].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[2].bounds.height == 50 && ((diagram.basicElements[0] as GridPanel).children[2] as Canvas).children.length == 2)).toBe(true); done(); }); }); describe('Grid Panel with column span', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram21' }); document.body.appendChild(ele); let grid: GridPanel = new GridPanel(); grid.offsetX = 300; grid.offsetY = 200; // grid.width = 100; // grid.height = 100; // grid.style.fill = 'wheat'; grid.cellStyle.fill = 'none'; grid.cellStyle.strokeColor = 'none'; let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 200; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 200; colDefns.push(colDefn2); grid.setDefinitions(rowDefns, colDefns); let child1: DiagramElement = new DiagramElement(); //child1.margin = new Margin(0, 0, 0, 0); grid.addObject(child1, 0, 0, 1, 2); let child2: DiagramElement = new DiagramElement(); grid.addObject(child2, 1, 0); let child3: DiagramElement = new DiagramElement(); grid.addObject(child3, 1, 0); diagram = new Diagram({ width: 1000, height: 1000, basicElements: [grid] }); diagram.appendTo('#diagram21'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking grid panel without rows and columns', (done: Function) => { expect(diagram.basicElements[0].actualSize.width == 400 && diagram.basicElements[0].actualSize.height == 100).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children.length == 3)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[0].bounds.x == 100 && (diagram.basicElements[0] as GridPanel).children[0].bounds.y == 150 && (diagram.basicElements[0] as GridPanel).children[0].bounds.width == 400 && (diagram.basicElements[0] as GridPanel).children[0].bounds.height == 50 && ((diagram.basicElements[0] as GridPanel).children[0] as Canvas).children.length == 1)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[1].bounds.x == 100 && (diagram.basicElements[0] as GridPanel).children[1].bounds.y == 200 && (diagram.basicElements[0] as GridPanel).children[1].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[1].bounds.height == 50 && ((diagram.basicElements[0] as GridPanel).children[1] as Canvas).children.length == 2)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[2].bounds.x == 300 && (diagram.basicElements[0] as GridPanel).children[2].bounds.y == 200 && (diagram.basicElements[0] as GridPanel).children[2].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[2].bounds.height == 50)).toBe(true); done(); }); }); describe('Grid Panel with Row span and column span', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramGridPanel' }); document.body.appendChild(ele); let grid: GridPanel = new GridPanel(); grid.offsetX = 300; grid.offsetY = 200; // grid.width = 100; // grid.height = 100; // grid.style.fill = 'wheat'; grid.cellStyle.fill = 'none'; grid.cellStyle.strokeColor = 'none'; let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let rowDefn3: RowDefinition = new RowDefinition(); rowDefn3.height = 50; rowDefns.push(rowDefn3); let rowDefn4: RowDefinition = new RowDefinition(); rowDefn4.height = 50; rowDefns.push(rowDefn4); let rowDefn5: RowDefinition = new RowDefinition(); rowDefn5.height = 50; rowDefns.push(rowDefn5); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 200; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 200; colDefns.push(colDefn2); let colDefn3: ColumnDefinition = new ColumnDefinition(); colDefn3.width = 200; colDefns.push(colDefn3); let colDefn4: ColumnDefinition = new ColumnDefinition(); colDefn4.width = 200; colDefns.push(colDefn4); grid.setDefinitions(rowDefns, colDefns); let child00: DiagramElement = new DiagramElement(); child00.id = 'child00'; grid.addObject(child00, 0, 0, 1, 3); let child03: DiagramElement = new DiagramElement(); child03.id = 'child03'; grid.addObject(child03, 0, 3); let child10: DiagramElement = new DiagramElement(); child10.id = 'child10'; grid.addObject(child10, 1, 0); let child11: DiagramElement = new DiagramElement(); child11.id = 'child11'; grid.addObject(child11, 1, 1); let child12: DiagramElement = new DiagramElement(); child12.id = 'child12'; grid.addObject(child12, 1, 2); let child13: DiagramElement = new DiagramElement(); child13.id = 'child13'; grid.addObject(child13, 1, 3); let child20: DiagramElement = new DiagramElement(); child20.id = 'child20'; grid.addObject(child20, 2, 0, 2, 1); let child21: DiagramElement = new DiagramElement(); child21.id = 'child21'; grid.addObject(child21, 2, 1); let child22: DiagramElement = new DiagramElement(); child22.id = 'child22'; grid.addObject(child22, 2, 2); let child23: DiagramElement = new DiagramElement(); child23.id = 'child23'; grid.addObject(child23, 2, 3); let child31: DiagramElement = new DiagramElement(); child31.id = 'child31'; grid.addObject(child31, 3, 1); let child32: DiagramElement = new DiagramElement(); child32.id = 'child32'; grid.addObject(child32, 3, 2); let child33: DiagramElement = new DiagramElement(); child33.id = 'child33'; grid.addObject(child33, 3, 3); let child40: DiagramElement = new DiagramElement(); child40.id = 'child40'; grid.addObject(child40, 4, 0); let child41: DiagramElement = new DiagramElement(); child41.id = 'child41'; grid.addObject(child41, 4, 1); let child42: DiagramElement = new DiagramElement(); child42.id = 'child42'; grid.addObject(child42, 4, 2); let child43: DiagramElement = new DiagramElement(); child43.id = 'child43'; grid.addObject(child43, 4, 3); diagram = new Diagram({ width: 1000, height: 1000, basicElements: [grid] }); diagram.appendTo('#diagramGridPanel'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking grid panel without rows and columns', (done: Function) => { expect(diagram.basicElements[0].actualSize.width == 800 && diagram.basicElements[0].actualSize.height == 250).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children.length == 17)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[0].bounds.x == -100 && (diagram.basicElements[0] as GridPanel).children[0].bounds.y == 75 && (diagram.basicElements[0] as GridPanel).children[0].bounds.width == 600 && (diagram.basicElements[0] as GridPanel).children[0].bounds.height == 50 && ((diagram.basicElements[0] as GridPanel).children[0] as Canvas).children.length == 1)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[6].bounds.x == -100 && (diagram.basicElements[0] as GridPanel).children[6].bounds.y == 175 && (diagram.basicElements[0] as GridPanel).children[6].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[6].bounds.height == 100 && ((diagram.basicElements[0] as GridPanel).children[6] as Canvas).children.length == 1)).toBe(true); done(); }); }); describe('Swimlane structure', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram22' }); document.body.appendChild(ele); let grid: GridPanel = new GridPanel(); grid.offsetX = 300; grid.offsetY = 200; // grid.width = 300; // grid.height = 250; grid.style.fill = 'red'; grid.cellStyle.fill = "none"; grid.cellStyle.strokeColor = "none"; let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 25; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 100; rowDefns.push(rowDefn2); let rowDefn3: RowDefinition = new RowDefinition(); rowDefn3.height = 100; rowDefns.push(rowDefn3); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 25; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 200; colDefns.push(colDefn2); grid.setDefinitions(rowDefns, colDefns); let swimlaneHeader: DiagramElement = new DiagramElement(); grid.addObject(swimlaneHeader, 0, 0, 1, 2); let laneheader1: DiagramElement = new DiagramElement(); // laneheader1.width = 100; // laneheader1.height = 25; // laneheader1.rotateAngle = 270; grid.addObject(laneheader1, 1, 0); let lane1: DiagramElement = new DiagramElement(); //lane1.width = 275; //lane1.height = 100; grid.addObject(lane1, 1, 1); let laneheader2: DiagramElement = new DiagramElement(); laneheader2.width = 100; laneheader2.height = 25; laneheader2.rotateAngle = 270; grid.addObject(laneheader2, 2, 0); let lane2: DiagramElement = new DiagramElement(); //lane1.width = 275; //lane1.height = 100; grid.addObject(lane2, 2, 1); let node: DiagramElement = new DiagramElement(); node.width = 100; node.height = 100; node.margin.left = 300; node.margin.top = 150; grid.addObject(node, 1, 1); diagram = new Diagram({ width: 1000, height: 1000, basicElements: [grid] }); diagram.appendTo('#diagram22'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking grid panel without rows and columns', (done: Function) => { expect(diagram.basicElements[0].actualSize.width == 425 && diagram.basicElements[0].actualSize.height == 375).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children.length == 5)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[0].bounds.x == 87.5 && (diagram.basicElements[0] as GridPanel).children[0].bounds.y == 12.5 && (diagram.basicElements[0] as GridPanel).children[0].bounds.width == 425 && (diagram.basicElements[0] as GridPanel).children[0].bounds.height == 25 && ((diagram.basicElements[0] as GridPanel).children[0] as Canvas).children.length == 1)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[1].bounds.x == 87.5 && (diagram.basicElements[0] as GridPanel).children[1].bounds.y == 37.5 && (diagram.basicElements[0] as GridPanel).children[1].bounds.width == 25 && (diagram.basicElements[0] as GridPanel).children[1].bounds.height == 250 && ((diagram.basicElements[0] as GridPanel).children[1] as Canvas).children.length == 1)).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[2].bounds.x == 112.5 && (diagram.basicElements[0] as GridPanel).children[2].bounds.y == 37.5 && (diagram.basicElements[0] as GridPanel).children[2].bounds.width == 400 && (diagram.basicElements[0] as GridPanel).children[2].bounds.height == 250 && ((diagram.basicElements[0] as GridPanel).children[2] as Canvas).children.length == 2)).toBe(true); expect((diagram.basicElements[0] as GridPanel).children[3].bounds.x == 87.5 && (diagram.basicElements[0] as GridPanel).children[3].bounds.y == 287.5 && (diagram.basicElements[0] as GridPanel).children[3].bounds.width == 25 && (diagram.basicElements[0] as GridPanel).children[3].bounds.height == 100 && ((diagram.basicElements[0] as GridPanel).children[3] as Canvas).children.length == 1).toBe(true); expect(((diagram.basicElements[0] as GridPanel).children[4].bounds.x == 112.5 && (diagram.basicElements[0] as GridPanel).children[4].bounds.y == 287.5 && (diagram.basicElements[0] as GridPanel).children[4].bounds.width == 400 && (diagram.basicElements[0] as GridPanel).children[4].bounds.height == 100 && ((diagram.basicElements[0] as GridPanel).children[4] as Canvas).children.length == 1)).toBe(true); done(); }); }); describe('Grid panel size changing', () => { let diagram: Diagram; let ele: HTMLElement; let grid: GridPanel = new GridPanel(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramGrid4' }); document.body.appendChild(ele); grid.offsetX = 300; grid.offsetY = 200; grid.width = 900; grid.height = 300; // grid.style.fill = 'wheat'; grid.cellStyle.fill = 'none'; grid.cellStyle.strokeColor = 'none'; let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let rowDefn3: RowDefinition = new RowDefinition(); rowDefn3.height = 50; rowDefns.push(rowDefn3); let rowDefn4: RowDefinition = new RowDefinition(); rowDefn4.height = 50; rowDefns.push(rowDefn4); let rowDefn5: RowDefinition = new RowDefinition(); rowDefn5.height = 50; rowDefns.push(rowDefn5); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 200; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 200; colDefns.push(colDefn2); let colDefn3: ColumnDefinition = new ColumnDefinition(); colDefn3.width = 200; colDefns.push(colDefn3); let colDefn4: ColumnDefinition = new ColumnDefinition(); colDefn4.width = 200; colDefns.push(colDefn4); grid.setDefinitions(rowDefns, colDefns); let child00: DiagramElement = new DiagramElement(); child00.id = 'child00'; grid.addObject(child00, 0, 0, 1, 3); let child03: DiagramElement = new DiagramElement(); child03.id = 'child03'; grid.addObject(child03, 0, 3); let child10: DiagramElement = new DiagramElement(); child10.id = 'child10'; grid.addObject(child10, 1, 0); let child11: DiagramElement = new DiagramElement(); child11.id = 'child11'; grid.addObject(child11, 1, 1); let child12: DiagramElement = new DiagramElement(); child12.id = 'child12'; grid.addObject(child12, 1, 2); let child13: DiagramElement = new DiagramElement(); child13.id = 'child13'; grid.addObject(child13, 1, 3); let child20: DiagramElement = new DiagramElement(); child20.id = 'child20'; grid.addObject(child20, 2, 0, 2, 1); let child21: DiagramElement = new DiagramElement(); child21.id = 'child21'; grid.addObject(child21, 2, 1); let child22: DiagramElement = new DiagramElement(); child22.id = 'child22'; grid.addObject(child22, 2, 2); let child23: DiagramElement = new DiagramElement(); child23.id = 'child23'; grid.addObject(child23, 2, 3); let child31: DiagramElement = new DiagramElement(); child31.id = 'child31'; grid.addObject(child31, 3, 1); let child32: DiagramElement = new DiagramElement(); child32.id = 'child32'; grid.addObject(child32, 3, 2); let child33: DiagramElement = new DiagramElement(); child33.id = 'child33'; grid.addObject(child33, 3, 3); let child40: DiagramElement = new DiagramElement(); child40.id = 'child40'; grid.addObject(child40, 4, 0); let child41: DiagramElement = new DiagramElement(); child41.id = 'child41'; grid.addObject(child41, 4, 1); let child42: DiagramElement = new DiagramElement(); child42.id = 'child42'; grid.addObject(child42, 4, 2); let child43: DiagramElement = new DiagramElement(); child43.id = 'child43'; grid.addObject(child43, 4, 3); let node1: DiagramElement = new DiagramElement(); node1.width = 100; node1.height = 100; node1.margin.left = 30; node1.margin.top = 15; node1.style.fill = 'red'; grid.addObject(node1, 1, 1); let node2: DiagramElement = new DiagramElement(); node2.width = 100; node2.height = 100; node2.margin.left = 30; node2.margin.top = 15; node2.style.fill = 'blue'; grid.addObject(node2, 2, 1); diagram = new Diagram({ width: 1000, height: 1000, basicElements: [grid] }); diagram.appendTo('#diagramGrid4'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking grid panel row height when change the row height at run time', (done: Function) => { expect(((diagram.basicElements[0] as GridPanel).children[3].bounds.x == 50 && (diagram.basicElements[0] as GridPanel).children[3].bounds.y == 35 && (diagram.basicElements[0] as GridPanel).children[3].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[3].bounds.height == 115 && ((diagram.basicElements[0] as GridPanel).children[3] as Canvas).children.length == 2)).toBe(true); grid.updateRowHeight(1, 240, true); diagram.updateGridContainer(grid); expect(((diagram.basicElements[0] as GridPanel).children[3].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[3].bounds.height == 240 && ((diagram.basicElements[0] as GridPanel).children[3] as Canvas).children.length == 2)).toBe(true); done(); }); it('Checking grid panel column width when change the column width at run time', (done: Function) => { expect(((diagram.basicElements[0] as GridPanel).children[3].bounds.width == 200 && (diagram.basicElements[0] as GridPanel).children[3].bounds.height == 240 && ((diagram.basicElements[0] as GridPanel).children[3] as Canvas).children.length == 2)).toBe(true); grid.updateColumnWidth(1, 240, true); diagram.updateGridContainer(grid); expect(((diagram.basicElements[0] as GridPanel).children[3].bounds.width == 240 && (diagram.basicElements[0] as GridPanel).children[3].bounds.height == 240 && ((diagram.basicElements[0] as GridPanel).children[3] as Canvas).children.length == 2)).toBe(true); done(); }); }); describe('Grid panel - Add Row at runtime', () => { let diagram: Diagram; let ele: HTMLElement; let grid: GridPanel = new GridPanel(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramGrid10' }); document.body.appendChild(ele); grid.offsetX = 300; grid.offsetY = 200; grid.cellStyle.fill = 'none'; grid.cellStyle.strokeColor = 'none'; let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 100; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 100; colDefns.push(colDefn2); grid.setDefinitions(rowDefns, colDefns); let child00: DiagramElement = new DiagramElement(); child00.id = 'child00'; grid.addObject(child00, 0, 0); let child01: DiagramElement = new DiagramElement(); child01.id = 'child01'; grid.addObject(child01, 0, 1); let child10: DiagramElement = new DiagramElement(); child10.id = 'child10'; grid.addObject(child10, 1, 0); let child11: DiagramElement = new DiagramElement(); child11.id = 'child11'; grid.addObject(child11, 1, 1); diagram = new Diagram({ width: 500, height: 500, basicElements: [grid] }); diagram.appendTo('#diagramGrid10'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking insert row in first', (done: Function) => { expect((diagram.basicElements[0] as GridPanel).children.length == 4).toBe(true); var rowDefns = []; var rowDefn1 = new RowDefinition(); rowDefn1.height = 100; rowDefns.push(rowDefn1); grid.addRow(0, rowDefn1, true); var child10 = new DiagramElement(); child10.id = 'child20'; grid.addObject(child10, 0, 0); var child11 = new DiagramElement(); child11.id = 'child21'; grid.addObject(child11, 0, 1); expect((diagram.basicElements[0] as GridPanel).children.length == 6).toBe(true); done(); }); it('Checking insert row in middle', (done: Function) => { expect((diagram.basicElements[0] as GridPanel).children.length == 6).toBe(true); var rowDefns = []; var rowDefn1 = new RowDefinition(); rowDefn1.height = 70; rowDefns.push(rowDefn1); grid.addRow(1, rowDefn1, true); var child10 = new DiagramElement(); child10.id = 'child220'; grid.addObject(child10, 1, 0); var child11 = new DiagramElement(); child11.id = 'child221'; grid.addObject(child11, 1, 1); expect((diagram.basicElements[0] as GridPanel).children.length == 8).toBe(true); done(); }); it('Checking insert row in last', (done: Function) => { expect((diagram.basicElements[0] as GridPanel).children.length == 8).toBe(true); var rowDefns = []; var rowDefn1 = new RowDefinition(); rowDefn1.height = 100; rowDefns.push(rowDefn1); grid.addRow(4, rowDefn1, true); var child10 = new DiagramElement(); child10.id = 'child40'; grid.addObject(child10, 4, 0); var child11 = new DiagramElement(); child11.id = 'child41'; grid.addObject(child11, 4, 1); expect((diagram.basicElements[0] as GridPanel).children.length == 10).toBe(true); done(); }); }); describe('Grid panel - Add Column at runtime', () => { let diagram: Diagram; let ele: HTMLElement; let grid: GridPanel = new GridPanel(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramGrid11' }); document.body.appendChild(ele); grid.offsetX = 300; grid.offsetY = 200; grid.cellStyle.fill = 'none'; grid.cellStyle.strokeColor = 'none'; let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 100; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 100; colDefns.push(colDefn2); grid.setDefinitions(rowDefns, colDefns); let child00: DiagramElement = new DiagramElement(); child00.id = 'child00'; grid.addObject(child00, 0, 0); let child01: DiagramElement = new DiagramElement(); child01.id = 'child01'; grid.addObject(child01, 0, 1); let child10: DiagramElement = new DiagramElement(); child10.id = 'child10'; grid.addObject(child10, 1, 0); let child11: DiagramElement = new DiagramElement(); child11.id = 'child11'; grid.addObject(child11, 1, 1); diagram = new Diagram({ width: 500, height: 500, basicElements: [grid] }); diagram.appendTo('#diagramGrid11'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking insert column in first', (done: Function) => { expect((diagram.basicElements[0] as GridPanel).children.length == 4).toBe(true); var colDefns = []; var colDefn = new ColumnDefinition(); colDefn.width = 100; colDefns.push(colDefn); grid.addColumn(0, colDefn, true); var child10 = new DiagramElement(); child10.id = 'newchild20'; grid.addObject(child10, 0, 0); var child11 = new DiagramElement(); child11.id = 'newchild21'; grid.addObject(child11, 1, 0); expect((diagram.basicElements[0] as GridPanel).children.length == 6).toBe(true); done(); }); it('Checking insert column in middle', (done: Function) => { expect((diagram.basicElements[0] as GridPanel).children.length == 6).toBe(true); var colDefns = []; var colDefn = new ColumnDefinition(); colDefn.width = 100; colDefns.push(colDefn); grid.addColumn(1, colDefn, true); var child10 = new DiagramElement(); child10.id = 'newchild120'; grid.addObject(child10, 0, 1); var child11 = new DiagramElement(); child11.id = 'newchild121'; grid.addObject(child11, 1, 1); expect((diagram.basicElements[0] as GridPanel).children.length == 8).toBe(true); done(); }); it('Checking insert column in last', (done: Function) => { expect((diagram.basicElements[0] as GridPanel).children.length == 8).toBe(true); var colDefns = []; var colDefn = new ColumnDefinition(); colDefn.width = 100; colDefns.push(colDefn); grid.addColumn(4, colDefn, true); var child10 = new DiagramElement(); child10.id = 'newchild220'; grid.addObject(child10, 4, 0); var child11 = new DiagramElement(); child11.id = 'newchild221'; grid.addObject(child11, 4, 0); expect((diagram.basicElements[0] as GridPanel).children.length == 10).toBe(true); done(); }); }); describe('Grid panel - Remove Row and Column at runtime', () => { let diagram: Diagram; let ele: HTMLElement; let grid: GridPanel = new GridPanel(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramGrid12' }); document.body.appendChild(ele); grid.offsetX = 300; grid.offsetY = 200; grid.cellStyle.fill = 'none'; grid.cellStyle.strokeColor = 'none'; let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 100; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 100; colDefns.push(colDefn2); grid.setDefinitions(rowDefns, colDefns); let child00: DiagramElement = new DiagramElement(); child00.id = 'child00'; grid.addObject(child00, 0, 0); let child01: DiagramElement = new DiagramElement(); child01.id = 'child01'; grid.addObject(child01, 0, 1); let child10: DiagramElement = new DiagramElement(); child10.id = 'child10'; grid.addObject(child10, 1, 0); let child11: DiagramElement = new DiagramElement(); child11.id = 'child11'; grid.addObject(child11, 1, 1); diagram = new Diagram({ width: 500, height: 500, basicElements: [grid] }); diagram.appendTo('#diagramGrid12'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking remove column in first', (done: Function) => { expect((diagram.basicElements[0] as GridPanel).children.length == 4).toBe(true); grid.removeColumn(1); diagram.updateGridContainer(grid); expect((diagram.basicElements[0] as GridPanel).children.length == 2).toBe(true); done(); }); it('Checking remove row', (done: Function) => { expect((diagram.basicElements[0] as GridPanel).children.length == 2).toBe(true); grid.removeRow(1); diagram.updateGridContainer(grid); expect((diagram.basicElements[0] as GridPanel).children.length == 1).toBe(true); done(); }); }); describe('Grid panel - Swap the rows in grid', () => { let diagram: Diagram; let ele: HTMLElement; let grid: GridPanel = new GridPanel(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramGrid13' }); document.body.appendChild(ele); grid.offsetX = 300; grid.offsetY = 200; grid.cellStyle.fill = 'none'; grid.cellStyle.strokeColor = 'none'; let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 50; rowDefns.push(rowDefn2); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 100; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 100; colDefns.push(colDefn2); grid.setDefinitions(rowDefns, colDefns); let child00: DiagramElement = new DiagramElement(); child00.id = 'child00'; grid.addObject(child00, 0, 0); let child01: DiagramElement = new DiagramElement(); child01.id = 'child01'; grid.addObject(child01, 0, 1); let child10: DiagramElement = new DiagramElement(); child10.id = 'child10'; grid.addObject(child10, 1, 0); let child11: DiagramElement = new DiagramElement(); child11.id = 'child11'; grid.addObject(child11, 1, 1); diagram = new Diagram({ width: 500, height: 500, basicElements: [grid] }); diagram.appendTo('#diagramGrid13'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking inter change the row in the grid', (done: Function) => { expect((diagram.basicElements[0] as GridPanel).children[0].bounds.x == 200 && (diagram.basicElements[0] as GridPanel).children[0].bounds.y == 150 && (diagram.basicElements[0] as GridPanel).children[0].bounds.width == 100 && (diagram.basicElements[0] as GridPanel).children[0].bounds.height == 50).toBe(true); grid.updateRowIndex(1, 0); diagram.updateGridContainer(grid); expect((diagram.basicElements[0] as GridPanel).children[0].bounds.x == 200 && (diagram.basicElements[0] as GridPanel).children[0].bounds.y == 200 && (diagram.basicElements[0] as GridPanel).children[0].bounds.width == 100 && (diagram.basicElements[0] as GridPanel).children[0].bounds.height == 50).toBe(true); done(); }); it('Checking the properties after change', (done: Function) => { grid.updateProperties(400, 300, 400, 400); diagram.updateGridContainer(grid); expect((diagram.basicElements[0] as GridPanel).offsetX == 400 && (diagram.basicElements[0] as GridPanel).offsetY == 300 && (diagram.basicElements[0] as GridPanel).width == 400 && (diagram.basicElements[0] as GridPanel).height == 400).toBe(true); done(); }); }); describe('Simple Grid container', () => { let diagram: Diagram; let ele: HTMLElement; let diagramCanvas: HTMLElement; let mouseevents = new MouseEvents(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramGridContainer' }); document.body.appendChild(ele); let rowDefns: RowDefinition[] = []; let rowDefn1: RowDefinition = new RowDefinition(); rowDefn1.height = 50; rowDefns.push(rowDefn1); let rowDefn2: RowDefinition = new RowDefinition(); rowDefn2.height = 100; rowDefns.push(rowDefn2); let rowDefn3: RowDefinition = new RowDefinition(); rowDefn3.height = 50; rowDefns.push(rowDefn3); let colDefns: ColumnDefinition[] = []; let colDefn: ColumnDefinition = new ColumnDefinition(); colDefn.width = 20; colDefns.push(colDefn); let colDefn2: ColumnDefinition = new ColumnDefinition(); colDefn2.width = 100; colDefns.push(colDefn2); let colDefn3: ColumnDefinition = new ColumnDefinition(); colDefn3.width = 100; colDefns.push(colDefn3); let nodes: NodeModel[] = [ { id: 'node01', offsetX: 100, offsetY: 100, rowIndex: 0, columnIndex: 0, columnSpan: 3, annotations: [{ content: 'H' }], container: { type: 'Canvas', orientation: 'Vertical' } }, { id: 'n1', offsetX: 100, offsetY: 100, annotations: [{ content: 'n1' }], margin: { left: 10, top: 10 }, width: 40, height: 30 }, { id: 'n2', offsetX: 100, offsetY: 100, annotations: [{ content: 'n2' }], margin: { left: 10, top: 10 }, width: 40, height: 30 }, { id: 'node02', offsetX: 100, offsetY: 100, rowIndex: 1, columnIndex: 0, columnSpan: 1, annotations: [{ content: 'p' }], container: { type: 'Canvas', orientation: 'Vertical' } }, { id: 'node03', offsetX: 100, offsetY: 100, rowIndex: 1, columnIndex: 1, columnSpan: 1, annotations: [{ content: 'L' }], container: { type: 'Canvas', orientation: 'Vertical' }, }, { id: 'node04', offsetX: 100, offsetY: 100, rowIndex: 1, columnIndex: 2, rowSpan: 1, annotations: [{ content: 'L' }], container: { type: 'Canvas', orientation: 'Vertical' }, children: ['n2'], constraints: NodeConstraints.Default | NodeConstraints.AllowDrop }, { id: 'node05', offsetX: 100, offsetY: 100, rowIndex: 2, columnIndex: 0, annotations: [{ content: 'p' }], container: { type: 'Canvas', orientation: 'Vertical' } }, { id: 'node06', offsetX: 100, offsetY: 100, rowIndex: 2, columnIndex: 1, annotations: [{ content: 'L' }], container: { type: 'Canvas', orientation: 'Vertical' }, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop }, { id: 'node07', offsetX: 100, offsetY: 100, rowIndex: 2, columnIndex: 2, annotations: [{ content: 'L' }], container: { type: 'Canvas', orientation: 'Vertical' }, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop, children: ['n1'] }, { id: 'grid', offsetX: 400, offsetY: 300, rows: rowDefns, columns: colDefns, children: ['node01', 'node02', 'node03', 'node04', 'node05', 'node06', 'node07'], container: { type: 'Grid', orientation: 'Vertical' } }, ]; diagram = new Diagram({ width: 1000, height: 1000, nodes: nodes }); diagram.appendTo('#diagramGridContainer'); diagramCanvas = document.getElementById(diagram.element.id + 'content'); mouseevents.clickEvent(diagramCanvas, 10, 10); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking grid container', (done: Function) => { expect(diagram.nodes[9].offsetX == 400 && diagram.nodes[9].offsetY == 300).toBe(true); done(); }); it('Checking grid container resize the column width', (done: Function) => { mouseevents.clickEvent(diagramCanvas, 10, 10); var node1 = diagram.nodes[4]; mouseevents.clickEvent(diagramCanvas, node1.offsetX + diagram.element.offsetLeft, node1.offsetY + diagram.element.offsetTop); resize(diagram, 'resizeEast'); expect(diagram.nodes[9].offsetX == 407.5 && diagram.nodes[9].offsetY == 300 && diagram.nodes[9].wrapper.actualSize.width == 265 && diagram.nodes[9].wrapper.actualSize.height == 200).toBe(true); done(); }); it('Checking grid container resize the row height', (done: Function) => { mouseevents.clickEvent(diagramCanvas, 10, 10); var node1 = diagram.nodes[6]; mouseevents.clickEvent(diagramCanvas, node1.offsetX + diagram.element.offsetLeft, node1.offsetY + diagram.element.offsetTop); resize(diagram, 'resizeSouth'); expect(diagram.nodes[9].offsetX == 407.5 && diagram.nodes[9].offsetY == 310 && diagram.nodes[9].wrapper.actualSize.width == 265 && diagram.nodes[9].wrapper.actualSize.height == 220).toBe(true); done(); }); it('Checking Select the node', (done: Function) => { let node: NodeModel = diagram.nodes[1]; mouseevents.clickEvent(diagramCanvas, node.offsetX + diagram.element.offsetLeft, node.offsetY + diagram.element.offsetTop); resize(diagram, 'resizeEast'); expect(diagram.nodes[9].offsetX == 397.5 && diagram.nodes[9].offsetY == 310 && diagram.nodes[9].wrapper.actualSize.width == 245 && diagram.nodes[9].wrapper.actualSize.height == 220).toBe(true); resize(diagram, 'resizeSouth'); resize(diagram, 'resizeSouth'); expect(diagram.nodes[9].offsetX == 397.5 && diagram.nodes[9].offsetY == 315 && diagram.nodes[9].wrapper.actualSize.width == 245 && diagram.nodes[9].wrapper.actualSize.height == 230).toBe(true); done(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) }); describe('Diagram grid dot test cases', () => { let diagram: Diagram; let ele: HTMLElement; let diagramCanvas: HTMLElement; let mouseevents = new MouseEvents(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramGriddots' }); document.body.appendChild(ele); diagram = new Diagram({ width: '800px', height: '500px', snapSettings: { gridType: 'Dots', }, }); diagram.appendTo('#diagramGriddots'); diagramCanvas = document.getElementById(diagram.element.id + 'content'); mouseevents.clickEvent(diagramCanvas, 10, 10); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Diagram grid dot test cases - intial rendering', (done: Function) => { var diagramgriddot = document.getElementById("diagramGriddots_pattern") expect(diagramgriddot.children.length === 72).toBe(true); expect(diagramgriddot.children[0] instanceof SVGCircleElement && diagramgriddot.children[0].getAttribute('fill') === 'lightgray' && diagramgriddot.children[0].getAttribute("cx") === "0" && diagramgriddot.children[0].getAttribute("cy") === "0" && diagramgriddot.children[5].getAttribute("cy") === "0" && diagramgriddot.children[20].getAttribute("cx") === "40" && diagramgriddot.children[20].getAttribute("cy") === "60" && diagramgriddot.children[71].getAttribute("cx") === "100" && diagramgriddot.children[71].getAttribute("cy") === "100").toBe(true); diagram.snapSettings.horizontalGridlines.dotIntervals = [1, 30, 0.5, 30, 0.5, 30, 0.5, 30, 0.5, 30]; diagram.snapSettings.verticalGridlines.dotIntervals = [1, 30, 0.5, 30, 0.5, 30, 0.5, 30, 0.5, 30]; diagram.snapSettings.horizontalGridlines.lineColor = 'black'; diagram.dataBind() var diagramgriddot1 = document.getElementById("diagramGriddots_pattern") expect(diagramgriddot1.children[0].getAttribute('fill') === 'black' && diagramgriddot1.children[0].getAttribute("cx") === "0" && diagramgriddot1.children[0].getAttribute("cy") === "0" && diagramgriddot1.children[5].getAttribute("cy") === "0" && diagramgriddot1.children[20].getAttribute("cx") === "61.5" && diagramgriddot1.children[20].getAttribute("cy") === "92" && diagramgriddot1.children[71].getAttribute("cx") === "153" && diagramgriddot1.children[71].getAttribute("cy") === "153").toBe(true); diagram.snapSettings.horizontalGridlines.dotIntervals = [3, 20, 1, 20, 1, 20, 1, 20, 1, 20]; diagram.snapSettings.verticalGridlines.dotIntervals = [3, 20, 1, 20, 1, 20]; diagram.dataBind() var diagramgriddot1 = document.getElementById("diagramGriddots_pattern"); expect(diagramgriddot1.children[0].getAttribute('fill') === 'black' && diagramgriddot1.children[0].getAttribute("cx") === "0" && diagramgriddot1.children[0].getAttribute("cy") === "0" && diagramgriddot1.children[5].getAttribute("cy") === "23" && diagramgriddot1.children[20].getAttribute("cx") === "0" && diagramgriddot1.children[20].getAttribute("cy") === "107" && diagramgriddot1.children[47].getAttribute("cx") === "65" && diagramgriddot1.children[47].getAttribute("cy") === "107").toBe(true); diagram.snapSettings.gridType = 'Lines'; diagram.snapSettings.horizontalGridlines.lineColor = 'lightgray'; diagram.dataBind() var diagramgriddot2 = document.getElementById("diagramGriddots_pattern") expect(diagramgriddot2.children.length === 10 && diagramgriddot2.children[0] instanceof SVGPathElement && diagramgriddot2.children[0].getAttribute("d") === "M0,0.625 L100,0.625 Z" && diagramgriddot2.children[9].getAttribute("d") === "M80.125,0 L80.125,100 Z").toBe(true); diagram.snapSettings.gridType = 'Dots'; diagram.dataBind(); expect(diagramgriddot1.children[0].getAttribute('fill') === 'black' && diagramgriddot1.children[0].getAttribute("cx") === "0" && diagramgriddot1.children[0].getAttribute("cy") === "0" && diagramgriddot1.children[5].getAttribute("cy") === "23" && diagramgriddot1.children[20].getAttribute("cx") === "0" && diagramgriddot1.children[20].getAttribute("cy") === "107" && diagramgriddot1.children[47].getAttribute("cx") === "65" && diagramgriddot1.children[47].getAttribute("cy") === "107").toBe(true); done(); }); }); });
the_stack
import * as colorSpaces from '../util/color_spaces'; import Color from '../util/color'; import extend from '../util/extend'; import getType from '../util/get_type'; import * as interpolate from '../util/interpolate'; import Interpolate from '../expression/definitions/interpolate'; import Formatted from '../expression/types/formatted'; import ResolvedImage from '../expression/types/resolved_image'; import {supportsInterpolation} from '../util/properties'; import {findStopLessThanOrEqualTo} from '../expression/stops'; export function isFunction(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); } function identityFunction(x) { return x; } export function createFunction(parameters, propertySpec) { const isColor = propertySpec.type === 'color'; const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object'; const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; const zoomDependent = zoomAndFeatureDependent || !featureDependent; const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval'); if (isColor) { parameters = extend({}, parameters); if (parameters.stops) { parameters.stops = parameters.stops.map((stop) => { return [stop[0], Color.parse(stop[1])]; }); } if (parameters.default) { parameters.default = Color.parse(parameters.default); } else { parameters.default = Color.parse(propertySpec.default); } } if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { // eslint-disable-line import/namespace throw new Error(`Unknown color space: ${parameters.colorSpace}`); } let innerFun; let hashedStops; let categoricalKeyType; if (type === 'exponential') { innerFun = evaluateExponentialFunction; } else if (type === 'interval') { innerFun = evaluateIntervalFunction; } else if (type === 'categorical') { innerFun = evaluateCategoricalFunction; // For categorical functions, generate an Object as a hashmap of the stops for fast searching hashedStops = Object.create(null); for (const stop of parameters.stops) { hashedStops[stop[0]] = stop[1]; } // Infer key type based on first stop key-- used to encforce strict type checking later categoricalKeyType = typeof parameters.stops[0][0]; } else if (type === 'identity') { innerFun = evaluateIdentityFunction; } else { throw new Error(`Unknown function type "${type}"`); } if (zoomAndFeatureDependent) { const featureFunctions = {}; const zoomStops = []; for (let s = 0; s < parameters.stops.length; s++) { const stop = parameters.stops[s]; const zoom = stop[0].zoom; if (featureFunctions[zoom] === undefined) { featureFunctions[zoom] = { zoom, type: parameters.type, property: parameters.property, default: parameters.default, stops: [] }; zoomStops.push(zoom); } featureFunctions[zoom].stops.push([stop[0].value, stop[1]]); } const featureFunctionStops = []; for (const z of zoomStops) { featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]); } const interpolationType = {name: 'linear'}; return { kind: 'composite', interpolationType, interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), zoomStops: featureFunctionStops.map(s => s[0]), evaluate({zoom}, properties) { return evaluateExponentialFunction({ stops: featureFunctionStops, base: parameters.base }, propertySpec, zoom).evaluate(zoom, properties); } }; } else if (zoomDependent) { const interpolationType = type === 'exponential' ? {name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1} : null; return { kind: 'camera', interpolationType, interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), zoomStops: parameters.stops.map(s => s[0]), evaluate: ({zoom}) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType) }; } else { return { kind: 'source', evaluate(_, feature) { const value = feature && feature.properties ? feature.properties[parameters.property] : undefined; if (value === undefined) { return coalesce(parameters.default, propertySpec.default); } return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); } }; } } function coalesce(a, b, c?) { if (a !== undefined) return a; if (b !== undefined) return b; if (c !== undefined) return c; } function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input return coalesce(evaluated, parameters.default, propertySpec.default); } function evaluateIntervalFunction(parameters, propertySpec, input) { // Edge cases if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default); const n = parameters.stops.length; if (n === 1) return parameters.stops[0][1]; if (input <= parameters.stops[0][0]) return parameters.stops[0][1]; if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1]; const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); return parameters.stops[index][1]; } function evaluateExponentialFunction(parameters, propertySpec, input) { const base = parameters.base !== undefined ? parameters.base : 1; // Edge cases if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default); const n = parameters.stops.length; if (n === 1) return parameters.stops[0][1]; if (input <= parameters.stops[0][0]) return parameters.stops[0][1]; if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1]; const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); const t = interpolationFactor( input, base, parameters.stops[index][0], parameters.stops[index + 1][0]); const outputLower = parameters.stops[index][1]; const outputUpper = parameters.stops[index + 1][1]; let interp = interpolate[propertySpec.type] || identityFunction; // eslint-disable-line import/namespace if (parameters.colorSpace && parameters.colorSpace !== 'rgb') { const colorspace = colorSpaces[parameters.colorSpace]; // eslint-disable-line import/namespace interp = (a, b) => colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t)); } if (typeof outputLower.evaluate === 'function') { return { evaluate(...args) { const evaluatedLower = outputLower.evaluate.apply(undefined, args); const evaluatedUpper = outputUpper.evaluate.apply(undefined, args); // Special case for fill-outline-color, which has no spec default. if (evaluatedLower === undefined || evaluatedUpper === undefined) { return undefined; } return interp(evaluatedLower, evaluatedUpper, t); } }; } return interp(outputLower, outputUpper, t); } function evaluateIdentityFunction(parameters, propertySpec, input) { if (propertySpec.type === 'color') { input = Color.parse(input); } else if (propertySpec.type === 'formatted') { input = Formatted.fromString(input.toString()); } else if (propertySpec.type === 'resolvedImage') { input = ResolvedImage.fromString(input.toString()); } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) { input = undefined; } return coalesce(input, parameters.default, propertySpec.default); } /** * Returns a ratio that can be used to interpolate between exponential function * stops. * * How it works: * Two consecutive stop values define a (scaled and shifted) exponential * function `f(x) = a * base^x + b`, where `base` is the user-specified base, * and `a` and `b` are constants affording sufficient degrees of freedom to fit * the function to the given stops. * * Here's a bit of algebra that lets us compute `f(x)` directly from the stop * values without explicitly solving for `a` and `b`: * * First stop value: `f(x0) = y0 = a * base^x0 + b` * Second stop value: `f(x1) = y1 = a * base^x1 + b` * => `y1 - y0 = a(base^x1 - base^x0)` * => `a = (y1 - y0)/(base^x1 - base^x0)` * * Desired value: `f(x) = y = a * base^x + b` * => `f(x) = y0 + a * (base^x - base^x0)` * * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a * little algebra: * ``` * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) * ``` * * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as * an interpolation factor between the two stops' output values. * * (Note: a slightly different form for `ratio`, * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer * expensive `Math.pow()` operations.) * * @private */ function interpolationFactor(input, base, lowerValue, upperValue) { const difference = upperValue - lowerValue; const progress = input - lowerValue; if (difference === 0) { return 0; } else if (base === 1) { return progress / difference; } else { return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); } }
the_stack
* @module WebGL */ import { assert, BentleyStatus, Dictionary, dispose, Id64, Id64String } from "@itwin/core-bentley"; import { ClipVector, Point3d, Transform } from "@itwin/core-geometry"; import { ColorDef, ElementAlignedBox3d, Frustum, Gradient, ImageBuffer, ImageBufferFormat, ImageSourceFormat, IModelError, PackedFeatureTable, RenderMaterial, RenderTexture, } from "@itwin/core-common"; import { Capabilities, DepthType, WebGLContext } from "@itwin/webgl-compatibility"; import { SkyBox } from "../../DisplayStyleState"; import { imageElementFromImageSource } from "../../ImageUtil"; import { IModelApp } from "../../IModelApp"; import { IModelConnection } from "../../IModelConnection"; import { MapTileTreeReference, TileTreeReference } from "../../tile/internal"; import { ViewRect } from "../../ViewRect"; import { GraphicBranch, GraphicBranchOptions } from "../GraphicBranch"; import { BatchOptions, CustomGraphicBuilderOptions, GraphicBuilder, ViewportGraphicBuilderOptions } from "../GraphicBuilder"; import { InstancedGraphicParams, PatternGraphicParams } from "../InstancedGraphicParams"; import { PrimitiveBuilder } from "../primitives/geometry/GeometryListBuilder"; import { RealityMeshPrimitive } from "../primitives/mesh/RealityMeshPrimitive"; import { TerrainMeshPrimitive } from "../primitives/mesh/TerrainMeshPrimitive"; import { PointCloudArgs } from "../primitives/PointCloudPrimitive"; import { MeshParams, PointStringParams, PolylineParams } from "../primitives/VertexTable"; import { RenderClipVolume } from "../RenderClipVolume"; import { RenderGraphic, RenderGraphicOwner } from "../RenderGraphic"; import { RenderMemory } from "../RenderMemory"; import { CreateTextureArgs, CreateTextureFromSourceArgs, TextureCacheKey, TextureTransparency } from "../RenderTexture"; import { DebugShaderFile, GLTimerResultCallback, PlanarGridProps, RenderAreaPattern, RenderDiagnostics, RenderGeometry, RenderSystem, RenderSystemDebugControl, TerrainTexture, } from "../RenderSystem"; import { RenderTarget } from "../RenderTarget"; import { ScreenSpaceEffectBuilder, ScreenSpaceEffectBuilderParams } from "../ScreenSpaceEffectBuilder"; import { BackgroundMapDrape } from "./BackgroundMapDrape"; import { SkyBoxQuadsGeometry, SkySphereViewportQuadGeometry } from "./CachedGeometry"; import { ClipVolume } from "./ClipVolume"; import { isInstancedGraphicParams, PatternBuffers } from "./InstancedGeometry"; import { Debug } from "./Diagnostics"; import { WebGLDisposable } from "./Disposable"; import { DepthBuffer, FrameBufferStack } from "./FrameBuffer"; import { GL } from "./GL"; import { GLTimer } from "./GLTimer"; import { Batch, Branch, Graphic, GraphicOwner, GraphicsArray } from "./Graphic"; import { Layer, LayerContainer } from "./Layer"; import { LineCode } from "./LineCode"; import { Material } from "./Material"; import { MeshGraphic, MeshRenderGeometry } from "./Mesh"; import { PointCloudGeometry } from "./PointCloud"; import { PointStringGeometry } from "./PointString"; import { PolylineGeometry } from "./Polyline"; import { Primitive, SkyCubePrimitive, SkySpherePrimitive } from "./Primitive"; import { RenderBuffer, RenderBufferMultiSample } from "./RenderBuffer"; import { TextureUnit } from "./RenderFlags"; import { RenderState } from "./RenderState"; import { createScreenSpaceEffectBuilder, ScreenSpaceEffects } from "./ScreenSpaceEffect"; import { OffScreenTarget, OnScreenTarget } from "./Target"; import { Techniques } from "./Technique"; import { RealityMeshGeometry } from "./RealityMesh"; import { ExternalTextureLoader, Texture, TextureHandle } from "./Texture"; import { UniformHandle } from "./UniformHandle"; import { PlanarGridGeometry } from "./PlanarGrid"; /* eslint-disable no-restricted-syntax */ /** @internal */ export const enum ContextState { Uninitialized, Success, Error, } /** Describes WebGL extension methods. * @internal */ abstract class WebGLExtensions { private _system: System; public constructor(system: System) { this._system = system; } public get system() { return this._system; } public abstract setDrawBuffers(attachments: GLenum[]): void; public abstract vertexAttribDivisor(index: number, divisor: number): void; public abstract drawArraysInst(type: GL.PrimitiveType, first: number, count: number, numInstances: number): void; public abstract invalidateFrameBuffer(_attachments: number[]): void; } /** Describes WebGL1 extension methods. * @internal */ class WebGL1Extensions extends WebGLExtensions { private readonly _drawBuffersExtension?: WEBGL_draw_buffers; private readonly _instancingExtension?: ANGLE_instanced_arrays; public constructor(system: System, drawBuffersExt: WEBGL_draw_buffers | undefined, instancingExt: ANGLE_instanced_arrays | undefined) { super(system); this._drawBuffersExtension = drawBuffersExt; this._instancingExtension = instancingExt; } public setDrawBuffers(attachments: GLenum[]): void { // NB: The WEBGL_draw_buffers member is not exported directly because that type name is not available in some contexts (e.g. test-imodel-service). if (undefined !== this._drawBuffersExtension) this._drawBuffersExtension.drawBuffersWEBGL(attachments); } public vertexAttribDivisor(index: number, divisor: number): void { assert(undefined !== this._instancingExtension); this._instancingExtension.vertexAttribDivisorANGLE(index, divisor); } public drawArraysInst(type: GL.PrimitiveType, first: number, count: number, numInstances: number): void { if (undefined !== this._instancingExtension) { this._instancingExtension.drawArraysInstancedANGLE(type, first, count, numInstances); } } public invalidateFrameBuffer(_attachments: number[]): void { } // does not exist in WebGL1 } /** Describes WebGL2 extension methods. * @internal */ class WebGL2Extensions extends WebGLExtensions { private _context: WebGL2RenderingContext; public constructor(system: System) { super(system); this._context = system.context as WebGL2RenderingContext; } public setDrawBuffers(attachments: GLenum[]): void { this._context.drawBuffers(attachments); } public vertexAttribDivisor(index: number, divisor: number): void { this._context.vertexAttribDivisor(index, divisor); } public drawArraysInst(type: GL.PrimitiveType, first: number, count: number, numInstances: number): void { this._context.drawArraysInstanced(type, first, count, numInstances); } public invalidateFrameBuffer(attachments: number[]): void { this._context.invalidateFramebuffer(this._context.FRAMEBUFFER, attachments); } } /** Id map holds key value pairs for both materials and textures, useful for caching such objects. * @internal */ export class IdMap implements WebGLDisposable { private readonly _iModel: IModelConnection; /** Mapping of materials by their key values. */ public readonly materials = new Map<string, RenderMaterial>(); /** Mapping of textures by their key values. */ public readonly textures = new Map<string, RenderTexture>(); /** Mapping of textures using gradient symbology. */ public readonly gradients = new Dictionary<Gradient.Symb, RenderTexture>(Gradient.Symb.compareSymb); /** Pending promises to create a texture from an ImageSource. This prevents us from decoding the same ImageSource multiple times */ public readonly texturesFromImageSources = new Map<string, Promise<RenderTexture | undefined>>(); public constructor(iModel: IModelConnection) { this._iModel = iModel; } public get isDisposed(): boolean { return 0 === this.textures.size && 0 === this.gradients.size; } public dispose() { const textureArr = Array.from(this.textures.values()); const gradientArr = this.gradients.extractArrays().values; for (const texture of textureArr) dispose(texture); for (const gradient of gradientArr) dispose(gradient); this.textures.clear(); this.gradients.clear(); this.materials.clear(); } /** Add a material to this IdMap, given that it has a valid key. */ public addMaterial(material: RenderMaterial) { if (material.key) this.materials.set(material.key, material); } /** Add a texture to this IdMap, given that it has a valid key. */ public addTexture(texture: RenderTexture) { assert(texture instanceof Texture); if (texture.key) this.textures.set(texture.key, texture); } /** Add a texture to this IdMap using gradient symbology. */ public addGradient(gradientSymb: Gradient.Symb, texture: RenderTexture) { this.gradients.set(gradientSymb, texture); } /** Find a cached material using its key. If not found, returns undefined. */ public findMaterial(key: string): RenderMaterial | undefined { return this.materials.get(key); } /** Find a cached gradient using the gradient symbology. If not found, returns undefined. */ public findGradient(symb: Gradient.Symb): RenderTexture | undefined { return this.gradients.get(symb); } /** Find or create a new material given material parameters. This will cache the material if its key is valid. */ public getMaterial(params: RenderMaterial.Params): RenderMaterial { if (!params.key || !Id64.isValidId64(params.key)) // Only cache persistent materials. return new Material(params); let material = this.materials.get(params.key); if (!material) { material = new Material(params); this.materials.set(params.key, material); } return material; } public findTexture(key?: string | Gradient.Symb): RenderTexture | undefined { if (undefined === key) return undefined; else if (typeof key === "string") return this.textures.get(key); else return this.findGradient(key); } // eslint-disable-next-line deprecation/deprecation public getTextureFromElement(key: Id64String, iModel: IModelConnection, params: RenderTexture.Params, format: ImageSourceFormat): RenderTexture | undefined { let tex = this.findTexture(params.key); if (tex) return tex; const handle = TextureHandle.createForElement(key, iModel, params.type, format); if (!handle) return undefined; tex = new Texture({ handle, type: params.type, ownership: { key, iModel } }); this.addTexture(tex); return tex; } public async getTextureFromImageSource(args: CreateTextureFromSourceArgs, key: string): Promise<RenderTexture | undefined> { const texture = this.findTexture(key); if (texture) return texture; // Are we already in the process of decoding this image? let promise = this.texturesFromImageSources.get(key); if (promise) return promise; promise = this.createTextureFromImageSource(args, key); this.texturesFromImageSources.set(key, promise); return promise; } public async createTextureFromImageSource(args: CreateTextureFromSourceArgs, key: string): Promise<RenderTexture | undefined> { // JPEGs don't support transparency. const transparency = ImageSourceFormat.Jpeg === args.source.format ? TextureTransparency.Opaque : (args.transparency ?? TextureTransparency.Translucent); try { const image = await imageElementFromImageSource(args.source); if (!IModelApp.hasRenderSystem) return undefined; return IModelApp.renderSystem.createTexture({ type: args.type, ownership: args.ownership, image: { source: image, transparency, }, }); } catch { return undefined; } finally { this.texturesFromImageSources.delete(key); } } // eslint-disable-next-line deprecation/deprecation public getTextureFromCubeImages(posX: HTMLImageElement, negX: HTMLImageElement, posY: HTMLImageElement, negY: HTMLImageElement, posZ: HTMLImageElement, negZ: HTMLImageElement, params: RenderTexture.Params): RenderTexture | undefined { let tex = this.findTexture(params.key); if (tex) return tex; const handle = TextureHandle.createForCubeImages(posX, negX, posY, negY, posZ, negZ); if (!handle) return undefined; const ownership = params.key ? { key: params.key, iModel: this._iModel } : (params.isOwned ? "external" : undefined); tex = new Texture({ handle, ownership, type: params.type }); this.addTexture(tex); return tex; } public collectStatistics(stats: RenderMemory.Statistics): void { for (const texture of this.textures.values()) if (texture instanceof Texture) stats.addTexture(texture.bytesUsed); for (const gradient of this.gradients) if (gradient instanceof Texture) stats.addTexture(gradient.bytesUsed); } } export type TextureBinding = WebGLTexture | undefined; const enum VertexAttribState { Disabled = 0, Enabled = 1 << 0, Instanced = 1 << 2, InstancedEnabled = Instanced | Enabled, } interface TextureCacheInfo { idMap: IdMap; key: TextureCacheKey; } /** @internal */ export class System extends RenderSystem implements RenderSystemDebugControl, RenderMemory.Consumer, WebGLDisposable { public readonly canvas: HTMLCanvasElement; public readonly currentRenderState = new RenderState(); public readonly context: WebGLContext; public readonly frameBufferStack = new FrameBufferStack(); // frame buffers are not owned by the system public readonly capabilities: Capabilities; public readonly resourceCache: Map<IModelConnection, IdMap>; public readonly glTimer: GLTimer; private readonly _extensions: WebGLExtensions; private readonly _textureBindings: TextureBinding[] = []; private _removeEventListener?: () => void; // NB: Increase the size of these arrays when the maximum number of attributes used by any one shader increases. private readonly _curVertexAttribStates: VertexAttribState[] = [ VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, ]; private readonly _nextVertexAttribStates: VertexAttribState[] = [ VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, VertexAttribState.Disabled, ]; // The following are initialized immediately after the System is constructed. private _lineCodeTexture?: TextureHandle; private _noiseTexture?: TextureHandle; private _techniques?: Techniques; private _screenSpaceEffects?: ScreenSpaceEffects; public readonly debugShaderFiles: DebugShaderFile[] = []; public static get instance() { return IModelApp.renderSystem as System; } public get isValid(): boolean { return this.canvas !== undefined; } public get lineCodeTexture() { return this._lineCodeTexture; } public get noiseTexture() { return this._noiseTexture; } public get techniques() { assert(undefined !== this._techniques); return this._techniques; } public get screenSpaceEffects() { assert(undefined !== this._screenSpaceEffects); return this._screenSpaceEffects; } public override get maxTextureSize(): number { return this.capabilities.maxTextureSize; } public override get supportsInstancing(): boolean { return this.capabilities.supportsInstancing; } public override get supportsNonuniformScaledInstancing(): boolean { return this.capabilities.isWebGL2; } public get isWebGL2(): boolean { return this.capabilities.isWebGL2; } public override get isMobile(): boolean { return this.capabilities.isMobile; } public setDrawBuffers(attachments: GLenum[]): void { this._extensions.setDrawBuffers(attachments); } public doIdleWork(): boolean { return this.techniques.idleCompileNextShader(); } /** Return a Promise which when resolved indicates that all pending external textures have finished loading from the backend. */ public override async waitForAllExternalTextures(): Promise<void> { const extTexLoader = ExternalTextureLoader.instance; if (extTexLoader.numActiveRequests < 1 && extTexLoader.numPendingRequests < 1) return Promise.resolve(); const promise = new Promise<void>((resolve: any) => { extTexLoader.onTexturesLoaded.addOnce(() => { resolve(); }); }); return promise; } /** Attempt to create a WebGLRenderingContext, returning undefined if unsuccessful. */ public static createContext(canvas: HTMLCanvasElement, useWebGL2: boolean, inputContextAttributes?: WebGLContextAttributes): WebGLContext | undefined { let contextAttributes: WebGLContextAttributes = { powerPreference: "high-performance" }; if (undefined !== inputContextAttributes) { // NOTE: Order matters with spread operator - if caller wants to override powerPreference, he should be able to. contextAttributes = { ...contextAttributes, ...inputContextAttributes }; } // If requested, first try obtaining a WebGL2 context. let context = null; if (useWebGL2) context = canvas.getContext("webgl2", contextAttributes); // Fall back to WebGL1 if necessary. if (null === context) context = canvas.getContext("webgl", contextAttributes); return context ?? undefined; } public static create(optionsIn?: RenderSystem.Options): System { const options: RenderSystem.Options = undefined !== optionsIn ? optionsIn : {}; const canvas = document.createElement("canvas"); if (null === canvas) throw new IModelError(BentleyStatus.ERROR, "Failed to obtain HTMLCanvasElement"); const useWebGL2 = (undefined === options.useWebGL2 ? true : options.useWebGL2); const context = this.createContext(canvas, useWebGL2, optionsIn?.contextAttributes); if (undefined === context) { throw new IModelError(BentleyStatus.ERROR, "Failed to obtain WebGL context"); } const capabilities = Capabilities.create(context, options.disabledExtensions); if (undefined === capabilities) throw new IModelError(BentleyStatus.ERROR, "Failed to initialize rendering capabilities"); // set actual gl state to match desired state defaults context.depthFunc(GL.DepthFunc.Default); // LessOrEqual if (!capabilities.supportsShadowMaps) options.displaySolarShadows = false; if (!capabilities.supportsFragDepth) options.logarithmicDepthBuffer = false; if (!capabilities.supportsTextureFilterAnisotropic) { options.filterMapTextures = false; options.filterMapDrapeTextures = false; } return new this(canvas, context, capabilities, options); } public get isDisposed(): boolean { return undefined === this._techniques && undefined === this._lineCodeTexture && undefined === this._noiseTexture && undefined === this._screenSpaceEffects; } // Note: FrameBuffers inside of the FrameBufferStack are not owned by the System, and are only used as a central storage device public dispose() { this._techniques = dispose(this._techniques); this._screenSpaceEffects = dispose(this._screenSpaceEffects); this._lineCodeTexture = dispose(this._lineCodeTexture); this._noiseTexture = dispose(this._noiseTexture); // We must attempt to dispose of each idmap in the resourceCache (if idmap is already disposed, has no effect) this.resourceCache.forEach((idMap: IdMap) => { dispose(idMap); }); this.resourceCache.clear(); if (undefined !== this._removeEventListener) { this._removeEventListener(); this._removeEventListener = undefined; } } public override onInitialized(): void { this._techniques = Techniques.create(this.context); const noiseDim = 4; const noiseArr = new Uint8Array([152, 235, 94, 173, 219, 215, 115, 176, 73, 205, 43, 201, 10, 81, 205, 198]); this._noiseTexture = TextureHandle.createForData(noiseDim, noiseDim, noiseArr, false, GL.Texture.WrapMode.Repeat, GL.Texture.Format.Luminance); assert(undefined !== this._noiseTexture, "System.noiseTexture not created."); this._lineCodeTexture = TextureHandle.createForData(LineCode.size, LineCode.count, new Uint8Array(LineCode.lineCodeData), false, GL.Texture.WrapMode.Repeat, GL.Texture.Format.Luminance); assert(undefined !== this._lineCodeTexture, "System.lineCodeTexture not created."); this._screenSpaceEffects = new ScreenSpaceEffects(); } public createTarget(canvas: HTMLCanvasElement): RenderTarget { return new OnScreenTarget(canvas); } public createOffscreenTarget(rect: ViewRect): RenderTarget { return new OffScreenTarget(rect); } public createGraphic(options: CustomGraphicBuilderOptions | ViewportGraphicBuilderOptions): GraphicBuilder { return new PrimitiveBuilder(this, options); } public override createPlanarGrid(frustum: Frustum, grid: PlanarGridProps): RenderGraphic | undefined { return PlanarGridGeometry.create(frustum, grid, this); } public override createRealityMeshFromTerrain(terrainMesh: TerrainMeshPrimitive, transform?: Transform): RealityMeshGeometry | undefined { return RealityMeshGeometry.createFromTerrainMesh(terrainMesh, transform); } public override createRealityMeshGraphic(terrainGeometry: RealityMeshGeometry, featureTable: PackedFeatureTable, tileId: string | undefined, baseColor: ColorDef | undefined, baseTransparent: boolean, textures?: TerrainTexture[]): RenderGraphic | undefined { return RealityMeshGeometry.createGraphic(this, terrainGeometry, featureTable, tileId, baseColor, baseTransparent, textures); } public override createRealityMesh(realityMesh: RealityMeshPrimitive): RenderGraphic | undefined { const geom = RealityMeshGeometry.createFromRealityMesh(realityMesh); return geom ? Primitive.create(geom) : undefined; } public override createMeshGeometry(params: MeshParams, viOrigin?: Point3d): MeshRenderGeometry | undefined { return MeshRenderGeometry.create(params, viOrigin); } public override createPolylineGeometry(params: PolylineParams, viOrigin?: Point3d): PolylineGeometry | undefined { return PolylineGeometry.create(params, viOrigin); } public override createPointStringGeometry(params: PointStringParams, viOrigin?: Point3d): PointStringGeometry | undefined { return PointStringGeometry.create(params, viOrigin); } public override createAreaPattern(params: PatternGraphicParams): PatternBuffers | undefined { return PatternBuffers.create(params); } public override createRenderGraphic(geometry: RenderGeometry, instances?: InstancedGraphicParams | RenderAreaPattern): RenderGraphic | undefined { if (!(geometry instanceof MeshRenderGeometry)) { if (geometry instanceof PolylineGeometry || geometry instanceof PointStringGeometry) return Primitive.create(geometry, instances); assert(false, "Invalid RenderGeometry for System.createRenderGraphic"); return undefined; } assert(!instances || instances instanceof PatternBuffers || isInstancedGraphicParams(instances)); return MeshGraphic.create(geometry, instances); } public override createPointCloud(args: PointCloudArgs): RenderGraphic | undefined { return Primitive.create(new PointCloudGeometry(args)); } public createGraphicList(primitives: RenderGraphic[]): RenderGraphic { return new GraphicsArray(primitives); } public createGraphicBranch(branch: GraphicBranch, transform: Transform, options?: GraphicBranchOptions): RenderGraphic { return new Branch(branch, transform, undefined, options); } public createBatch(graphic: RenderGraphic, features: PackedFeatureTable, range: ElementAlignedBox3d, options?: BatchOptions): RenderGraphic { return new Batch(graphic, features, range, options); } public override createGraphicOwner(owned: RenderGraphic): RenderGraphicOwner { return new GraphicOwner(owned as Graphic); } public override createGraphicLayer(graphic: RenderGraphic, layerId: string) { return new Layer(graphic as Graphic, layerId); } public override createGraphicLayerContainer(graphic: RenderGraphic, drawAsOverlay: boolean, transparency: number, elevation: number) { return new LayerContainer(graphic as Graphic, drawAsOverlay, transparency, elevation); } public override createSkyBox(params: SkyBox.CreateParams): RenderGraphic | undefined { if (undefined !== params.cube) return SkyCubePrimitive.create(SkyBoxQuadsGeometry.create(params.cube)); assert(undefined !== params.sphere || undefined !== params.gradient); return SkySpherePrimitive.create(SkySphereViewportQuadGeometry.createGeometry(params)); } public override createScreenSpaceEffectBuilder(params: ScreenSpaceEffectBuilderParams): ScreenSpaceEffectBuilder { return createScreenSpaceEffectBuilder(params); } public applyRenderState(newState: RenderState) { newState.apply(this.currentRenderState); this.currentRenderState.copyFrom(newState); } public createDepthBuffer(width: number, height: number, numSamples: number = 1): DepthBuffer | undefined { // Note: The buffer/texture created here have ownership passed to the caller (system will not dispose of these) switch (this.capabilities.maxDepthType) { case DepthType.RenderBufferUnsignedShort16: { return RenderBuffer.create(width, height); } case DepthType.TextureUnsignedInt32: { return TextureHandle.createForAttachment(width, height, GL.Texture.Format.DepthComponent, GL.Texture.DataType.UnsignedInt); } case DepthType.TextureUnsignedInt24Stencil8: { if (this.capabilities.isWebGL2) { if (numSamples > 1) { return RenderBufferMultiSample.create(width, height, WebGL2RenderingContext.DEPTH24_STENCIL8, numSamples); } else { const context2 = this.context as WebGL2RenderingContext; return TextureHandle.createForAttachment(width, height, GL.Texture.Format.DepthStencil, context2.UNSIGNED_INT_24_8); } } else { const dtExt: WEBGL_depth_texture | undefined = this.capabilities.queryExtensionObject<WEBGL_depth_texture>("WEBGL_depth_texture"); return TextureHandle.createForAttachment(width, height, GL.Texture.Format.DepthStencil, dtExt!.UNSIGNED_INT_24_8_WEBGL); } } default: { assert(false); return undefined; } } } /** Returns the corresponding IdMap for an IModelConnection. Creates a new one if it doesn't exist. */ public createIModelMap(imodel: IModelConnection): IdMap { let idMap = this.resourceCache.get(imodel); if (!idMap) { idMap = new IdMap(imodel); this.resourceCache.set(imodel, idMap); } return idMap; } /** Removes an IModelConnection-IdMap pairing from the system's resource cache. */ private removeIModelMap(imodel: IModelConnection) { const idMap = this.resourceCache.get(imodel); if (idMap === undefined) return; dispose(idMap); this.resourceCache.delete(imodel); } /** Attempt to create a material for the given iModel using a set of material parameters. */ public override createMaterial(params: RenderMaterial.Params, imodel: IModelConnection): RenderMaterial | undefined { const idMap = this.getIdMap(imodel); const material = idMap.getMaterial(params); return material; } /** Using its key, search for an existing material of an open iModel. */ public override findMaterial(key: string, imodel: IModelConnection): RenderMaterial | undefined { const idMap = this.resourceCache.get(imodel); if (!idMap) return undefined; return idMap.findMaterial(key); } private getTextureCacheInfo(args: CreateTextureArgs): TextureCacheInfo | undefined { const owner = undefined !== args.ownership && args.ownership !== "external" ? args.ownership : undefined; return owner ? { idMap: this.getIdMap(owner.iModel), key: owner.key } : undefined; } public override createTexture(args: CreateTextureArgs): RenderTexture | undefined { const info = this.getTextureCacheInfo(args); const existing = info?.idMap.findTexture(info?.key); if (existing) return existing; const type = args.type ?? RenderTexture.Type.Normal; const source = args.image.source; // ###TODO createForImageBuffer should take args.transparency. let handle; if (source instanceof ImageBuffer) handle = TextureHandle.createForImageBuffer(source, type); // ###TODO use transparency from args else handle = TextureHandle.createForImage(source, TextureTransparency.Opaque !== args.image.transparency, type); if (!handle) return undefined; const texture = new Texture({ handle, type, ownership: args.ownership }); if (texture && info) info.idMap.addTexture(texture); return texture; } public override async createTextureFromSource(args: CreateTextureFromSourceArgs): Promise<RenderTexture | undefined> { if (typeof args.ownership !== "object") return super.createTextureFromSource(args); return this.getIdMap(args.ownership.iModel).getTextureFromImageSource(args, args.ownership.key); } // eslint-disable-next-line deprecation/deprecation public override createTextureFromElement(id: Id64String, imodel: IModelConnection, params: RenderTexture.Params, format: ImageSourceFormat): RenderTexture | undefined { return this.getIdMap(imodel).getTextureFromElement(id, imodel, params, format); } // eslint-disable-next-line deprecation/deprecation public override createTextureFromCubeImages(posX: HTMLImageElement, negX: HTMLImageElement, posY: HTMLImageElement, negY: HTMLImageElement, posZ: HTMLImageElement, negZ: HTMLImageElement, imodel: IModelConnection, params: RenderTexture.Params): RenderTexture | undefined { return this.getIdMap(imodel).getTextureFromCubeImages(posX, negX, posY, negY, posZ, negZ, params); } /** Attempt to create a texture using gradient symbology. */ public override getGradientTexture(symb: Gradient.Symb, iModel?: IModelConnection): RenderTexture | undefined { const source = symb.getImage(0x100, 0x100); return this.createTexture({ image: { source, transparency: ImageBufferFormat.Rgba === source.format ? TextureTransparency.Translucent : TextureTransparency.Opaque, }, ownership: iModel ? { iModel, key: symb } : undefined, type: RenderTexture.Type.Normal, }); } /** Using its key, search for an existing texture of an open iModel. */ public override findTexture(key: TextureCacheKey, imodel: IModelConnection): RenderTexture | undefined { const idMap = this.resourceCache.get(imodel); if (!idMap) return undefined; return idMap.findTexture(key); } public override createClipVolume(clipVector: ClipVector): RenderClipVolume | undefined { return ClipVolume.create(clipVector); } public override createBackgroundMapDrape(drapedTree: TileTreeReference, mapTree: MapTileTreeReference) { return BackgroundMapDrape.create(drapedTree, mapTree); } protected constructor(canvas: HTMLCanvasElement, context: WebGLContext, capabilities: Capabilities, options: RenderSystem.Options) { super(options); this.canvas = canvas; this.context = context; this.capabilities = capabilities; this.resourceCache = new Map<IModelConnection, IdMap>(); this.glTimer = GLTimer.create(this); if (capabilities.isWebGL2) this._extensions = new WebGL2Extensions(this); else { const drawBuffersExtension = capabilities.queryExtensionObject<WEBGL_draw_buffers>("WEBGL_draw_buffers"); const instancingExtension = capabilities.queryExtensionObject<ANGLE_instanced_arrays>("ANGLE_instanced_arrays"); this._extensions = new WebGL1Extensions(this, drawBuffersExtension, instancingExtension); } // Make this System a subscriber to the the IModelConnection onClose event this._removeEventListener = IModelConnection.onClose.addListener((imodel) => this.removeIModelMap(imodel)); canvas.addEventListener("webglcontextlost", async () => RenderSystem.contextLossHandler(), false); } /** Exposed strictly for tests. */ public getIdMap(imodel: IModelConnection): IdMap { const map = this.resourceCache.get(imodel); return undefined !== map ? map : this.createIModelMap(imodel); } private bindTexture(unit: TextureUnit, target: GL.Texture.Target, texture: TextureBinding, makeActive: boolean): void { const index = unit - TextureUnit.Zero; if (this._textureBindings[index] === texture) { if (makeActive) this.context.activeTexture(unit); return; } this._textureBindings[index] = texture; this.context.activeTexture(unit); this.context.bindTexture(target, undefined !== texture ? texture : null); } /** Bind the specified texture to the specified unit. This may *or may not* make the texture *active* */ public bindTexture2d(unit: TextureUnit, texture: TextureBinding) { this.bindTexture(unit, GL.Texture.Target.TwoDee, texture, false); } /** Bind the specified texture to the specified unit. This may *or may not* make the texture *active* */ public bindTextureCubeMap(unit: TextureUnit, texture: TextureBinding) { this.bindTexture(unit, GL.Texture.Target.CubeMap, texture, false); } /** Bind the specified texture to the specified unit. This *always* makes the texture *active* */ public activateTexture2d(unit: TextureUnit, texture: TextureBinding) { this.bindTexture(unit, GL.Texture.Target.TwoDee, texture, true); } /** Bind the specified texture to the specified unit. This *always* makes the texture *active* */ public activateTextureCubeMap(unit: TextureUnit, texture: TextureBinding) { this.bindTexture(unit, GL.Texture.Target.CubeMap, texture, true); } // Ensure *something* is bound to suppress 'no texture assigned to unit x' warnings. public ensureSamplerBound(uniform: UniformHandle, unit: TextureUnit): void { this.lineCodeTexture!.bindSampler(uniform, unit); } public override get maxRealityImageryLayers() { return Math.min(this.capabilities.maxFragTextureUnits, this.capabilities.maxVertTextureUnits) < 16 ? 3 : 6; } public disposeTexture(texture: WebGLTexture) { System.instance.context.deleteTexture(texture); for (let i = 0; i < this._textureBindings.length; i++) { if (this._textureBindings[i] === texture) { this._textureBindings[i] = undefined; break; } } } // System keeps track of current enabled state of vertex attribute arrays. // This prevents errors caused by leaving a vertex attrib array enabled after disposing of the buffer bound to it; // also prevents unnecessarily 'updating' the enabled state of a vertex attrib array when it hasn't actually changed. public enableVertexAttribArray(id: number, instanced: boolean): void { assert(id < this._nextVertexAttribStates.length, "if you add new vertex attributes you must update array length"); assert(id < this._curVertexAttribStates.length, "if you add new vertex attributes you must update array length"); this._nextVertexAttribStates[id] = instanced ? VertexAttribState.InstancedEnabled : VertexAttribState.Enabled; } public updateVertexAttribArrays(): void { const cur = this._curVertexAttribStates; const next = this._nextVertexAttribStates; const context = this.context; for (let i = 0; i < next.length; i++) { const oldState = cur[i]; const newState = next[i]; if (oldState !== newState) { // Update the enabled state if it changed. const wasEnabled = 0 !== (VertexAttribState.Enabled & oldState); const nowEnabled = 0 !== (VertexAttribState.Enabled & newState); if (wasEnabled !== nowEnabled) { if (nowEnabled) { context.enableVertexAttribArray(i); } else { context.disableVertexAttribArray(i); } } // Only update the divisor if the attribute is enabled. if (nowEnabled) { const wasInstanced = 0 !== (VertexAttribState.Instanced & oldState); const nowInstanced = 0 !== (VertexAttribState.Instanced & newState); if (wasInstanced !== nowInstanced) { this.vertexAttribDivisor(i, nowInstanced ? 1 : 0); } } cur[i] = newState; } // Set the attribute back to disabled, but preserve the divisor. next[i] &= ~VertexAttribState.Enabled; } } public vertexAttribDivisor(index: number, divisor: number) { this._extensions.vertexAttribDivisor(index, divisor); } public drawArrays(type: GL.PrimitiveType, first: number, count: number, numInstances: number): void { if (0 !== numInstances) { this._extensions.drawArraysInst(type, first, count, numInstances); } else { this.context.drawArrays(type, first, count); } } public invalidateFrameBuffer(attachments: number[]): void { this._extensions.invalidateFrameBuffer(attachments); } public override enableDiagnostics(enable: RenderDiagnostics): void { Debug.printEnabled = RenderDiagnostics.None !== (enable & RenderDiagnostics.DebugOutput); Debug.evaluateEnabled = RenderDiagnostics.None !== (enable & RenderDiagnostics.WebGL); } // RenderSystemDebugControl public override get debugControl(): RenderSystemDebugControl { return this; } private _drawSurfacesAsWiremesh = false; public get drawSurfacesAsWiremesh() { return this._drawSurfacesAsWiremesh; } public set drawSurfacesAsWiremesh(asWiremesh: boolean) { this._drawSurfacesAsWiremesh = asWiremesh; } private _dpiAwareLOD?: boolean; public override get dpiAwareLOD(): boolean { return this._dpiAwareLOD ?? super.dpiAwareLOD; } public override set dpiAwareLOD(dpiAware: boolean) { this._dpiAwareLOD = dpiAware; } public loseContext(): boolean { const ext = this.capabilities.queryExtensionObject<WEBGL_lose_context>("WEBGL_lose_context"); if (undefined === ext) return false; ext.loseContext(); return true; } public compileAllShaders(): boolean { return this.techniques.compileShaders(); } public get isGLTimerSupported(): boolean { return this.glTimer.isSupported; } public set resultsCallback(callback: GLTimerResultCallback | undefined) { this.glTimer.resultsCallback = callback; } public override collectStatistics(stats: RenderMemory.Statistics): void { if (undefined !== this._lineCodeTexture) stats.addTexture(this._lineCodeTexture.bytesUsed); if (undefined !== this._noiseTexture) stats.addTexture(this._noiseTexture.bytesUsed); for (const idMap of this.resourceCache.values()) idMap.collectStatistics(stats); } public setMaxAnisotropy(max: number | undefined): void { this.capabilities.setMaxAnisotropy(max, this.context); } }
the_stack
import { NowResponse, NowRequest } from "@vercel/node"; import { getHtml } from "../../util/template"; import { writeTempFile, pathToFileURL } from "../../util/file"; import { getScreenshot } from "../../util/chromium"; import { fetchCaseGraph } from "../../util/fetcher"; const isDev = process.env.NOW_REGION === "dev1"; const getAgeKey = pasien => { if (!pasien.umur) return `U`; if (pasien.umur < 5) { return `B`; } else if (pasien.umur < 19) { return `A`; } else if (pasien.umur < 50) { return `D`; } else { return `T`; } }; // const umurReducer = (accumulated, current) => { // const ageKey = getAgeKey(current) // return { // ...accumulated, // [ageKey]: { // L: (accumulated[ageKey] && accumulated[ageKey].L || 0) + (current.jenis_kelamin === 1 ? 1 : 0), // P: (accumulated[ageKey] && accumulated[ageKey].P || 0) + (current.jenis_kelamin === 0 ? 1 : 0), // U: (accumulated[ageKey] && accumulated[ageKey].U || 0) + (current.jenis_kelamin === 2 ? 1 : 0), // } // } // } const emojis = { B: { 0: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/baby_1f476.png`, 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/baby_emoji-modifier-fitzpatrick-type-1-2_1f476-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/baby_emoji-modifier-fitzpatrick-type-3_1f476-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/baby_emoji-modifier-fitzpatrick-type-4_1f476-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/baby_emoji-modifier-fitzpatrick-type-5_1f476-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/baby_emoji-modifier-fitzpatrick-type-6_1f476-1f3ff_1f3ff.png` }, A: { U: { 0: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/child_1f9d2.png`, 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/child_emoji-modifier-fitzpatrick-type-1-2_1f9d2-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/child_emoji-modifier-fitzpatrick-type-3_1f9d2-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/child_emoji-modifier-fitzpatrick-type-4_1f9d2-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/child_emoji-modifier-fitzpatrick-type-5_1f9d2-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/child_emoji-modifier-fitzpatrick-type-6_1f9d2-1f3ff_1f3ff.png` }, L: { 0: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/boy_1f466.png`, 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/boy_emoji-modifier-fitzpatrick-type-1-2_1f466-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/boy_emoji-modifier-fitzpatrick-type-3_1f466-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/boy_emoji-modifier-fitzpatrick-type-4_1f466-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/boy_emoji-modifier-fitzpatrick-type-5_1f466-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/boy_emoji-modifier-fitzpatrick-type-6_1f466-1f3ff_1f3ff.png` }, P: { 0: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/girl_1f467.png`, 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/girl_emoji-modifier-fitzpatrick-type-1-2_1f467-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/girl_emoji-modifier-fitzpatrick-type-3_1f467-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/girl_emoji-modifier-fitzpatrick-type-4_1f467-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/girl_emoji-modifier-fitzpatrick-type-5_1f467-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/girl_emoji-modifier-fitzpatrick-type-6_1f467-1f3ff_1f3ff.png` } }, D: { U: { 0: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/adult_1f9d1.png`, 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/adult_emoji-modifier-fitzpatrick-type-1-2_1f9d1-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/adult_emoji-modifier-fitzpatrick-type-3_1f9d1-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/adult_emoji-modifier-fitzpatrick-type-4_1f9d1-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/adult_emoji-modifier-fitzpatrick-type-5_1f9d1-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/adult_emoji-modifier-fitzpatrick-type-6_1f9d1-1f3ff_1f3ff.png` }, L: { 0: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man_1f468.png`, 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man_emoji-modifier-fitzpatrick-type-1-2_1f468-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man_emoji-modifier-fitzpatrick-type-3_1f468-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man_emoji-modifier-fitzpatrick-type-4_1f468-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man_emoji-modifier-fitzpatrick-type-5_1f468-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man_emoji-modifier-fitzpatrick-type-6_1f468-1f3ff_1f3ff.png` }, P: { 0: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman_1f469.png`, 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman_emoji-modifier-fitzpatrick-type-1-2_1f469-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman_emoji-modifier-fitzpatrick-type-3_1f469-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman_emoji-modifier-fitzpatrick-type-4_1f469-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman_emoji-modifier-fitzpatrick-type-5_1f469-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman_emoji-modifier-fitzpatrick-type-6_1f469-1f3ff_1f3ff.png` } }, T: { U: { 0: "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-adult_1f9d3.png", 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-adult_emoji-modifier-fitzpatrick-type-1-2_1f9d3-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-adult_emoji-modifier-fitzpatrick-type-3_1f9d3-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-adult_emoji-modifier-fitzpatrick-type-4_1f9d3-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-adult_emoji-modifier-fitzpatrick-type-5_1f9d3-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-adult_emoji-modifier-fitzpatrick-type-6_1f9d3-1f3ff_1f3ff.png` }, L: { 0: "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-man_1f474.png", 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-man_emoji-modifier-fitzpatrick-type-1-2_1f474-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-man_emoji-modifier-fitzpatrick-type-3_1f474-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-man_emoji-modifier-fitzpatrick-type-4_1f474-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-man_emoji-modifier-fitzpatrick-type-5_1f474-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-man_emoji-modifier-fitzpatrick-type-6_1f474-1f3ff_1f3ff.png` }, P: { 0: "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-woman_1f475.png", 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-woman_emoji-modifier-fitzpatrick-type-1-2_1f475-1f3fb_1f3fb.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-woman_emoji-modifier-fitzpatrick-type-3_1f475-1f3fc_1f3fc.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-woman_emoji-modifier-fitzpatrick-type-4_1f475-1f3fd_1f3fd.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-woman_emoji-modifier-fitzpatrick-type-5_1f475-1f3fe_1f3fe.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/older-woman_emoji-modifier-fitzpatrick-type-6_1f475-1f3ff_1f3ff.png` } }, U: { U: { 0: "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/person-bald_1f9d1-200d-1f9b2.png", 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/person-light-skin-tone-bald_1f9d1-1f3fb-200d-1f9b2.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/person-medium-light-skin-tone-bald_1f9d1-1f3fc-200d-1f9b2.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/person-medium-skin-tone-bald_1f9d1-1f3fd-200d-1f9b2.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/person-medium-dark-skin-tone-bald_1f9d1-1f3fe-200d-1f9b2.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/person-dark-skin-tone-bald_1f9d1-1f3ff-200d-1f9b2.png` }, L: { 0: "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man-bald_1f468-200d-1f9b2.png", 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man-bald-light-skin-tone_1f468-1f3fb-200d-1f9b2.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man-bald-medium-light-skin-tone_1f468-1f3fc-200d-1f9b2.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man-bald-medium-skin-tone_1f468-1f3fd-200d-1f9b2.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man-bald-medium-dark-skin-tone_1f468-1f3fe-200d-1f9b2.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/man-bald-dark-skin-tone_1f468-1f3ff-200d-1f9b2.png` }, P: { 0: "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman-bald_1f469-200d-1f9b2.png", 1: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman-bald-light-skin-tone_1f469-1f3fb-200d-1f9b2.png`, 2: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman-bald-medium-light-skin-tone_1f469-1f3fc-200d-1f9b2.png`, 3: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman-bald-medium-skin-tone_1f469-1f3fd-200d-1f9b2.png`, 4: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman-bald-medium-dark-skin-tone_1f469-1f3fe-200d-1f9b2.png`, 5: `https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/woman-bald-dark-skin-tone_1f469-1f3ff-200d-1f9b2.png` } } }; const metaMapper = pasien => ({ age: getAgeKey(pasien), gender: ["P", "L", "U"][pasien.jenis_kelamin ?? 2], status: ["Meninggal", "Sembuh", "Masih Dirawat"][pasien.id_status ?? 2], variant: ((pasien.id_pasien * (pasien.umur ?? 0)) % 5) + 1 }); const emojiMapper = meta => ({ src: meta.age === "B" ? emojis[meta.age][meta.variant] : emojis[meta.age][meta.gender][meta.variant], status: meta.status }); const sortByKasus = (pasienA, pasienB) => pasienA.kode_pasien - pasienB.kode_pasien; const srcToImg = ({ src, status }) => status === "Meninggal" ? `<div class="person"><img class="img back" src="${src}" /><img class="img front" src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/cross-mark_274c.png" /></div>` : status === "Sembuh" ? `<div class="person"><img class="img back" src="${src}" /><img class="img front" src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/white-heavy-check-mark_2705.png" /></div>` : `<div class="person"><img src="${src}" class="img" /></div>`; const dateReducer = (accumulated, current) => { return { ...accumulated, [current.added_date]: (accumulated[current.added_date] || 0) + 1 }; }; export default async function handler(req: NowRequest, res: NowResponse) { try { const width = parseInt(req.query.width as string, 10) || 1200; const height = parseInt(req.query.height as string, 10) || 627; const isHtmlDebug = isDev && (process.env.OG_HTML_DEBUG === "1" || req.query.debug === "true"); const daysOffset = req.query.daysOffset ? parseInt(req.query.daysOffset as string, 10) : 0; const data = await fetchCaseGraph(); const days = Object.keys(data.reduce(dateReducer, {})); const day = days.slice(-1 * daysOffset - 1)[0]; const sorted = data.sort(sortByKasus); const emojis = sorted .filter(p => p.added_date <= day) .map(metaMapper) .map(emojiMapper) .map(srcToImg); const html = getHtml({ emojis, width, height }); if (isHtmlDebug) { res.setHeader("Content-Type", "text/html"); res.end(html); return; } const text = JSON.stringify({ emojis, width, height }); const filePath = await writeTempFile(text, html); const fileUrl = pathToFileURL(filePath); const file = await getScreenshot(fileUrl, isDev, width, height); res.setHeader("Content-Type", `image/png`); res.end(file); } catch (e) { res.statusCode = 500; res.setHeader("Content-Type", "text/html"); res.end("<h1>Internal Error</h1><p>Sorry, there was a problem</p>"); console.error(e); } }
the_stack
import { DetachedSequenceId, NodeId, TraitLabel, UuidString } from '../Identifiers'; import { Side } from '../Snapshot'; import { EditBase, BuildNode, NodeData, Payload, TraitLocation, TreeNodeSequence } from '../generic'; import { Build, Change, ConstraintEffect, Detach, Insert, Move, SetValue, StablePlace, StableRange, Constraint, getNodeId, } from '../default-edits'; /** * Types for Edits in Fluid Ops and Fluid summaries. * * Types describing locations in the tree are stable in the presence of other concurrent edits. * * All types are compatible with Fluid Serializable. * * These types can only be modified in ways that are both backwards and forwards compatible since they * are used in edits, and thus are persisted (using Fluid serialization). * * This means these types cannot be changed in any way that impacts their Fluid serialization * except through a very careful process: * * 1. The planned change must support all old data, and maintain the exact semantics of it. * This means that the change is pretty much limited to adding optional fields, * or making required fields optional. * 2. Support for the new format must be deployed to all users (This means all applications using SharedTree must do this), * and this deployment must be confirmed to be stable and will not be rolled back. * 3. Usage of the new format may start. * * Support for the old format can NEVER be removed: it must be maintained indefinably or old documents will break. * Because this process puts requirements on applications using shared tree, * step 3 should only ever be done in a Major version update, * and must be explicitly called out in the release notes * stating which versions of SharedTree are supported for documents modified by the new version. */ /** * The information included in an anchored edit. * @public */ export type AnchoredEditBase = EditBase<AnchoredChange>; /** * A change that composes an Edit. * * `Change` objects can be conveniently constructed with the helper methods exported on a constant of the same name. * @example * Change.insert(sourceId, destination) * @public */ export type AnchoredChange = AnchoredInsert | AnchoredDetach | Build | AnchoredSetValue | AnchoredConstraint; /** * Inserts a sequence of nodes at the specified destination. * The source can be constructed either by a Build (used to insert new nodes) or a Detach (amounts to a "move" operation). * @public */ export interface AnchoredInsert extends Insert { readonly destination: PlaceAnchor; } /** * Removes a sequence of nodes from the tree. * If a destination is specified, the detached sequence is associated with that ID and held for possible reuse * by later changes in this same Edit (such as by an Insert). * A Detach without a destination is a deletion of the specified sequence, as is a Detach with a destination that is not used later. * @public */ export interface AnchoredDetach extends Detach { readonly source: RangeAnchor; } /** * Modifies the payload of a node. * @public */ export interface AnchoredSetValue extends SetValue { readonly nodeToModify: NodeAnchor; } /** * A set of constraints on the validity of an Edit. * A Constraint is used to detect when an Edit, due to other concurrent edits, may have unintended effects or merge in * non-semantic ways. It is processed in order like any other Change in an Edit. It can cause an edit to fail if the * various constraints are not met at the time of evaluation (ex: the parentNode has changed due to concurrent editing). * Does not modify the document. * @public */ export interface AnchoredConstraint extends Constraint { /** * Selects a sequence of nodes which will be checked against the constraints specified by the optional fields. * If `toConstrain` is invalid, it will be treated like a constraint being unmet. * Depending on `effect` this may or may not make the Edit invalid. * * When a constraint is not met, the effects is specified by `effect`. */ readonly toConstrain: RangeAnchor; } // Note: Documentation of this constant is merged with documentation of the `AnchoredChange` interface. /** * @public */ export const AnchoredChange = { build: Change.build, insert: Change.insert as (source: DetachedSequenceId, destination: PlaceAnchor) => AnchoredInsert, detach: Change.detach as (source: RangeAnchor, destination?: DetachedSequenceId) => AnchoredDetach, setPayload: Change.setPayload as (nodeToModify: NodeAnchor, payload: Payload) => AnchoredSetValue, clearPayload: Change.clearPayload as (nodeToModify: NodeAnchor) => AnchoredSetValue, constraint: Change.constraint as ( toConstrain: RangeAnchor, effect: ConstraintEffect, identityHash?: UuidString, length?: number, contentHash?: UuidString, parentNode?: NodeId, label?: TraitLabel ) => AnchoredConstraint, }; /** * Helper for creating a `Delete` edit. * @public */ export const AnchoredDelete = { /** * @returns an AnchoredChange that deletes the supplied part of the tree. */ create: (rangeAnchor: RangeAnchor): AnchoredChange => AnchoredChange.detach(rangeAnchor), }; /** * Helper for creating an `Insert` edit. * @public */ export const AnchoredInsert = { /** * @returns an AnchoredChange that inserts 'nodes' into the specified location in the tree. */ create: Insert.create as (nodes: TreeNodeSequence<BuildNode>, destination: PlaceAnchor) => AnchoredChange[], }; /** * Helper for creating a `Move` edit. * @public */ export const AnchoredMove = { /** * @returns an AnchoredChange that moves the specified content to a new location in the tree. */ create: Move.create as (source: RangeAnchor, destination: PlaceAnchor) => AnchoredChange[], }; /** * Indicates one of the predefined alternatives for the semantics of a place in a tree. */ export enum PlaceAnchorSemanticsChoice { /** * The resulting `PlaceAnchor` is valid iff the referenced sibling or parent node with the given ID exists in the snapshot on which the * change is applied. */ BoundToNode = 0, /** * The resulting `PlaceAnchor` is interpreted as relative to the siblings in the trait (or the parent in the case of start and end). * If the sibling referenced in the `PlaceAnchor` is moved, the anchor moves with it. * If the sibling referenced in the `PlaceAnchor` is deleted, the anchor is interpreted as relative to the next remaining sibling. * If no siblings remain on the side of interest (before the referenced sibling for "After" places and after the referenced sibling * for "Before" places) then the anchor is interpreted relative to the containing parent/trait (the start of the trait for "After" * places and the end of the trait for "Before" places). * If no siblings and no parent remains, the anchor is invalid. */ RelativeToNode = 1, // Future work: // RelativeToRank = 2, } /** * A location in a trait with associated merge semantics. * See also `StablePlace`. * `PlaceAnchor`. objects can be conveniently constructed with the helper methods exported on a constant of the same name. * @example * PlaceAnchor.before(node) * PlaceAnchor.atStartOf(trait) * @public */ export interface PlaceAnchor extends StablePlace { /** * The choice of semantics for the place. * No value is equivalent to PlaceAnchorSemanticsChoice.BoundToNode. */ readonly semantics?: PlaceAnchorSemanticsChoice; } export type RelativePlaceAnchor = PlaceAnchor & { semantic: PlaceAnchorSemanticsChoice.RelativeToNode }; /** * Specifies the range of nodes from `start` to `end` within a trait. * See also `StableRange`. * Valid iff start and end are valid and are within the same trait and the start does not occur after the end in the trait. * * `RangeAnchor`s are currently resolved by resolving their constituent places and checking the validity of the resulting range. * This may lead to the range becoming invalid (i.e., cannot be resolved) despite there being reasonable ways to salvage it. * For example the range [After(B), Before(D)] in the trait [A, B, C, D] would be made invalid by a change that moves B after D. * A reasonable resolution would be to resolve the range to [After(A), Before(D)]. The current implementation will instead treat * the range as invalid. * Future improvements may offer more a resilient resolution strategy for ranges. * * `RangeAnchor` objects can be conveniently constructed with the helper methods exported on a constant of the same name. * @example * RangeAnchor.from(PlaceAnchor.before(startNode)).to(PlaceAnchor.after(endNode)) * @public */ export interface RangeAnchor extends StableRange { readonly start: PlaceAnchor; readonly end: PlaceAnchor; } export type NodeAnchor = NodeId; /** * The remainder of this file consists of ergonomic factory methods for persisted types, or common combinations thereof (e.g. "Move" as a * combination of a "Detach" change and an "Insert" change). * * None of these helpers are persisted in documents, and therefore changes to their semantics need only follow standard semantic versioning * practices. */ // Note: Documentation of this constant is merged with documentation of the `PlaceAnchor` interface. /** * @public */ export const PlaceAnchor = { /** * @returns The location directly before `node`. */ before: ( node: NodeData | NodeId, semantics: PlaceAnchorSemanticsChoice = PlaceAnchorSemanticsChoice.RelativeToNode ): PlaceAnchor => ({ side: Side.Before, referenceSibling: getNodeId(node), semantics, }), /** * @returns The location directly after `node`. */ after: ( node: NodeData | NodeId, semantics: PlaceAnchorSemanticsChoice = PlaceAnchorSemanticsChoice.RelativeToNode ): PlaceAnchor => ({ side: Side.After, referenceSibling: getNodeId(node), semantics }), /** * @returns The location at the start of `trait`. */ atStartOf: ( trait: TraitLocation, semantics: PlaceAnchorSemanticsChoice = PlaceAnchorSemanticsChoice.RelativeToNode ): PlaceAnchor => ({ side: Side.After, referenceTrait: trait, semantics }), /** * @returns The location at the end of `trait`. */ atEndOf: ( trait: TraitLocation, semantics: PlaceAnchorSemanticsChoice = PlaceAnchorSemanticsChoice.RelativeToNode ): PlaceAnchor => ({ side: Side.Before, referenceTrait: trait, semantics }), }; // Note: Documentation of this constant is merged with documentation of the `RangeAnchor` interface. /** * @public */ export const RangeAnchor = { /** * Factory for producing a `RangeAnchor` from a start `StablePlace` to an end `StablePlace`. * @example * RangeAnchor.from(StablePlace.before(startNode)).to(StablePlace.after(endNode)) */ from: StableRange.from as (start: PlaceAnchor) => { to: (end: PlaceAnchor) => RangeAnchor }, /** * @returns a `RangeAnchor` which contains only the provided `node`. * Both the start and end `PlaceAnchor` objects used to anchor this `RangeAnchor` are in terms of the passed in node. */ only: ( node: NodeData | NodeAnchor, semantics: PlaceAnchorSemanticsChoice = PlaceAnchorSemanticsChoice.RelativeToNode ): RangeAnchor => ({ start: PlaceAnchor.before(node, semantics), end: PlaceAnchor.after(node, semantics) }), /** * @returns a `RangeAnchor` which contains everything in the trait. * This is anchored using the provided `trait`, and is independent of the actual contents of the trait: * it does not use sibling anchoring. */ all: StableRange.all as (trait: TraitLocation) => RangeAnchor, };
the_stack
import type { IntlShape } from 'react-intl'; import type { TApplicationContext } from '@commercetools-frontend/application-shell-connectors'; import type { Command } from './types'; import { oneLineTrim } from 'common-tags'; import { hasSomePermissions } from '@commercetools-frontend/permissions'; import { LOGOUT_REASONS, SUPPORT_PORTAL_URL, } from '@commercetools-frontend/constants'; import { permissions } from './constants'; import messages from './messages'; import { location } from '../../utils/location'; import { actionTypes } from './types'; function nonNullable<T>(value: T | boolean): value is NonNullable<T> { return value !== null && value !== undefined && typeof value !== 'boolean'; } type CreateCommandsOptions = { intl: IntlShape; applicationContext: TApplicationContext<{}>; featureToggles: { [key: string]: boolean }; changeProjectDataLocale?: (locale: string) => void; }; const createCommands = ({ intl, applicationContext, featureToggles, changeProjectDataLocale, }: CreateCommandsOptions): Command[] => { return [ applicationContext.project && applicationContext.permissions && featureToggles.canViewDashboard && hasSomePermissions( [permissions.ViewOrders], applicationContext.permissions ) && { id: 'go/dashboard', text: intl.formatMessage(messages.openDashboard), keywords: ['Go to Dashboard'], action: { type: actionTypes.go, to: `/${applicationContext.project.key}/dashboard`, }, }, applicationContext.project && applicationContext.permissions && hasSomePermissions( [permissions.ViewProducts], applicationContext.permissions ) && { id: 'go/products', text: intl.formatMessage(messages.openProducts), keywords: ['Go to Products'], action: { type: actionTypes.go, to: `/${applicationContext.project.key}/products/pim-search`, }, subCommands: [ hasSomePermissions( [permissions.ViewProducts], applicationContext.permissions ) && { id: 'go/products/list', text: intl.formatMessage(messages.openProductList), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/products/pim-search`, }, }, hasSomePermissions( [permissions.ViewProducts], applicationContext.permissions ) && { id: 'go/products/modified', text: intl.formatMessage(messages.openModifiedProducts), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/products/modified`, }, }, hasSomePermissions( [permissions.ViewProducts], applicationContext.permissions ) && featureToggles.pimSearch && { id: 'go/products/pim-search', text: intl.formatMessage(messages.openPimSearch), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/products/pim-search`, }, }, hasSomePermissions( [permissions.ManageProducts], applicationContext.permissions ) && { id: 'go/products/add', text: intl.formatMessage(messages.openAddProducts), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/products/new`, }, }, ].filter(nonNullable), }, applicationContext.project && applicationContext.permissions && hasSomePermissions( [permissions.ViewCategories], applicationContext.permissions ) && { id: 'go/categories', text: intl.formatMessage(messages.openCategories), keywords: ['Go to Categories'], action: { type: actionTypes.go, to: `/${applicationContext.project.key}/categories`, }, subCommands: [ hasSomePermissions( [permissions.ViewCategories], applicationContext.permissions ) && { id: 'go/categories/list', text: intl.formatMessage(messages.openCategoriesList), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/categories?mode=list`, }, }, hasSomePermissions( [permissions.ViewCategories], applicationContext.permissions ) && { id: 'go/categories/search', text: intl.formatMessage(messages.openCategoriesSearch), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/categories?mode=search`, }, }, hasSomePermissions( [permissions.ManageCategories], applicationContext.permissions ) && { id: 'go/categories/add', text: intl.formatMessage(messages.openAddCategory), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/categories/new`, }, }, ].filter(nonNullable), }, applicationContext.project && applicationContext.permissions && hasSomePermissions( [permissions.ViewCustomers, permissions.ViewCustomerGroups], applicationContext.permissions ) && { id: 'go/customers', text: intl.formatMessage(messages.openCustomers), keywords: ['Go to Customers'], action: { type: actionTypes.go, to: `/${applicationContext.project.key}/customers`, }, subCommands: [ hasSomePermissions( [permissions.ViewCustomers], applicationContext.permissions ) && { id: 'go/customers/list', text: intl.formatMessage(messages.openCustomersList), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/customers`, }, }, hasSomePermissions( [permissions.ManageCustomers], applicationContext.permissions ) && { id: 'go/customers/new', text: intl.formatMessage(messages.openAddCustomer), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/customers/new`, }, }, hasSomePermissions( [permissions.ViewCustomerGroups], applicationContext.permissions ) && { id: 'go/customer/customer-groups', text: intl.formatMessage(messages.openCustomerGroupsList), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/customers/customer-groups`, }, }, hasSomePermissions( [permissions.ManageCustomerGroups], applicationContext.permissions ) && { id: 'go/customers/customer-groups/add', text: intl.formatMessage(messages.openAddCustomerGroup), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/customers/customer-groups/new`, }, }, ].filter(nonNullable), }, applicationContext.project && applicationContext.permissions && hasSomePermissions( [permissions.ViewOrders], applicationContext.permissions ) && { id: 'go/orders', text: intl.formatMessage(messages.openOrders), keywords: ['Go to Orders'], action: { type: actionTypes.go, to: `/${applicationContext.project.key}/orders`, }, subCommands: [ hasSomePermissions( [permissions.ViewOrders], applicationContext.permissions ) && { id: 'go/orders/list', text: intl.formatMessage(messages.openOrdersList), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/orders`, }, }, hasSomePermissions( [permissions.ManageOrders], applicationContext.permissions ) && { id: 'go/orders/add', text: intl.formatMessage(messages.openAddOrder), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/orders/new`, }, }, ].filter(nonNullable), }, applicationContext.project && applicationContext.permissions && hasSomePermissions( [ permissions.ViewDiscountCodes, permissions.ViewProductDiscounts, permissions.ViewCartDiscounts, ], applicationContext.permissions ) && { id: 'go/discounts', text: intl.formatMessage(messages.openDiscounts), keywords: ['Go to Discounts'], action: { type: actionTypes.go, to: `/${applicationContext.project.key}/discounts`, }, subCommands: [ hasSomePermissions( [permissions.ViewProductDiscounts], applicationContext.permissions ) && { id: 'go/discounts/products/list', text: intl.formatMessage(messages.openProductDiscountsList), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/discounts/products`, }, }, hasSomePermissions( [permissions.ViewCartDiscounts], applicationContext.permissions ) && { id: 'go/discounts/carts/list', text: intl.formatMessage(messages.openCartDiscountsList), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/discounts/carts`, }, }, hasSomePermissions( [permissions.ViewDiscountCodes], applicationContext.permissions ) && { id: 'go/discounts/codes/list', text: intl.formatMessage(messages.openDiscountCodesList), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/discounts/codes`, }, }, hasSomePermissions( [ permissions.ManageProductDiscounts, permissions.ManageDiscountCodes, permissions.ManageCartDiscounts, ], applicationContext.permissions ) && { id: 'go/discounts/add', text: intl.formatMessage(messages.openAddDiscount), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/discounts/new`, }, subCommands: [ hasSomePermissions( [permissions.ManageProductDiscounts], applicationContext.permissions ) && { id: 'go/discounts/product/add', text: intl.formatMessage(messages.openAddProductDiscount), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/discounts/products/new`, }, }, hasSomePermissions( [permissions.ManageCartDiscounts], applicationContext.permissions ) && { id: 'go/discounts/cart/add', text: intl.formatMessage(messages.openAddCartDiscount), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/discounts/carts/new`, }, }, hasSomePermissions( [permissions.ManageDiscountCodes], applicationContext.permissions ) && { id: 'go/discounts/code/add', text: intl.formatMessage(messages.openAddCartDiscount), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/discounts/codes/new`, }, }, ].filter(nonNullable), }, ].filter(nonNullable), }, applicationContext.project && applicationContext.permissions && hasSomePermissions( [ permissions.ViewProjectSettings, permissions.ViewDeveloperSettings, permissions.ViewProductTypes, ], applicationContext.permissions ) && { id: 'go/settings', text: intl.formatMessage(messages.openSettings), keywords: ['Go to Settings'], action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/project`, }, subCommands: [ hasSomePermissions( [ permissions.ViewProjectSettings, permissions.ManageProjectSettings, ], applicationContext.permissions ) && { id: 'go/settings/project', text: intl.formatMessage(messages.openProjectSettings), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/project`, }, subCommands: [ { id: 'go/settings/project/international', text: intl.formatMessage( messages.openProjectSettingsInternationalTab ), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/project/international`, }, }, { id: 'go/settings/project/taxes', text: intl.formatMessage(messages.openProjectSettingsTaxesTab), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/project/taxes`, }, }, { id: 'go/settings/project/shipping-methods', text: intl.formatMessage( messages.openProjectSettingsShippingMethodsTab ), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/project/shipping-methods`, }, }, { id: 'go/settings/project/channels', text: intl.formatMessage( messages.openProjectSettingsChannelsTab ), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/project/channels`, }, }, { id: 'go/settings/project/stores', text: intl.formatMessage(messages.openProjectSettingsStoresTab), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/project/stores`, }, }, ].filter(nonNullable), }, hasSomePermissions( [permissions.ViewProductTypes], applicationContext.permissions ) && { id: 'go/settings/product-types', text: intl.formatMessage(messages.openProductTypesSettings), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/product-types`, }, }, hasSomePermissions( [permissions.ViewDeveloperSettings], applicationContext.permissions ) && { id: 'go/settings/developer', text: intl.formatMessage(messages.openDeveloperSettings), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/developer`, }, subCommands: [ hasSomePermissions( [permissions.ViewDeveloperSettings], applicationContext.permissions ) && { id: 'go/settings/developer/api-clients/list', text: intl.formatMessage(messages.openApiClientsList), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/developer/api-clients`, }, }, hasSomePermissions( [permissions.ManageDeveloperSettings], applicationContext.permissions ) && { id: 'go/settings/developer/api-clients/add', text: intl.formatMessage(messages.openAddApiClient), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/developer/api-clients/new`, }, }, ].filter(nonNullable), }, featureToggles.customApplications && hasSomePermissions( [permissions.ManageProjectSettings], applicationContext.permissions ) && { id: 'go/settings/custom-applications', text: intl.formatMessage(messages.openCustomApplicationsSettings), action: { type: actionTypes.go, to: `/${applicationContext.project.key}/settings/custom-applications`, }, }, ].filter(nonNullable), }, applicationContext.project && applicationContext.project.languages && applicationContext.project.languages.length > 1 && { id: 'action/set-resource-language', text: intl.formatMessage(messages.setResourceLanguage), keywords: [ 'set resource locale', 'set project data language', 'set project data locale', ], action: () => void 0, // We would know these statically, but we define them here as we don't // want to include them in the top-level search results subCommands: () => Promise.resolve( (applicationContext.project ? applicationContext.project.languages : [] ) .map( (language) => changeProjectDataLocale && { id: `action/set-resource-language/${language}`, text: oneLineTrim` ${language} ${ language === applicationContext.dataLocale ? ' (active)' : '' } `, action: () => { changeProjectDataLocale(language); // We reload, since ProjectDataLocale is written in a way where // only the tree under the parent container reloads, but // not all of them reload. // So this action would seem like it had not effect, unless we // reload location.reload(); }, } ) .filter(nonNullable) ), }, { id: 'go/support', text: intl.formatMessage(messages.openSupport), keywords: ['Go to support'], action: { type: actionTypes.go, to: SUPPORT_PORTAL_URL, }, }, { id: 'go/account-profile', text: intl.formatMessage(messages.openMyProfile), keywords: ['Go to user account', 'Go to profile', 'Open profile'], action: { type: actionTypes.go, to: `/account/profile` }, }, { id: 'go/privacy-policy', text: intl.formatMessage(messages.showPrivacyPolicy), keywords: ['Open Privacy Policy'], action: { type: actionTypes.go, to: 'https://commercetools.com/privacy#suppliers', }, }, { id: 'go/logout', text: intl.formatMessage(messages.logout), keywords: ['Sign out'], action: { type: actionTypes.go, to: `/logout?reason=${LOGOUT_REASONS.USER}`, }, }, { id: 'go/manage-projects', text: intl.formatMessage(messages.openManageProjects), keywords: [ 'Go to manage projects', 'Go to projects', 'Open projects list', ], action: { type: actionTypes.go, to: `/account/projects` }, }, { id: 'go/manage-organizations', text: intl.formatMessage(messages.openManageOrganizations), keywords: [ 'Go to manage organizations', 'Go to organizations', 'Open organizations list', ], action: { type: actionTypes.go, to: `/account/organizations` }, }, ...(applicationContext.user ? applicationContext.user.projects.results.map((userProject) => ({ id: `go/project(${userProject.key})`, text: intl.formatMessage(messages.useProject, { projectName: userProject.name, }), keywords: [userProject.key], action: () => { // Switching projects needs a full redirect so that // the feature flags are reloaded (and things caches get destroyed) window.location.href = `/${userProject.key}`; }, })) : []), ].filter(nonNullable); }; export default createCommands;
the_stack
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; import { Location } from '@angular/common'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { ElectrsApiService } from '../../services/electrs-api.service'; import { switchMap, tap, debounceTime, catchError, map, shareReplay, startWith, pairwise } from 'rxjs/operators'; import { Transaction, Vout } from '../../interfaces/electrs.interface'; import { Observable, of, Subscription } from 'rxjs'; import { StateService } from '../../services/state.service'; import { SeoService } from 'src/app/services/seo.service'; import { WebsocketService } from 'src/app/services/websocket.service'; import { RelativeUrlPipe } from 'src/app/shared/pipes/relative-url/relative-url.pipe'; import { BlockExtended, TransactionStripped } from 'src/app/interfaces/node-api.interface'; import { ApiService } from 'src/app/services/api.service'; import { BlockOverviewGraphComponent } from 'src/app/components/block-overview-graph/block-overview-graph.component'; @Component({ selector: 'app-block', templateUrl: './block.component.html', styleUrls: ['./block.component.scss'] }) export class BlockComponent implements OnInit, OnDestroy { network = ''; block: BlockExtended; blockHeight: number; lastBlockHeight: number; nextBlockHeight: number; blockHash: string; isLoadingBlock = true; latestBlock: BlockExtended; latestBlocks: BlockExtended[] = []; transactions: Transaction[]; isLoadingTransactions = true; strippedTransactions: TransactionStripped[]; overviewTransitionDirection: string; isLoadingOverview = true; isAwaitingOverview = true; error: any; blockSubsidy: number; fees: number; paginationMaxSize: number; page = 1; itemsPerPage: number; txsLoadingStatus$: Observable<number>; showDetails = false; showPreviousBlocklink = true; showNextBlocklink = true; transactionsError: any = null; overviewError: any = null; webGlEnabled = true; transactionSubscription: Subscription; overviewSubscription: Subscription; keyNavigationSubscription: Subscription; blocksSubscription: Subscription; networkChangedSubscription: Subscription; queryParamsSubscription: Subscription; @ViewChild('blockGraph') blockGraph: BlockOverviewGraphComponent; constructor( private route: ActivatedRoute, private location: Location, private router: Router, private electrsApiService: ElectrsApiService, public stateService: StateService, private seoService: SeoService, private websocketService: WebsocketService, private relativeUrlPipe: RelativeUrlPipe, private apiService: ApiService ) { this.webGlEnabled = detectWebGL(); } ngOnInit() { this.websocketService.want(['blocks', 'mempool-blocks']); this.paginationMaxSize = window.matchMedia('(max-width: 670px)').matches ? 3 : 5; this.network = this.stateService.network; this.itemsPerPage = this.stateService.env.ITEMS_PER_PAGE; this.txsLoadingStatus$ = this.route.paramMap .pipe( switchMap(() => this.stateService.loadingIndicators$), map((indicators) => indicators['blocktxs-' + this.blockHash] !== undefined ? indicators['blocktxs-' + this.blockHash] : 0) ); this.blocksSubscription = this.stateService.blocks$ .subscribe(([block]) => { this.latestBlock = block; this.latestBlocks.unshift(block); this.latestBlocks = this.latestBlocks.slice(0, this.stateService.env.KEEP_BLOCKS_AMOUNT); this.setNextAndPreviousBlockLink(); if (block.id === this.blockHash) { this.block = block; if (block?.extras?.reward != undefined) { this.fees = block.extras.reward / 100000000 - this.blockSubsidy; } } }); const block$ = this.route.paramMap.pipe( switchMap((params: ParamMap) => { const blockHash: string = params.get('id') || ''; this.block = undefined; this.page = 1; this.error = undefined; this.fees = undefined; this.stateService.markBlock$.next({}); if (history.state.data && history.state.data.blockHeight) { this.blockHeight = history.state.data.blockHeight; } let isBlockHeight = false; if (/^[0-9]+$/.test(blockHash)) { isBlockHeight = true; } else { this.blockHash = blockHash; } document.body.scrollTo(0, 0); if (history.state.data && history.state.data.block) { this.blockHeight = history.state.data.block.height; return of(history.state.data.block); } else { this.isLoadingBlock = true; let blockInCache: BlockExtended; if (isBlockHeight) { blockInCache = this.latestBlocks.find((block) => block.height === parseInt(blockHash, 10)); if (blockInCache) { return of(blockInCache); } return this.electrsApiService.getBlockHashFromHeight$(parseInt(blockHash, 10)) .pipe( switchMap((hash) => { this.blockHash = hash; this.location.replaceState( this.router.createUrlTree([(this.network ? '/' + this.network : '') + '/block/', hash]).toString() ); return this.apiService.getBlock$(hash); }) ); } blockInCache = this.latestBlocks.find((block) => block.id === this.blockHash); if (blockInCache) { return of(blockInCache); } return this.apiService.getBlock$(blockHash); } }), tap((block: BlockExtended) => { this.block = block; this.blockHeight = block.height; const direction = (this.lastBlockHeight < this.blockHeight) ? 'right' : 'left'; this.lastBlockHeight = this.blockHeight; this.nextBlockHeight = block.height + 1; this.setNextAndPreviousBlockLink(); this.seoService.setTitle($localize`:@@block.component.browser-title:Block ${block.height}:BLOCK_HEIGHT:: ${block.id}:BLOCK_ID:`); this.isLoadingBlock = false; this.setBlockSubsidy(); if (block?.extras?.reward !== undefined) { this.fees = block.extras.reward / 100000000 - this.blockSubsidy; } this.stateService.markBlock$.next({ blockHeight: this.blockHeight }); this.isLoadingTransactions = true; this.transactions = null; this.transactionsError = null; this.isLoadingOverview = true; this.isAwaitingOverview = true; this.overviewError = true; if (this.blockGraph) { this.blockGraph.exit(direction); } }), debounceTime(300), shareReplay(1) ); this.transactionSubscription = block$.pipe( switchMap((block) => this.electrsApiService.getBlockTransactions$(block.id) .pipe( catchError((err) => { this.transactionsError = err; return of([]); })) ), ) .subscribe((transactions: Transaction[]) => { if (this.fees === undefined && transactions[0]) { this.fees = transactions[0].vout.reduce((acc: number, curr: Vout) => acc + curr.value, 0) / 100000000 - this.blockSubsidy; } this.transactions = transactions; this.isLoadingTransactions = false; if (!this.isAwaitingOverview && this.blockGraph && this.strippedTransactions && this.overviewTransitionDirection) { this.isLoadingOverview = false; this.blockGraph.replace(this.strippedTransactions, this.overviewTransitionDirection, false); } }, (error) => { this.error = error; this.isLoadingBlock = false; this.isLoadingOverview = false; }); this.overviewSubscription = block$.pipe( startWith(null), pairwise(), switchMap(([prevBlock, block]) => this.apiService.getStrippedBlockTransactions$(block.id) .pipe( catchError((err) => { this.overviewError = err; return of([]); }), switchMap((transactions) => { if (prevBlock) { return of({ transactions, direction: (prevBlock.height < block.height) ? 'right' : 'left' }); } else { return of({ transactions, direction: 'down' }); } }) ) ), ) .subscribe(({transactions, direction}: {transactions: TransactionStripped[], direction: string}) => { this.isAwaitingOverview = false; this.strippedTransactions = transactions; this.overviewTransitionDirection = direction; if (!this.isLoadingTransactions && this.blockGraph) { this.isLoadingOverview = false; this.blockGraph.replace(this.strippedTransactions, this.overviewTransitionDirection, false); } }, (error) => { this.error = error; this.isLoadingOverview = false; this.isAwaitingOverview = false; }); this.networkChangedSubscription = this.stateService.networkChanged$ .subscribe((network) => this.network = network); this.queryParamsSubscription = this.route.queryParams.subscribe((params) => { if (params.showDetails === 'true') { this.showDetails = true; } else { this.showDetails = false; } }); this.keyNavigationSubscription = this.stateService.keyNavigation$.subscribe((event) => { if (this.showPreviousBlocklink && event.key === 'ArrowRight' && this.nextBlockHeight - 2 >= 0) { this.navigateToPreviousBlock(); } if (event.key === 'ArrowLeft') { if (this.showNextBlocklink) { this.navigateToNextBlock(); } else { this.router.navigate([this.relativeUrlPipe.transform('/mempool-block'), '0']); } } }); } ngOnDestroy() { this.stateService.markBlock$.next({}); this.transactionSubscription.unsubscribe(); this.overviewSubscription.unsubscribe(); this.keyNavigationSubscription.unsubscribe(); this.blocksSubscription.unsubscribe(); this.networkChangedSubscription.unsubscribe(); this.queryParamsSubscription.unsubscribe(); } // TODO - Refactor this.fees/this.reward for liquid because it is not // used anymore on Bitcoin networks (we use block.extras directly) setBlockSubsidy() { this.blockSubsidy = 0; } pageChange(page: number, target: HTMLElement) { const start = (page - 1) * this.itemsPerPage; this.isLoadingTransactions = true; this.transactions = null; this.transactionsError = null; target.scrollIntoView(); // works for chrome this.electrsApiService.getBlockTransactions$(this.block.id, start) .pipe( catchError((err) => { this.transactionsError = err; return of([]); }) ) .subscribe((transactions) => { this.transactions = transactions; this.isLoadingTransactions = false; target.scrollIntoView(); // works for firefox }); } toggleShowDetails() { if (this.showDetails) { this.showDetails = false; this.router.navigate([], { relativeTo: this.route, queryParams: { showDetails: false }, queryParamsHandling: 'merge', fragment: 'block' }); } else { this.showDetails = true; this.router.navigate([], { relativeTo: this.route, queryParams: { showDetails: true }, queryParamsHandling: 'merge', fragment: 'details' }); } } hasTaproot(version: number): boolean { const versionBit = 2; // Taproot return (Number(version) & (1 << versionBit)) === (1 << versionBit); } displayTaprootStatus(): boolean { if (this.stateService.network !== '') { return false; } return this.block && this.block.height > 681393 && (new Date().getTime() / 1000) < 1628640000; } onResize(event: any) { this.paginationMaxSize = event.target.innerWidth < 670 ? 3 : 5; } navigateToPreviousBlock() { if (!this.block) { return; } const block = this.latestBlocks.find((b) => b.height === this.nextBlockHeight - 2); this.router.navigate([this.relativeUrlPipe.transform('/block/'), block ? block.id : this.block.previousblockhash], { state: { data: { block, blockHeight: this.nextBlockHeight - 2 } } }); } navigateToNextBlock() { const block = this.latestBlocks.find((b) => b.height === this.nextBlockHeight); this.router.navigate([this.relativeUrlPipe.transform('/block/'), block ? block.id : this.nextBlockHeight], { state: { data: { block, blockHeight: this.nextBlockHeight } } }); } setNextAndPreviousBlockLink(){ if (this.latestBlock && this.blockHeight) { if (this.blockHeight === 0){ this.showPreviousBlocklink = false; } else { this.showPreviousBlocklink = true; } if (this.latestBlock.height && this.latestBlock.height === this.blockHeight) { this.showNextBlocklink = false; } else { this.showNextBlocklink = true; } } } onTxClick(event: TransactionStripped): void { const url = new RelativeUrlPipe(this.stateService).transform(`/tx/${event.txid}`); this.router.navigate([url]); } } function detectWebGL() { const canvas = document.createElement('canvas'); const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl'); return (gl && gl instanceof WebGLRenderingContext); }
the_stack
import { test, assert } from '../../utils/assert' import { ethers } from 'ethers' import { TypedDataDomain, TypedDataField } from '@ethersproject/abstract-signer' import { Wallet, DefaultProviderConfig } from '@0xsequence/provider' import { WalletContext } from '@0xsequence/network' import { testAccounts, getEOAWallet, testWalletContext, sendETH } from '../testutils' import { Transaction, TransactionRequest } from '@0xsequence/transactions' import { configureLogger } from '@0xsequence/utils' configureLogger({ logLevel: 'DEBUG' }) export const tests = async () => { // // Deploy Sequence WalletContext (deterministic). We skip deployment // as we rely on mock-wallet to deploy it. // const deployedWalletContext = testWalletContext console.log('walletContext:', deployedWalletContext) // // Setup // const providerConfig = { ...DefaultProviderConfig } providerConfig.walletAppURL = 'http://localhost:9999/mock-wallet/mock-wallet.test.html' providerConfig.networks = [{ name: 'hardhat', rpcUrl: 'http://0.0.0.0:8545' }] const wallet = new Wallet('hardhat', providerConfig) // provider + signer, by default if a chainId is not specified it will direct // requests to the defaultChain const provider = wallet.getProvider() const signer = wallet.getSigner() // clear it in case we're testing in browser session wallet.disconnect() await test('is disconnected / logged out', async () => { assert.false(wallet.isConnected(), 'is connected') }) await test('is closed', async () => { assert.false(wallet.isOpened(), 'is closed') }) await test('is disconnected', async () => { assert.false(wallet.isConnected(), 'is disconnnected') }) await test('connect', async () => { const { connected } = await wallet.connect({ keepWalletOpened: true }) assert.true(connected, 'is connected') }) await test('isOpened', async () => { assert.true(wallet.isOpened(), 'is opened') }) await test('isConnected', async () => { assert.true(wallet.isConnected(), 'is connected') }) let walletContext: WalletContext await test('getWalletContext', async () => { walletContext = await wallet.getWalletContext() assert.equal(walletContext.factory, deployedWalletContext.factory, 'wallet context factory') assert.equal(walletContext.guestModule, deployedWalletContext.guestModule, 'wallet context guestModule') }) await test('getChainId', async () => { const chainId = await wallet.getChainId() assert.equal(chainId, 31337, 'chainId is correct') }) await test('networks', async () => { const networks = await wallet.getNetworks() assert.equal(networks.length, 2, '2 networks') assert.true(networks[0].isDefaultChain, '1st network is DefaultChain') assert.true(!networks[0].isAuthChain, '1st network is not AuthChain') assert.true(!networks[1].isDefaultChain, '1st network is not DefaultChain') assert.true(networks[1].isAuthChain, '2nd network is AuthChain') assert.true(networks[1].chainId === 31338, 'authChainId is correct') const authNetwork = await wallet.getAuthNetwork() assert.equal(networks[1].chainId, authNetwork.chainId, 'authNetwork matches chainId') const authProvider = wallet.getProvider(authNetwork) assert.equal(await authProvider.getChainId(), 31338, 'authProvider chainId is 31338') assert.equal(await provider.getChainId(), 31337, 'provider chainId is 31337') }) await test('getAccounts', async () => { const address = await wallet.getAddress() assert.equal(address, ethers.utils.getAddress('0xa91Ab3C5390A408DDB4a322510A4290363efcEE9'), 'wallet address is correct') }) await test('getWalletConfig', async () => { const allWalletConfigs = await wallet.getWalletConfig() assert.equal(allWalletConfigs.length, 2, '2 wallet configs (one for each chain)') const config1 = allWalletConfigs[0] assert.true(config1.chainId !== undefined, 'config1, chainId is set') assert.true(config1.threshold === 1, 'config1, 1 threshold') assert.true(config1.signers.length === 1, 'config1, 1 signer') assert.true(config1.signers[0].address === '0x4e37E14f5d5AAC4DF1151C6E8DF78B7541680853', 'config1, signer address') assert.true(config1.signers[0].weight === 1, 'config1, signer weight') const config2 = allWalletConfigs[0] assert.true(config2.chainId !== undefined, 'config2, chainId is set') assert.true(config2.threshold === 1, 'config2, 1 threshold') assert.true(config2.signers.length === 1, 'config2, 1 signer') assert.true(config2.signers[0].address === '0x4e37E14f5d5AAC4DF1151C6E8DF78B7541680853', 'config2, signer address') assert.true(config2.signers[0].weight === 1, 'config2, signer weight') }) await test('getWalletState', async () => { const allWalletStates = await signer.getWalletState() assert.equal(allWalletStates.length, 2, '2 wallet states (one for each chain)') // we expect network order to be [defaultChain, authChain, ..], so chain 31337 will be at index 0 const state1 = allWalletStates[0] assert.true(state1.chainId === 31337, 'state1, chainId is 31337') assert.true(state1.config.threshold === 1, 'state1, threshold') assert.true(state1.config.signers.length === 1, 'state1, 1 signer') assert.true(state1.address === await wallet.getAddress(), 'state1, address') // assert.true(state1.deployed, 'state1, deployed') // assert.true(state1.publishedLatest, 'state1, publishedLatest') }) await test('multiple networks', async () => { // chainId 31337 { assert.equal(await provider.getChainId(), 31337, 'provider chainId is 31337') const network = await provider.getNetwork() assert.equal(network.chainId, 31337, 'chain id match') const netVersion = await provider.send('net_version', []) assert.equal(netVersion, '31337', 'net_version check') const chainId = await provider.send('eth_chainId', []) assert.equal(chainId, '0x7a69', 'eth_chainId check') const chainId2 = await signer.getChainId() assert.equal(chainId2, 31337, 'chainId check') } // chainId 31338 { const provider2 = await wallet.getProvider(31338) assert.equal(await provider2.getChainId(), 31338, '2nd chain, chainId is 31338') const network = await provider2.getNetwork() assert.equal(network.chainId, 31338, '2nd chain, chain id match') const netVersion = await provider2.send('net_version', []) assert.equal(netVersion, '31338', '2nd chain, net_version check') const chainId = await provider2.send('eth_chainId', []) assert.equal(chainId, '0x7a6a', '2nd chain, eth_chainId check') const chainId2 = await (await provider2).getSigner().getChainId() assert.equal(chainId2, 31338, '2nd chain, chainId check') } }) await test('getSigners', async () => { const signers = await signer.getSigners() assert.true(signers.length === 1, 'signers, single owner') assert.true(signers[0] === '0x4e37E14f5d5AAC4DF1151C6E8DF78B7541680853', 'signers, check address') }) await test('signMessage on defaultChain', async () => { const address = await wallet.getAddress() const chainId = await wallet.getChainId() const message = 'hihi' const message2 = ethers.utils.toUtf8Bytes('hihi') // Sign the message const sigs = await Promise.all([message, message2].map(async m => { // NOTE: below line is equivalent to `signer.signMessage(m)` call // const sig = await wallet.commands.signMessage(m) const sig = await signer.signMessage(m) assert.equal( sig, '0x0001000148ac663d58ddee141c0bc98f95d2d3017a5328017e3792a8c431186c66669649369aac41bd649cda1708a5af53d5477fa64106faaed4755cf516e559c0bcf51b1c02', 'signature match' ) return sig })) const sig = sigs[0] // Verify the signature const isValid = await wallet.commands.isValidMessageSignature(address, message, sig, chainId) assert.true(isValid, 'signature is valid') // Recover the address / config from the signature const walletConfig = await wallet.commands.recoverWalletConfigFromMessage(address, message, sig, chainId) assert.true(walletConfig.address === address, 'recover address') const singleSignerAddress = '0x4e37E14f5d5AAC4DF1151C6E8DF78B7541680853' // expected from mock-wallet owner assert.true(singleSignerAddress === walletConfig.signers[0].address, 'owner address check') }) await test('signTypedData on defaultChain', async () => { const address = await wallet.getAddress() const chainId = await wallet.getChainId() const domain: TypedDataDomain = { name: 'Ether Mail', version: '1', chainId: chainId, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC' } const types: {[key: string] : TypedDataField[]} = { 'Person': [ {name: "name", type: "string"}, {name: "wallet", type: "address"} ] } const message = { 'name': 'Bob', 'wallet': '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB' } const sig = await signer.signTypedData(domain, types, message) assert.equal( sig, '0x00010001c25b59035ea662350e08f41b5087fc49a98b94936826b61a226f97e400c6ce290b8dfa09e3b0df82288fbc599d5b1a023a864bbd876bc67ec1f94c5f2fc4e6101b02', 'signature match typed-data' ) // Verify typed data const isValid = await wallet.commands.isValidTypedDataSignature(address, { domain, types, message }, sig, chainId) assert.true(isValid, 'signature is valid') // Recover config / address const walletConfig = await wallet.commands.recoverWalletConfigFromTypedData(address, { domain, types, message }, sig, chainId) assert.true(walletConfig.address === address, 'recover address') const singleSignerAddress = '0x4e37E14f5d5AAC4DF1151C6E8DF78B7541680853' // expected from mock-wallet owner assert.true(singleSignerAddress === walletConfig.signers[0].address, 'owner address check') }) await test('signAuthMessage', async () => { // NOTE: by definition, signAuthMessage will always be directed at the authChain network const authNetwork = await wallet.getAuthNetwork() const address = await wallet.getAddress() const chainId = authNetwork.chainId const authProvider = wallet.getProvider(authNetwork) assert.equal(chainId, 31338, 'chainId is 31338 (authChain)') assert.equal(await authProvider.getChainId(), 31338, 'authProvider chainId is 31338') assert.equal(await authProvider.getChainId(), await authProvider.getSigner().getChainId(), 'authProvider signer chainId is 31338') // Sign the message const message = 'hihi' const sig = await signer.signMessage(message, chainId) assert.equal( sig, '0x000100013fd9888b53c7d78755ed5304178a49c18eb15d438c85a5feabedba6eb634901b35c9184821aabbd1bb41be58f13469bc1c6eb21f7cc8f8639cbca9e2e53f78891c02', 'signAuthMessage, signature match' ) // confirm that authSigner, the chain-bound provider, derived from the authProvider returns the same signature const authSigner = authProvider.getSigner() const sigChk = await authSigner.signMessage(message, chainId) assert.equal(sigChk, sig, 'authSigner.signMessage returns the same sig') const sigChk2 = await wallet.commands.signAuthMessage(message) assert.equal(sigChk2, sig, 'wallet.commands.signAuthMessage returns the same sig') // Verify the signature const isValid = await wallet.commands.isValidMessageSignature(address, message, sig, chainId) assert.true(isValid, 'signAuthMessage, signature is valid') // Recover the address / config from the signature const walletConfig = await wallet.commands.recoverWalletConfigFromMessage(address, message, sig, chainId) assert.true(walletConfig.address === address, 'recover address') const singleSignerAddress = '0x4e37E14f5d5AAC4DF1151C6E8DF78B7541680853' // expected from mock-wallet owner assert.true(singleSignerAddress === walletConfig.signers[0].address, 'owner address check') }) await test('getBalance', async () => { // technically, the mock-wallet's single signer owner has some ETH.. const balanceSigner1 = await provider.getBalance('0x4e37E14f5d5AAC4DF1151C6E8DF78B7541680853') assert.true(balanceSigner1.gt(ethers.BigNumber.from(0)), 'signer1 balance > 0') }) await test('fund sequence wallet', async () => { // fund Sequence wallet with some ETH from test seed account const testAccount = getEOAWallet(testAccounts[0].privateKey) const walletBalanceBefore = await signer.getBalance() const ethAmount = ethers.utils.parseEther('10.1234') const txResp = await sendETH(testAccount, await wallet.getAddress(), ethAmount) const txReceipt = await provider.getTransactionReceipt(txResp.hash) assert.true(txReceipt.status === 1, 'eth sent from signer1') const walletBalanceAfter = await signer.getBalance() assert.true(walletBalanceAfter.sub(walletBalanceBefore).eq(ethAmount), `wallet received ${ethAmount} eth`) }) const testSendETH = async (title: string, opts: { gasLimit?: string } = {}) => test(title, async () => { // sequence wallet to now send some eth back to another seed account // via the relayer { const walletAddress = wallet.getAddress() const walletBalanceBefore = await signer.getBalance() // send eth from sequence smart wallet to another test account const toAddress = testAccounts[1].address const toBalanceBefore = await provider.getBalance(toAddress) const ethAmount = ethers.utils.parseEther('1.4242') // NOTE: when a wallet is undeployed (counter-factual), and although the txn contents are to send from our // sequence wallet to the test account, the transaction by the Sequence Wallet instance will be sent `to` the // `GuestModule` smart contract address of the Sequence context `from` the Sequence Relayer (local) account. // // However, when a wallet is deployed on-chain, and the txn object is to send from our sequence wallet to the // test account, the transaction will be sent `to` the smart wallet contract address of the sender by // the relayer. The transaction will then be delegated through the Smart Wallet and transfer will occur // as an internal transaction on-chain. // // Also note, the gasLimit and gasPrice can be estimated by the relayer, or optionally may be specified. //-- // Record wallet deployed state before, so we can check the receipt.to below. We have to do this // because a wallet will automatically get bundled for deployment when it sends a transaction. const beforeWalletDeployed = await wallet.isDeployed() // NOTE/TODO: gasPrice even if set will be set again by the LocalRelayer, we should allow it to be overridden const tx: TransactionRequest = { from: await walletAddress, to: toAddress, value: ethAmount, } // specifying gasLimit manually if (opts.gasLimit) { tx.gasLimit = opts.gasLimit } const txResp = await signer.sendTransaction(tx) const txReceipt = await txResp.wait() assert.true(txReceipt.status === 1, 'txn sent successfully') assert.true(await signer.isDeployed(), 'wallet must be in deployed state after the txn') // transaction is sent to the deployed wallet, if the wallet is deployed.. otherwise its sent to guestModule if (beforeWalletDeployed) { assert.equal(txReceipt.to, await wallet.getAddress(), 'recipient is correct') } else { assert.equal(txReceipt.to, walletContext.guestModule, 'recipient is correct') } // Ensure fromAddress sent their eth const walletBalanceAfter = await signer.getBalance() assert.true(walletBalanceAfter.sub(walletBalanceBefore).mul(-1).eq(ethAmount), `wallet sent ${ethAmount} eth`) // Ensure toAddress received their eth const toBalanceAfter = await provider.getBalance(toAddress) assert.true(toBalanceAfter.sub(toBalanceBefore).eq(ethAmount), `toAddress received ${ethAmount} eth`) // Extra checks if (opts.gasLimit) { // In our test, we are passing a high gas limit for an internal transaction, so overall // transaction must be higher than this value if it used our value correctly assert.true(txResp.gasLimit.gte(opts.gasLimit), 'sendETH, using higher gasLimit') } } }) await testSendETH('sendETH (defaultChain)') // NOTE: this will pass, as we set the gasLimit low on the txn, but the LocalRelayer will re-estimate // the entire transaction to have it pass. await testSendETH('sendETH with high gasLimit override (defaultChain)', { gasLimit: '0x55555' }) await test('sendTransaction batch', async () => { const testAccount = getEOAWallet(testAccounts[1].privateKey) const ethAmount1 = ethers.utils.parseEther('1.234') const ethAmount2 = ethers.utils.parseEther('0.456') const tx1: TransactionRequest = { to: testAccount.address, value: ethAmount1, data: '0x' } const tx2: TransactionRequest = { to: testAccount.address, value: ethAmount2, data: '0x' } const txBatched = { ...tx1, auxiliary: [tx2] } const toBalanceBefore = await provider.getBalance(testAccount.address) const txnResp = await signer.sendTransaction(txBatched) await txnResp.wait() const toBalanceAfter = await provider.getBalance(testAccount.address) assert.true(toBalanceAfter.sub(toBalanceBefore).mul(1).eq(ethAmount1.add(ethAmount2)), `wallet sent ${ethAmount1} + ${ethAmount2} eth`) }) await test('sendTransaction batch format 2', async () => { const testAccount = getEOAWallet(testAccounts[1].privateKey) const ethAmount1 = ethers.utils.parseEther('1.234') const ethAmount2 = ethers.utils.parseEther('0.456') const tx1: TransactionRequest = { to: testAccount.address, value: ethAmount1, data: '0x' } const tx2: TransactionRequest = { to: testAccount.address, value: ethAmount2, data: '0x' } const toBalanceBefore = await provider.getBalance(testAccount.address) const txnResp = await signer.sendTransactionBatch([tx1, tx2]) await txnResp.wait() const toBalanceAfter = await provider.getBalance(testAccount.address) assert.true(toBalanceAfter.sub(toBalanceBefore).mul(1).eq(ethAmount1.add(ethAmount2)), `wallet sent ${ethAmount1} + ${ethAmount2} eth`) }) await test('sendTransaction batch format 3', async () => { const testAccount = getEOAWallet(testAccounts[1].privateKey) const ethAmount1 = ethers.utils.parseEther('1.234') const ethAmount2 = ethers.utils.parseEther('0.456') const tx1: Transaction = { delegateCall: false, revertOnError: false, gasLimit: '0x55555', to: testAccount.address, value: ethAmount1, data: '0x' } const tx2: Transaction = { delegateCall: false, revertOnError: false, gasLimit: '0x55555', to: testAccount.address, value: ethAmount2, data: '0x' } const toBalanceBefore = await provider.getBalance(testAccount.address) const txnResp = await signer.sendTransactionBatch([tx1, tx2]) await txnResp.wait() const toBalanceAfter = await provider.getBalance(testAccount.address) assert.true(toBalanceAfter.sub(toBalanceBefore).mul(1).eq(ethAmount1.add(ethAmount2)), `wallet sent ${ethAmount1} + ${ethAmount2} eth`) }) await test('should reject a transaction response on sendTransactionBatch (at runtime)', async () => { const testAccount = getEOAWallet(testAccounts[1].privateKey) const transactionResponse = await testAccount.sendTransaction({ to: ethers.Wallet.createRandom().address }) as any const txnResp = signer.sendTransactionBatch([transactionResponse]) await assert.rejected(txnResp) }) await test('sendETH from the sequence smart wallet (authChain)', async () => { // multi-chain to send eth on an alternative chain, in this case the authChain // // NOTE: the account addresses are both chains have been seeded with the same private key // so we can have overlapping addresses and keys for ease of use duringtesting // get provider of the 2nd chain (the authChain) const provider2 = wallet.getProvider('hardhat2') assert.equal(await provider2.getChainId(), 31338, 'provider is the 2nd chain') assert.equal(await provider2.getChainId(), await wallet.getProvider(31338).getChainId(), 'provider2 code path check') const authProvider = await wallet.getAuthProvider() assert.equal(await provider2.getChainId(), await authProvider.getChainId(), 'provider2 === authProvider') const signer2 = provider2.getSigner() // confirm all account addresses are the same and correct { assert.equal(await wallet.getAddress(), await signer.getAddress(), 'wallet and signer address match') assert.equal(await wallet.getAddress(), await signer2.getAddress(), 'wallet and signer2 address match') assert.true(await wallet.getAddress() !== testAccounts[0].address, 'wallet is not subkey address') } // initial balances { const testAccount = getEOAWallet(testAccounts[0].privateKey, provider2) const walletBalanceBefore = await testAccount.getBalance() const mainTestAccount = getEOAWallet(testAccounts[0].privateKey, wallet.getProvider()) const mainWalletBalanceBefore = await mainTestAccount.getBalance() assert.true(walletBalanceBefore.toString() !== mainWalletBalanceBefore.toString(), 'balances across networks do not match') // test different code paths lead to same results assert.equal( (await provider2.getBalance(await testAccount.getAddress())).toString(), (await testAccount.getBalance()).toString(), 'balance match 1' ) assert.equal( (await provider.getBalance(await mainTestAccount.getAddress())).toString(), (await mainTestAccount.getBalance()).toString(), 'balance match 2' ) } // first, lets move some ETH info the wallet from teh testnet seed account { const testAccount = getEOAWallet(testAccounts[0].privateKey, provider2) const walletBalanceBefore = await signer2.getBalance() const ethAmount = ethers.utils.parseEther('4.2') // const txResp = await sendETH(testAccount, await wallet.getAddress(), ethAmount) // const txReceipt = await provider2.getTransactionReceipt(txResp.hash) const txReceipt = await (await sendETH(testAccount, await wallet.getAddress(), ethAmount)).wait() assert.true(txReceipt.status === 1, 'eth sent') const walletBalanceAfter = await signer2.getBalance() assert.true(walletBalanceAfter.sub(walletBalanceBefore).eq(ethAmount), `wallet received ${ethAmount} eth`) } // using sequence wallet on the authChain, send eth back to anotehr seed account via // the authChain relayer { const walletAddress = wallet.getAddress() const walletBalanceBefore = await signer2.getBalance() // send eth from sequence smart wallet to another test account const toAddress = testAccounts[1].address const toBalanceBefore = await provider2.getBalance(toAddress) const ethAmount = ethers.utils.parseEther('1.1234') const tx = { from: walletAddress, to: toAddress, value: ethAmount, } const txReceipt = await (await signer2.sendTransaction(tx)).wait() assert.true(txReceipt.status === 1, 'txn sent successfully') assert.true(await signer2.isDeployed(), 'wallet must be in deployed state after the txn') // Ensure fromAddress sent their eth const walletBalanceAfter = await signer2.getBalance() assert.true(walletBalanceAfter.sub(walletBalanceBefore).mul(-1).eq(ethAmount), `wallet sent ${ethAmount} eth`) // Ensure toAddress received their eth const toBalanceAfter = await provider2.getBalance(toAddress) assert.true(toBalanceAfter.sub(toBalanceBefore).eq(ethAmount), `toAddress received ${ethAmount} eth`) } }) } // TODO: send coins // TODO: send collectible // TODO: setup some failure states..? hmm, might be trickier, but maybe could have requestHandler do some faults/other.. // TODO: add auth helpers to @0xsequence/auth, and heplers in "commands" // //-------- // // import { sequence} from '@0xsequence' // const wallet = new sequence.Wallet() // wallet.login() // wallet.sendETH() // wallet.signMessage() // wallet.sendTransaction(...) // const tokens = new sequence.Tokens() // tokens.mintCoin(xx) // tokens.mintCollectible() // wallet.sendTransaction(tokens.mintCoin(xx)) // wallet.sendTransaction(tokens.mintCollectible(xx))
the_stack
import * as cosmiconfig from "cosmiconfig"; import * as fs from "fs"; import * as http from "http"; import * as https from "https"; import * as mkdirp from "mkdirp"; import * as nock from "nock"; import * as path from "path"; import * as zlib from "zlib"; import * as URL from "url-parse"; import { log } from "./log"; import { Mode } from "./Mode"; const fnv1a = require("@sindresorhus/fnv1a"); const chalk = require("chalk"); const terminalLink = require("terminal-link"); // Cannot use `Symbol` here, since it's referentially different // between the dist/ & src/ versions. const IS_STUBBED = "IS_STUBBED"; const REQUEST_ARGUMENTS = new WeakMap(); interface Config { mode?: Mode; ignore?: Ignore; identify?: Identify; normalizer?: Normalizer; recordingsPath?: string; } interface Ignore { (request: NormalizedRequest): boolean; } interface Identify { (request: NormalizedRequest, response?: ResponseRecording): | undefined | string | [string, string]; } interface NormalizedRequest extends RequestRecording { url: URL; } // TODO Use { request, response, url } to avoid mudying the request interface Normalizer { (request: NormalizedRequest, response?: ResponseRecording): void; } enum Methods { DELETE = "DELETE", GET = "GET", HEAD = "HEAD", MERGE = "MERGE", OPTIONS = "OPTIONS", PATCH = "PATCH", POST = "POST", PUT = "PUT" } // A more relaxed version of http.ReuestOptions interface RequestOptions extends http.RequestOptions { href?: string; proto?: string; } interface RequestRecording { method: Methods; href: string; headers: http.IncomingHttpHeaders; body: string; } interface ResponseRecording { statusCode: number; headers: http.IncomingHttpHeaders; body: object | string; } interface Recording { request: RequestRecording; response: ResponseRecording; } interface InterceptedRequest { body: string; headers: http.IncomingHttpHeaders; method: Methods; options: RequestOptions; req: http.ClientRequest; respond: nock.ReplyCallback; } const explorer = cosmiconfig("recorder", { searchPlaces: ["recorder.config.js"] }); const { NODE_ENV, // Default to REPLAY in CI, RECORD otherwise RECORDER = NODE_ENV === "test" ? Mode.REPLAY : Mode.RECORD } = process.env; // ! nock overrides http methods upon require. Restore to normal before starting. nock.restore(); export class Recorder { private ClientRequest = http.ClientRequest; private httpRequest = http.request; private httpsRequest = https.request; private identities = new Map(); private config: Config = { mode: RECORDER as Mode, recordingsPath: path.resolve(process.cwd(), "__recordings__") }; constructor() { // @ts-ignore if (this.ClientRequest[IS_STUBBED]) { // ! No need to log this, now that the fix is in place // log( // "Network requests are already intercepted, so there are multiple versions running!" // ); return; } const result = explorer.searchSync(); if (result && result.config) { this.configure(result.config as Config); } if (log.enabled) { log(this.getModeBanner()); } // ! This only happens when running src/Recorder.ts & dist/Recorder.js // if (process.env.RECORDER_ACTIVE) { // log( // "Already active, so there are multiple versions sharing this process." // ); // } this.setupNock(); this.patchNock(); process.env.RECORDER_ACTIVE = "true"; } bypass() { this.configure({ mode: Mode.BYPASS }); } async bypassRequest(interceptedRequest: InterceptedRequest) { const { respond } = interceptedRequest; const { body, headers, statusCode } = await this.makeRequest( interceptedRequest ); respond(null, [statusCode, body, headers]); } configure = (config: Config) => { Object.assign(this.config, config); }; getRecording = (interceptedRequest: InterceptedRequest): Recording => { const { request } = this.normalize(interceptedRequest) as Recording; const recordingPath = this.getRecordingPath(request); if (!fs.existsSync(recordingPath)) { throw new Error( `Missing recording ${this.getRecordingLink(recordingPath)}` ); } const recording = JSON.parse(fs.readFileSync(recordingPath, "utf8")); return recording; }; getRecordingLink(recordingPath: string): string { const relativePath = recordingPath.replace(process.cwd(), "").slice(1); return terminalLink(relativePath, `vscode://file/${recordingPath}`, { fallback: (text: string) => text }); } getRecordingPath(request: RequestRecording): string { const { href } = request; const url = new URL(href, true); const { hostname, pathname } = url; if (!hostname) { throw new Error( `Cannot parse hostname from recording's "href": ${JSON.stringify(href)}` ); } if (!pathname) { throw new Error( `Cannot parse pathname from recording's "href": ${JSON.stringify(href)}` ); } const hash = fnv1a(JSON.stringify(request)); const identity = this.identify(request); const filename = identity ? `${hash}-${identity}` : hash; const recordingPath = path.join( this.config.recordingsPath as string, hostname, pathname, `${filename}.json` ); return recordingPath; } getHrefFromOptions(options: RequestOptions) { if (options.href) { return options.href; } const protocol = options.protocol || `${options.proto}:` || "http:"; const host = options.hostname || options.host || "localhost"; const { path, port } = options; const url = new URL("", true); url.set("protocol", protocol); url.set("host", host); url.set("pathname", path); if ( port && !host.includes(":") && (port !== 80 || protocol !== "http:") && (port !== 443 || protocol !== "https:") ) { url.set("port", port); } return url.href; } getMode() { return this.config.mode; } getModeBanner() { const modeEnum = this.getModeEnum() as string; return [ "\n", chalk.bgWhite("".padStart(23)), chalk.bgWhite.hex("#3d4852")( ` ${chalk.red("•")} R e c ${chalk.hex("#44883E")("⬢ ")} r d e r ` ), chalk.bgWhite("".padStart(23)), chalk .keyword("orange") .bold.inverse(modeEnum.padStart((23 + modeEnum.length) / 2).padEnd(23)), "\n" ].join("\n"); } getModeEnum() { return Object.keys(Mode).find( (key) => Mode[key as keyof typeof Mode] === this.getMode() ); } handleRequest = (interceptedRequest: InterceptedRequest) => { let mode = this.getMode(); const { method, options } = interceptedRequest; const recordingPath = this.hasRecording(interceptedRequest); const href = this.getHrefFromOptions(options); const link = terminalLink(href, href, { fallback: (text: string) => text }); if (this.config.ignore) { const { request } = this.normalize(interceptedRequest); const url = new URL(request.href, true); if (this.config.ignore({ ...request, url })) { log(`Ignoring ${link}`); return this.bypassRequest(interceptedRequest); } } switch (mode) { case Mode.BYPASS: log(`Bypass ${method} ${href}`); return this.bypassRequest(interceptedRequest); case Mode.RECORD: if (recordingPath) { log(`Replaying ${this.getRecordingLink(recordingPath)}`); return this.replayRequest(interceptedRequest); } log(`Recording ${link}`); return this.recordRequest(interceptedRequest); case Mode.RERECORD: log(`Recording ${link}`); return this.recordRequest(interceptedRequest); case Mode.REPLAY: if (recordingPath) { log(`Replaying ${this.getRecordingLink(recordingPath)}`); } else { log(`Replaying ${link}`); } return this.replayRequest(interceptedRequest); default: throw new Error(`Mode.${mode} is not supported`); } }; handleResponse = ( interceptedRequest: InterceptedRequest, recording: Recording ) => { const { respond } = interceptedRequest; const { request, response } = recording; const { body, headers, statusCode } = response; this.identify(request, response); respond(null, [statusCode, body, headers]); }; hasRecording(interceptedRequest: InterceptedRequest): string | false { const { request } = this.normalize(interceptedRequest) as Recording; const recordingPath = this.getRecordingPath(request); return fs.existsSync(recordingPath) ? recordingPath : false; } identify(request: RequestRecording, response?: ResponseRecording) { const { identify } = this.config; if (!identify) { return; } const { href } = request; const url = new URL(href, true); const result = identify( { ...request, url }, response ); if (!result) { return; } if (Array.isArray(result)) { const [identity, token] = result; if (!token) { throw new Error(`Custom identifier returned ${JSON.stringify(result)}`); } this.identities.set(token, identity); return identity; } if (typeof result === "string") { const identity = this.identities.get(result); // Trust the provided identity, since it may not be a token if (!identity) { return result; } return identity; } throw new Error( 'identifier() should return ["identity", "token"] or "token"' ); } async makeRequest( interceptedRequest: InterceptedRequest ): Promise<ResponseRecording> { const { body, headers, method, options } = interceptedRequest; const request = (options.proto === "https" ? this.httpsRequest : this.httpRequest)({ ...options, method, headers }); const responsePromise = new Promise((resolve, reject) => { request.once("response", resolve); request.once("error", reject); request.once("timeout", reject); }); // Because we JSON.parse responses, we need to stringify it if (String(headers["content-type"]).includes("application/json")) { request.write(JSON.stringify(body)); } else { request.write(body); } request.end(); const response = (await responsePromise) as http.IncomingMessage; const responseBody = await new Promise((resolve, reject) => { const chunks: any[] = []; response.on("data", (chunk) => chunks.push(chunk)); response.once("end", () => { const { headers } = response; // GitHub sends compressed, chunked payloads if ( headers["content-encoding"] === "gzip" && headers["transfer-encoding"] === "chunked" ) { const decoded = Buffer.concat(chunks); const unzipped = zlib.gunzipSync(decoded).toString("utf8"); // TODO Is this the correct thing to do? delete headers["content-encoding"]; delete headers["transfer-encoding"]; try { const json = JSON.parse(unzipped); // TODO Is this safe to assume? headers["content-encoding"] = "application/json"; return resolve(json); } catch (error) { return resolve(unzipped); } return resolve(unzipped); } const body = Buffer.concat(chunks).toString("utf8"); // Simple services oftent send "application/json; charset=utf-8" if (String(headers["content-type"]).includes("application/json")) { try { return resolve(JSON.parse(body)); } catch (error) { console.warn(error); } } return resolve(body); }); response.once("error", reject); }); return { statusCode: response.statusCode as number, headers: response.headers, body: responseBody }; } normalize( interceptedRequest: InterceptedRequest, response?: ResponseRecording ) { // Poor-man's clone for immutability const headers = JSON.parse(JSON.stringify(interceptedRequest.headers)); const { body, method, options } = interceptedRequest; const href = this.getHrefFromOptions(options); const url = new URL(href, true); // fThis is redundant with `href`, so why should we keep it? delete headers.host; // Remove ephemeral ports from superagent testing // ! user-agent can be "..." or ["..."] if (String(headers["user-agent"]).includes("node-superagent")) { url.set("port", undefined); } const recording = { request: { method, href, headers, body, url }, response }; const { normalizer } = this.config; if (normalizer) { normalizer(recording.request, recording.response); } // Update href to match url object recording.request.href = recording.request.url.toString(); // Don't save parsed url delete recording.request.url; return recording; } record() { this.configure({ mode: Mode.RECORD }); } async recordRequest(request: InterceptedRequest) { const { respond } = request; const response = await this.makeRequest(request); const { statusCode, body, headers } = response; // Respond with *real* response for recording, not recording. respond(null, [statusCode, body, headers]); const recording = this.normalize(request, response) as Recording; this.identify(recording.request, recording.response); process.nextTick(() => this.saveRecording(recording)); } replay() { this.configure({ mode: Mode.REPLAY }); } async replayRequest(interceptedRequest: InterceptedRequest) { const { req } = interceptedRequest; try { const recording = await this.getRecording(interceptedRequest); this.identify(recording.request, recording.response); return this.handleResponse(interceptedRequest, recording); } catch (error) { req.emit("error", error); } } rerecord() { this.configure({ mode: Mode.RERECORD }); } patchNock() { // This is Nock's `OverriddenClientRequest` const { ClientRequest } = http; // @ts-ignore http.ClientRequest = function recordClientRequest( url: string | URL | http.ClientRequestArgs, cb?: (res: http.IncomingMessage) => void ) { const req = new ClientRequest(url, cb); REQUEST_ARGUMENTS.set(req, [url, cb]); return req; }; // We need a way to tell that we've already overridden nock. // @ts-ignore http.ClientRequest[IS_STUBBED] = true; } saveRecording(recording: Recording) { const recordingPath = this.getRecordingPath(recording.request); const serialized = JSON.stringify(recording, null, 2); mkdirp.sync(path.dirname(recordingPath)); fs.writeFileSync(recordingPath, serialized); } setupNock() { nock.restore(); nock.cleanAll(); const interceptor = nock(/.*/).persist(); const recorder = this; Object.keys(Methods).forEach((m) => { interceptor .intercept(/.*/, m) .reply(async function reply(uri, body, respond) { // @ts-ignore const { method, req } = this as any; const { headers } = req; const [options] = REQUEST_ARGUMENTS.get(req); const interceptedRequest: InterceptedRequest = { body, headers, method, options, req, respond: respond as nock.ReplyCallback }; recorder.handleRequest(interceptedRequest); }); }); nock.activate(); } }
the_stack
export interface ISummaryExpression { fieldName: string; customSummary?: any; } export interface IgxSummaryResult { key: string; label: string; summaryResult: any; } export interface ISummaryRecord { summaries: Map<string, IgxSummaryResult[]>; max?: number; cellIndentation?: number; } const clear = (el) => el === 0 || Boolean(el); const first = (arr) => arr[0]; const last = (arr) => arr[arr.length - 1]; export class IgxSummaryOperand { /** * Counts all the records in the data source. * If filtering is applied, counts only the filtered records. * ```typescript * IgxSummaryOperand.count(dataSource); * ``` * * @memberof IgxSummaryOperand */ public static count(data: any[]): number { return data.length; } /** * Executes the static `count` method and returns `IgxSummaryResult[]`. * ```typescript * interface IgxSummaryResult { * key: string; * label: string; * summaryResult: any; * } * ``` * Can be overridden in the inherited classes to provide customization for the `summary`. * ```typescript * class CustomSummary extends IgxSummaryOperand { * constructor() { * super(); * } * public operate(data: any[], allData: any[], fieldName: string): IgxSummaryResult[] { * const result = []; * result.push({ * key: "test", * label: "Test", * summaryResult: IgxSummaryOperand.count(data) * }); * return result; * } * } * this.grid.getColumnByName('ColumnName').summaries = CustomSummary; * ``` * * @memberof IgxSummaryOperand */ public operate(data: any[] = [], allData: any[] = [], fieldName?: string): IgxSummaryResult[] { return [{ key: 'count', label: 'Count', summaryResult: IgxSummaryOperand.count(data) }]; } } // @dynamic export class IgxNumberSummaryOperand extends IgxSummaryOperand { /** * Returns the minimum numeric value in the provided data records. * If filtering is applied, returns the minimum value in the filtered data records. * ```typescript * IgxNumberSummaryOperand.min(data); * ``` * * @memberof IgxNumberSummaryOperand */ public static min(data: any[]): number { return data.length && data.filter(clear).length ? data.filter(clear).reduce((a, b) => Math.min(a, b)) : 0; } /** * Returns the maximum numeric value in the provided data records. * If filtering is applied, returns the maximum value in the filtered data records. * ```typescript * IgxNumberSummaryOperand.max(data); * ``` * * @memberof IgxNumberSummaryOperand */ public static max(data: any[]): number { return data.length && data.filter(clear).length ? data.filter(clear).reduce((a, b) => Math.max(a, b)) : 0; } /** * Returns the sum of the numeric values in the provided data records. * If filtering is applied, returns the sum of the numeric values in the data records. * ```typescript * IgxNumberSummaryOperand.sum(data); * ``` * * @memberof IgxNumberSummaryOperand */ public static sum(data: any[]): number { return data.length && data.filter(clear).length ? data.filter(clear).reduce((a, b) => +a + +b) : 0; } /** * Returns the average numeric value in the data provided data records. * If filtering is applied, returns the average numeric value in the filtered data records. * ```typescript * IgxSummaryOperand.average(data); * ``` * * @memberof IgxNumberSummaryOperand */ public static average(data: any[]): number { return data.length && data.filter(clear).length ? this.sum(data) / this.count(data) : 0; } /** * Executes the static methods and returns `IgxSummaryResult[]`. * ```typescript * interface IgxSummaryResult { * key: string; * label: string; * summaryResult: any; * } * ``` * Can be overridden in the inherited classes to provide customization for the `summary`. * ```typescript * class CustomNumberSummary extends IgxNumberSummaryOperand { * constructor() { * super(); * } * public operate(data: any[], allData: any[], fieldName: string): IgxSummaryResult[] { * const result = super.operate(data, allData, fieldName); * result.push({ * key: "avg", * label: "Avg", * summaryResult: IgxNumberSummaryOperand.average(data) * }); * result.push({ * key: 'mdn', * label: 'Median', * summaryResult: this.findMedian(data) * }); * return result; * } * } * this.grid.getColumnByName('ColumnName').summaries = CustomNumberSummary; * ``` * * @memberof IgxNumberSummaryOperand */ public operate(data: any[] = [], allData: any[] = [], fieldName?: string): IgxSummaryResult[] { const result = super.operate(data, allData, fieldName); result.push({ key: 'min', label: 'Min', summaryResult: IgxNumberSummaryOperand.min(data) }); result.push({ key: 'max', label: 'Max', summaryResult: IgxNumberSummaryOperand.max(data) }); result.push({ key: 'sum', label: 'Sum', summaryResult: IgxNumberSummaryOperand.sum(data) }); result.push({ key: 'average', label: 'Avg', summaryResult: IgxNumberSummaryOperand.average(data) }); return result; } } // @dynamic export class IgxDateSummaryOperand extends IgxSummaryOperand { /** * Returns the latest date value in the data records. * If filtering is applied, returns the latest date value in the filtered data records. * ```typescript * IgxDateSummaryOperand.latest(data); * ``` * * @memberof IgxDateSummaryOperand */ public static latest(data: any[]) { return data.length && data.filter(clear).length ? first(data.filter(clear).sort((a, b) => new Date(b).valueOf() - new Date(a).valueOf())) : undefined; } /** * Returns the earliest date value in the data records. * If filtering is applied, returns the latest date value in the filtered data records. * ```typescript * IgxDateSummaryOperand.earliest(data); * ``` * * @memberof IgxDateSummaryOperand */ public static earliest(data: any[]) { return data.length && data.filter(clear).length ? last(data.filter(clear).sort((a, b) => new Date(b).valueOf() - new Date(a).valueOf())) : undefined; } /** * Executes the static methods and returns `IgxSummaryResult[]`. * ```typescript * interface IgxSummaryResult { * key: string; * label: string; * summaryResult: any; * } * ``` * Can be overridden in the inherited classes to provide customization for the `summary`. * ```typescript * class CustomDateSummary extends IgxDateSummaryOperand { * constructor() { * super(); * } * public operate(data: any[], allData: any[], fieldName: string): IgxSummaryResult[] { * const result = super.operate(data, allData, fieldName); * result.push({ * key: "deadline", * label: "Deadline Date", * summaryResult: this.calculateDeadline(data); * }); * return result; * } * } * this.grid.getColumnByName('ColumnName').summaries = CustomDateSummary; * ``` * * @memberof IgxDateSummaryOperand */ public operate(data: any[] = [], allData: any[] = [], fieldName?: string): IgxSummaryResult[] { const result = super.operate(data, allData, fieldName); result.push({ key: 'earliest', label: 'Earliest', summaryResult: IgxDateSummaryOperand.earliest(data) }); result.push({ key: 'latest', label: 'Latest', summaryResult: IgxDateSummaryOperand.latest(data) }); return result; } } // @dynamic export class IgxTimeSummaryOperand extends IgxSummaryOperand { /** * Returns the latest time value in the data records. Compare only the time part of the date. * If filtering is applied, returns the latest time value in the filtered data records. * ```typescript * IgxTimeSummaryOperand.latestTime(data); * ``` * * @memberof IgxTimeSummaryOperand */ public static latestTime(data: any[]) { return data.length && data.filter(clear).length ? first(data.filter(clear).map(v => new Date(v)).sort((a, b) => new Date().setHours(b.getHours(), b.getMinutes(), b.getSeconds()) - new Date().setHours(a.getHours(), a.getMinutes(), a.getSeconds()))) : undefined; } /** * Returns the earliest time value in the data records. Compare only the time part of the date. * If filtering is applied, returns the earliest time value in the filtered data records. * ```typescript * IgxTimeSummaryOperand.earliestTime(data); * ``` * * @memberof IgxTimeSummaryOperand */ public static earliestTime(data: any[]) { return data.length && data.filter(clear).length ? last(data.filter(clear).map(v => new Date(v)).sort((a, b) => new Date().setHours(b.getHours(), b.getMinutes(), b.getSeconds()) - new Date().setHours(a.getHours(), a.getMinutes(), a.getSeconds()))) : undefined; } /** * @memberof IgxTimeSummaryOperand */ public operate(data: any[] = [], allData: any[] = [], fieldName?: string): IgxSummaryResult[] { const result = super.operate(data, allData, fieldName); result.push({ key: 'earliest', label: 'Earliest', summaryResult: IgxTimeSummaryOperand.earliestTime(data) }); result.push({ key: 'latest', label: 'Latest', summaryResult: IgxTimeSummaryOperand.latestTime(data) }); return result; } } export class IgxCurrencySummaryOperand extends IgxSummaryOperand { public operate(data: any[] = [], allData: any[] = [], fieldName?: string): IgxSummaryResult[] { const result = super.operate(data, allData, fieldName); result.push({ key: 'min', label: 'Min', summaryResult: IgxNumberSummaryOperand.min(data) }); result.push({ key: 'max', label: 'Max', summaryResult: IgxNumberSummaryOperand.max(data) }); result.push({ key: 'sum', label: 'Sum', summaryResult: IgxNumberSummaryOperand.sum(data) }); result.push({ key: 'average', label: 'Avg', summaryResult: IgxNumberSummaryOperand.average(data) }); return result; } } export class IgxPercentSummaryOperand extends IgxSummaryOperand { public operate(data: any[] = [], allData: any[] = [], fieldName?: string): IgxSummaryResult[] { const result = super.operate(data, allData, fieldName); result.push({ key: 'min', label: 'Min', summaryResult: IgxNumberSummaryOperand.min(data) }); result.push({ key: 'max', label: 'Max', summaryResult: IgxNumberSummaryOperand.max(data) }); result.push({ key: 'sum', label: 'Sum', summaryResult: IgxNumberSummaryOperand.sum(data) }); result.push({ key: 'average', label: 'Avg', summaryResult: IgxNumberSummaryOperand.average(data) }); return result; } }
the_stack
import _ from 'lodash'; import { FlowsenseToken, FlowsenseTokenCategory, FlowsenseCategorizedToken, QueryValue, FlowsenseDef, } from './types'; import * as util from './update/util'; import * as update from './update'; import * as utterance from './utterance'; import { OutputPort, InputPort } from '@/components/port'; import { SubsetNode } from '@/components/subset-node'; import { Node } from '@/components/node'; import { Visualization } from '@/components/visualization'; import FlowsenseUpdateTracker from '@/store/flowsense/update/tracker'; import { randomInt } from '@/common/util'; interface InjectedToken { marker: string; token: FlowsenseCategorizedToken; } interface MarkerMapping { [marker: string]: FlowsenseCategorizedToken; } interface InjectionMapping { dataset: { [token: string]: string; }; nodeLabel: { [token: string]: string; }; column: { [token: string]: string; }; nodeType: { [token: string]: string; }; } export interface InjectedQuery { query: string; rawQuery: string; tokens: FlowsenseToken[]; mapping: InjectionMapping; markerMapping: MarkerMapping; } export interface QuerySource { node: Node; port: OutputPort; } export interface QueryTarget { node: Node; port: InputPort; } /** * Generates special utterances based on the current diagram. */ export const getSpecialUtterances = (): FlowsenseCategorizedToken[] => { return utterance.getColumnNameUtterances() .concat(utterance.getNodeTypeUtterances()) .concat(utterance.getNodeLabelUtterances()) .concat(utterance.getDatasetNameUtterances()); }; /** * Replaces special utterance markers in the auto completed query by real values. * The real values are found from the datasets, or just placeholders. */ export const ejectSuggestionToken = (token: FlowsenseToken) => { if (token.chosenCategory === -1) { token.chosenCategory = 0; } const matchedColumnMarker = token.text.match(/^r_column_(.*)$/); if (matchedColumnMarker !== null) { const columns = utterance.getColumnNameUtterances(); if (columns.length) { const category = columns[randomInt(columns.length) % columns.length]; token.categories.push(category); token.chosenCategory = token.categories.length - 1; token.text = category.value[0]; } } const matchedNodeTypeMarker = token.text.match(/^r_node_type_(.*)$/); if (matchedNodeTypeMarker !== null) { const nodeTypes = utterance.getNodeTypeUtterances(); // Always use scatterplot // TODO: choose type based on action const category = nodeTypes[1]; token.categories.push(category); token.chosenCategory = token.categories.length - 1; token.text = category.displayText as string; } const matchedNodeLabelMarker = token.text.match(/^r_node_label_(.*)$/); if (matchedNodeLabelMarker !== null) { const nodeLabels = utterance.getNodeLabelUtterances(); const category = nodeLabels[randomInt(nodeLabels.length) % nodeLabels.length]; token.categories.push(category); token.chosenCategory = token.categories.length - 1; token.text = category.value[0]; } if (token.text === FlowsenseDef.NUMBER_VALUE) { token.text = '[number]'; } if (token.text === FlowsenseDef.STRING_VALUE) { token.text = '[string]'; } }; /** * Assigns a special marker for the categorized token, which will be treated as special utterance by Flowsense parser. * @param value The unique original value of the token. * @param prefix Marker prefix, e.g. "r_column_", "r_node_". * @param mapping Mapping dictionary storing all assigned markers. */ const assignMarker = (value: string, prefix: string, categorized: FlowsenseCategorizedToken, mapping: { [token: string]: string }, markerMapping: MarkerMapping): string => { if (value in mapping) { return mapping[value]; } const id = _.size(mapping) + 1; const marker = prefix + id; mapping[value] = marker; markerMapping[marker] = categorized; return marker; }; /** * Injects the query by replacing special utterances with markers that start with "r_". * The markers can be used to assist FlowSense parser. */ export const injectQuery = (tokens: FlowsenseToken[], rawQuery: string): InjectedQuery => { let query = ''; const mapping = { dataset: {}, nodeLabel: {}, column: {}, nodeType: {}, }; const markerMapping = {}; for (const token of tokens) { const categorized = token.categories[token.chosenCategory]; const category = categorized.category; let marker = token.text; if (category === FlowsenseTokenCategory.DATASET) { const value = categorized.value[0]; marker = assignMarker(value, 'r_dataset_', categorized, mapping.dataset, markerMapping); } else if (category === FlowsenseTokenCategory.NODE_LABEL) { const value = categorized.value[0]; marker = assignMarker(value, 'r_node_label_', categorized, mapping.nodeLabel, markerMapping); } else if (category === FlowsenseTokenCategory.NODE_TYPE) { const value = categorized.value[0]; marker = assignMarker(value, 'r_node_type_', categorized, mapping.nodeType, markerMapping); } else if (category === FlowsenseTokenCategory.COLUMN) { const value = categorized.value[0] + '/' + categorized.value[2]; // column name / filename (hash) marker = assignMarker(value, 'r_column_', categorized, mapping.column, markerMapping); } query += marker; } return { query, rawQuery, tokens, mapping, markerMapping, }; }; /** * Ejects a marker and returns its original categorized token. */ export const ejectMarker = (marker: string, markerMapping: MarkerMapping): FlowsenseCategorizedToken | null => { if (!(marker in markerMapping)) { return null; } return markerMapping[marker]; }; /** * Wrapper for ejectMarker that ensures that the marker is mappable. * If the marker is not an injection, such as "r_chart", "histogram" the method panics. */ export const ejectMappableMarker = (marker: string, markerMapping: MarkerMapping): FlowsenseCategorizedToken => { const result = ejectMarker(marker, markerMapping); if (result === null) { console.error(`${marker} is not in markerMapping`); } return result as FlowsenseCategorizedToken; }; /** * Parses the query source field and returns the ejected query sources. * The query sources are a list of nodes with specified ports. */ const getQuerySources = (value: QueryValue, query: InjectedQuery, tracker: FlowsenseUpdateTracker): QuerySource[] | null => { // If value does not have source, fill in the default source. // Note that a query handler may choose not to use any source (e.g. load dataset). if (!value.source) { const defaultSources = util.getDefaultSources(1); if (!defaultSources.length) { return []; // No nodes yet } const node = util.getDefaultSources(1)[0]; if (!(node as SubsetNode).getSubsetOutputPort) { return []; } return [ { node, port: (node as SubsetNode).getSubsetOutputPort() } ]; } let errored = false; const sources = value.source.map(spec => { let node: Node | undefined; if (spec.id === FlowsenseDef.DEFAULT_SOURCE) { node = util.getDefaultSources(1)[0]; } else { node = util.getNodeByLabelOrType(spec.id, query, tracker); } if (!node) { errored = true; return; } const isSelection = spec.isSelection || false; let port: OutputPort; if (isSelection) { if (!(node as Visualization).getSelectionPort) { tracker.cancel(`node ${node.getLabel()} does not have selection output`); errored = true; return; } port = (node as Visualization).getSelectionPort(); } else { if (!(node as SubsetNode).getSubsetOutputPort) { tracker.cancel(`node ${node.getLabel()} does not have subset output port`); errored = true; return; } port = (node as SubsetNode).getSubsetOutputPort(); } return { node, port }; }); if (errored) { return null; // errored } return sources as QuerySource[]; }; /** * Parses the query target field and returns the ejected query targets. * Creates the target nodes if the specification indicates new node creation. */ const getQueryTargets = (value: QueryValue, query: InjectedQuery, tracker: FlowsenseUpdateTracker): QueryTarget[] => { // A query may have no targets. if (!value.target) { return []; } let errored = false; const results = value.target.map(spec => { let node: Node | undefined; if (spec.isCreate) { let nodeType = spec.id; if (nodeType === FlowsenseDef.DEFAULT_CHART_TYPE) { // Choose default chart type here if (value.seriesColumn !== undefined || value.groupByColumn !== undefined) { // series column is present, use a line chart nodeType = 'line-chart'; } else if ((value.columns || []).indexOf(FlowsenseDef.ALL_COLUMNS) !== -1) { // If all columns are to be shown, use parallel coordinates. nodeType = 'parallel-coordinates'; } else { // There are no specified chart type. // Simply choose a chart based on the number of columns to show. // 1: histogram // 2: scatterplot // 3 or more: parallel coordinates const numColumns = value.columns ? value.columns.length : 2; nodeType = numColumns >= 3 ? 'parallel-coordinates' : (numColumns === 1 ? 'histogram' : 'scatterplot'); } } else if (nodeType === FlowsenseDef.SERIES_CHART_TYPE) { nodeType = 'line-chart'; } else { const ejected = ejectMarker(nodeType, query.markerMapping); // If the token cannot be ejected, it is a nodeType string itself. nodeType = ejected !== null ? ejected.value[0] : nodeType; } node = util.createNode(util.getCreateNodeOptions(nodeType)); tracker.createNode(node); } else { node = util.getNodeByLabelOrType(spec.id, query, tracker); if (!node) { errored = true; return; } } let port: InputPort; if ((node as SubsetNode).getSubsetInputPort) { port = (node as SubsetNode).getSubsetInputPort(); } else { port = node.getInputPort('in'); } return { node, port }; }); if (errored) { return []; } return results as QueryTarget[]; }; /** * Executes the query. Ejects the markers on the fly. */ export const executeQuery = (value: QueryValue, query: InjectedQuery) => { // TODO: complete query execution console.log('execute', value); const tracker = new FlowsenseUpdateTracker(query); const sources = getQuerySources(value, query, tracker); const targets = getQueryTargets(value, query, tracker); let message = 'create '; // undo and redo do not affect diagram layout // They do not commit an action to the history stack. if (value.undo || value.redo) { if (value.undo) { update.undo(tracker); message = 'undo'; } else if (value.redo) { update.redo(tracker); message = 'redo'; } return; } // Whether the operation results in a single chart creation. let onlyCreateChart = true; if (!sources) { return; } if (value.loadDataset) { update.loadDataset(tracker, value, query, targets); message = 'load dataset'; onlyCreateChart = false; } if (value.setOperator) { update.createSetOperator(tracker, value, query); message = 'set operator'; onlyCreateChart = false; } if (value.filters) { update.createFilter(tracker, value, query, sources, targets); message = 'filter'; onlyCreateChart = false; } if (value.visuals) { update.createOrUpdateVisualEditor(tracker, value, query, sources, targets); message = 'visual editor'; onlyCreateChart = false; } if (value.highlight) { update.createHighlightSubdiagram(tracker, value, query, sources, targets); message = 'highlight'; onlyCreateChart = false; } if (value.extract) { update.createConstantsGenerator(tracker, value, query, sources, targets); message = 'extract constants'; onlyCreateChart = false; } if (value.link) { update.linkNodes(tracker, value, query, sources, targets); message = 'link'; onlyCreateChart = false; } if (value.edge) { update.editEdge(tracker, value.edge, query); message = 'edit edge'; onlyCreateChart = false; } // Applies chart's column settings when the diagram completes. const visualizationTarget = targets.find(target => (target.node as Visualization).isVisualization); if (visualizationTarget) { update.completeChart(tracker, value, query, sources, visualizationTarget, onlyCreateChart); message += (message ? ' ' : '') + 'visualization'; } if (value.autoLayout) { update.autoLayout(tracker); } tracker.selectCreatedNodes(); tracker.autoLayoutAndCommit(message); };
the_stack